Monday, January 23, 2012

for, while do-while loops

Looping are most common in programming languages. It makes programming easier if we understand it correctly. Loops are used to repeat the execution of a set of statement that come inside the set of curly braces { } of that particular loop. There are 3 different types of looping statements- for, while and do-while. Once u understand any one of them, then the rest of them become understandable.

Consider the C++ code below

      1     2    4
for(i=0; i<5; i++)
     {
      cout<<"\n"<<i;        3
      }
(rest of the program)     5

At first the value of i will be 0. It happens by the statement i=0. This statement get executed only once i.e. when it first enters into the loop. Then it checks i<5. If it is yes then the statements inside the loop get executed otherwise the statement after the loop(rest of the program) gets executed. If the statement inside the loop is executed, then the statement i++ executed. It increments the value of i and i becomes 1 this time. Then it checks i<5 and the above mentioned steps continues till the value of i get incremented to 5. It checks i<5. That time i is not less that 5 as the value of i is 5. Then the loop exits.

The sequence of execution will be.
1234343434345

The output will be.
0
1
2
3
4

So if we need to execute a set of statement for 5 times then we should put inside the loop in part 3.

It is same with the case of while loop also, but a little bit difference in the syntax.

i=0;
while(i<5)
   {
   cout<<“\n”<<i;
   i++;
   }

The do-while loop is a bit different from the other 2 loops. It is exit controlled loop but other are entry controlled loops i.e. they perform checking when it enters the loops whereas do-while performs checking after executing the statements. It checks whether to continue the loop.
So that do-while loop performs the execution of the loop atleast once.

Code eg.

i=1;
do
   {
   cout<<i;
   i++;
   }while(i<0);

The output will be.
1

The statement inside the loop get executed once even then the value if i is not less than 0.

No comments :

Post a Comment