Control structures are fundamental in programming, allowing you to control the flow of your program based on conditions and loops. Pascal provides several types of control structures, including conditional statements and loops.
The if-then
statement is used to execute a block of code only if a specified condition is true.
if condition then
statement;
program IfThenExample;
var
num: integer;
begin
num := 10;
if num > 5 then
writeln('num is greater than 5');
end.
The if-then-else
statement allows you to choose between two blocks of code to execute based on a condition.
if condition then
statement1
else
statement2;
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.
The case
statement is used to execute one block of code out of many based on the value of a variable.
case variable of
value1: statement1;
value2: statement2;
...
else statementN;
end;
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 are used to execute a block of code repeatedly.
The for
loop is used to execute a block of code a fixed number of times.
for variable := start_value to end_value do
statement;
program ForLoopExample;
var
i: integer;
begin
for i := 1 to 10 do
writeln(i);
end.
The while
loop is used to execute a block of code as long as a condition is true.
while condition do
statement;
program WhileLoopExample;
var
i: integer;
begin
i := 1;
while i <= 10 do
begin
writeln(i);
i := i + 1;
end;
end.
The repeat-until
loop is used to execute a block of code until a condition becomes true.
repeat
statement;
until condition;
program RepeatUntilExample;
var
i: integer;
begin
i := 1;
repeat
writeln(i);
i := i + 1;
until i > 10;
end.
You can also nest loops, meaning you can place one loop inside another.
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.
Pascal provides the break
statement to exit a loop prematurely and the continue
statement to skip the remaining code in the current iteration and proceed to the next iteration of the loop.
program BreakExample;
var
i: integer;
begin
for i := 1 to 10 do
begin
if i = 5 then
break;
writeln(i);
end;
end.
program ContinueExample;
var
i: integer;
begin
for i := 1 to 10 do
begin
if i = 5 then
continue;
writeln(i);
end;
end.