In Tutorial 2 getting the computer to print math was nice. However, as the program developed, it became more difficult to tell what the answer to the question was. Imagine a program that had hundreds of math problems just printing away. The program will be nearly impossible to find the answers to the problems. What is needed is to label the answers. writeln can print text and calculations with the correct formatting syntax.
Calculations and text can be separated by using a comma.
begin
writeln('5 + 7 = ', 5 + 7);
writeln('6 - 3 = ', 6 - 3);
writeln( '5 * 2 = ', 5 * 2);
writeln('10 / 2 = ', 10 / 2:0:2);
writeln('100 / 3 = ', 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.
The output is:
5 + 7 = 12
6 - 3 = 3
5 * 2 = 10
10 / 2 = 5.00
100 / 3 = 33.33
6
6
0
The formatting looks nice, however, the spacing for the floating point calculations is not correct any more. Using formatting i.e. :0:2 can be confusing. Creating a constant space is easier to work with.
to create a constant space place these lines below Classes and above begin.
const
s = ‘ ‘;
using this formatting with writeln can change the spacing of the output.
writeln(s:3, '10 / 2 = ', s:2, 10 / 2:0:2);
Modify the program to look like this:
program FPTutorial3;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
const
s = ' ';
begin
writeln(s:3, '5 + 7 = ', 5 + 7);
writeln(s:3, '6 - 3 = ', 6 - 3);
writeln(s:3, '5 * 2 = ', 5 * 2);
writeln(s:3, '10 / 2 = ', s:2, 10 / 2:0:2);
writeln(s:3, '100 / 3 = ', 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.
The output will look like this
5 + 7 = 12
6 - 3 = 3
5 * 2 = 10
10 / 2 = 5.00
100 / 3 = 33.33
6
6
0
Somethings to try on your own:
Make a program that places the calculations in even columns.
Finish formatting the rest of the lines in the program shown in this tutorial.
Video: Free Pascal Tutorial 3 - Formatting Lines - Lazarus (5:40)