Sunday 16 May 2010

Looping Statement in Delphi ( Delphi Tutorial # 11 )

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

Go to Previous Tutorial or Next Tutorial

0 comments:

Post a Comment

These links are part of a pay per click advertising program called Infolinks. Infolinks is an In Text advertising service; they take my text and create links within it. If you hover your mouse over these double underlined links, you will see a small dialog box containing an advertisement related to the text. You can choose to move the mouse away and go on with your browsing, or to click on the box and visit the relevant ad. Click here to learn more about Infolinks Double Underline Link Ads.