In Lesson 1, we saw that writeln was capable of printing text surrounded by single quotes. writeln is capable of doing a more than just printing text. writeln is capable of printing calculations too.
The Arithmetic Operators include:
+ Addition
- Subtraction
* Multiplication
/ Division
Div Integer Division
Mod Remainder
Free Pascal follows the rules of the order of operations. PEMDAS ( Please Excuse My Dear Aunt Sally):
1)Parentheses
2)Exponents
3)Multiplication
4)Division
5)Addition
6)Subtraction
In a new file, type and run the following:
begin
writeln(5 + 7);
writeln;
writeln;
writeln(‘Press <Enter> To Quit’);
readln();
end.
The computer will print:
12
We can add to the program to include subtraction, multiplication and division.
begin
writeln(5 + 7);
writeln(6 - 3);
writeln(5 * 2);
writeln(10 / 2);
writeln;
writeln(‘Press <Enter> To Quit’);
readln();
end.
Run the program and the output will be:
12
3
10
5.0000000000000E+0000
There are lots of zeros behind the five. It looks silly and confusing to have a number printed like that.
By adding a line
writeln(10 div 2);
and running the program we find that the program shows the output of 5 for the calculation. This method must be used with caution. If the calculation is 10 div 3, the computer will output 3 as the answer. This is because div is used for integer division.
One way of making the floating point numbers look presentable is to use formatting after the calculation.
Modify the division line of code as follows:
writeln(10 / 2:0:2);
After running the program, the output, for this line, is:
5.00
We can add to the program to include some problems with parentheses. this proves that Free Pascal follows the order of operations.
begin
writeln(5 + 7);
writeln(6 - 3);
writeln(5 * 2);
writeln(10 / 2:5:2);
writeln(100/3:0:2);
writeln(5 - 2 + 3);
writeln((5 - 2) + 3);
writeln(5 - (2 + 3));
writeln;
writeln;
writeln('Press <Enter> To Quit');
readln();
end.
Run the program and the output will be:
12
3
10
5.00
33.33
6
6
0
Have a little fun. Check out the cheer for PEMDAS from some smart cheerleaders:
Video: Cheer for the Order of Operations (1:29) (TeacherTube)
Somethings to try on your own:
Make a program that will calculate your own math problems
Video: Free Pascal Tutorial 2 - Printing Math - Lazarus (7:06)