Looping statement is used for repeating a process. For example, if we want to write numbers from 1 to 100, we can use looping statement instead of writing a hundreds statements. In Pascal, there are three looping statements :
- for statement
- repeat statement
- while statement
We have break statement and continue statement related to repetition process.
For statement
The syntax of for statement :
- for counter := first value to last value do
- for counter := first value downto last value do
Counter is an ordinal type variable (see Delphi Tutorial # 3 : Identifier and Data Type). First value and last value are expressions which data type is the same as counter’s data type. Counter’s value will change from the first value to the last value. And in every step of counter, the statement will be executed.
Example 1 :
program Project1;{$APPTYPE CONSOLE}
uses
SysUtils;
var
number : integer;
letter : char;
begin
for number:=1 to 5 do
writeln(number);
for letter:='A' to 'E' do
writeln(letter);
for number:=5 downto 1 do
writeln(number);
for letter:='E' downto 'A' do
writeln(letter);
readln;
end.
Example 2 (adding numbers between 1 to 100) :
program Project1;{$APPTYPE CONSOLE}
uses
SysUtils;
var
i, sum : integer;
begin
sum := 0;
for i:=1 to 100 do
begin
sum := sum + i;
end;
writeln(sum);
readln;
end.
Example 3 (adding odd numbers between 1 to 100) :
program Project1;{$APPTYPE CONSOLE}
uses
SysUtils;
var
i, sum : integer;
begin
sum := 0;
for i:=1 to 100 do
begin
if Odd(i) then
sum := sum + i;
end;
writeln(sum);
readln;
end.
Example 4 (adding even numbers between 1 to 100) :
program Project1;{$APPTYPE CONSOLE}
uses
SysUtils;
var
i, sum : integer;
begin
sum := 0;
for i:=1 to 100 do
begin
if not Odd(i) then
sum := sum + i;
end;
writeln(sum);
readln;
end.
You can download the complete code here
0 comments:
Post a Comment