Loops/Repetitions in Pascal with examples
Loops are used to execute certain parts of code (statements) for a specific number of times, or until a condition is satisfied.
There are three type of loops/repetitions available in pascal.
They are
- while
- for
- repeat … until
Pascal program to print one to hundred using “while”
program onetohundredwhile;
{define variable}
var
x: integer;
{main program}
begin {start of main program}
{assign value to variable x}
x:=1;
while x<=100 do {repeat until the condition is true}
begin {start repetition}
write(x,#9);
x:=x+1;
end; {end repetition}
readln();
end.
Pascal program to print one to hundred using “for”
program onetohundredwhilefor;
var
x: integer;
{main program}
begin
for x:=1 to 100 do {no block since having one statement only}
writeln(x);
readln();
end. {end of main program}
Pascal program to print one to hundred using “repeat...until”
program onetohundredrepeatuntil;
var
x: integer;
begin {start of main program}
x:=1;
repeat {start repetition}
writeln(x);
x:=x+1;
until x>100; {repeat until the condition is false}
readln();
end. {end of main program}
Note :
- {} in pascal is used for comments, comments are not executed when program is compiled or executed.
- begin .... end; is used to make a block of statements
- readln() is used to wait until the enter key pressed to finish
- #9 for tab

No comments:
Post a Comment