Chapter 3: Control Structures
Control structures decide the flow of a program: which statements run, and how many times. Pascal has several kinds, including conditional statements and loops.
Conditional statements
If-then statement
The if-then statement runs a block of code only when a condition is true.
if condition then
statement;
Example
program IfThenExample;
var
num: integer;
begin
num := 10;
if num > 5 then
writeln('num is greater than 5');
end.
If-then-else statement
With if-then-else, a condition decides which of two blocks of code runs.
if condition then
statement1
else
statement2;
Example
program IfThenElseExample;
var
num: integer;
begin
num := 10;
if num > 15 then
writeln('num is greater than 15')
else
writeln('num is not greater than 15');
end.
Case statement
The case statement picks one block of code out of many, based on the value of a variable.
case variable of
value1: statement1;
value2: statement2;
...
else statementN;
end;
Example
program CaseExample;
var
grade: char;
begin
grade := 'B';
case grade of
'A': writeln('Excellent');
'B': writeln('Good');
'C': writeln('Fair');
'D': writeln('Poor');
'F': writeln('Fail');
else
writeln('Invalid grade');
end;
end.
Loops
A loop runs a block of code repeatedly.
For loop
The for loop runs a block of code a fixed number of times.
for variable := start_value to end_value do
statement;
Example
program ForLoopExample;
var
i: integer;
begin
for i := 1 to 10 do
writeln(i);
end.
While loop
A while loop keeps repeating its block of code as long as a condition is true.
while condition do
statement;
Example
program WhileLoopExample;
var
i: integer;
begin
i := 1;
while i <= 10 do
begin
writeln(i);
i := i + 1;
end;
end.
Repeat-until loop
The repeat-until loop runs its block of code until a condition becomes true.
repeat
statement;
until condition;
Example
program RepeatUntilExample;
var
i: integer;
begin
i := 1;
repeat
writeln(i);
i := i + 1;
until i > 10;
end.
Nested loops
You can also nest loops by placing one loop inside another.
Example
program NestedLoopExample;
var
i, j: integer;
begin
for i := 1 to 3 do
begin
for j := 1 to 3 do
begin
writeln('i = ', i, ', j = ', j);
end;
end;
end.
Breaking out of loops
The break statement exits a loop early. The continue statement skips the rest of the current iteration and moves on to the next one.
Example: using break
program BreakExample;
var
i: integer;
begin
for i := 1 to 10 do
begin
if i = 5 then
break;
writeln(i);
end;
end.
Example: using continue
program ContinueExample;
var
i: integer;
begin
for i := 1 to 10 do
begin
if i = 5 then
continue;
writeln(i);
end;
end.