Ads 468x60px

Thursday 10 January 2013

For Loop

The mostly used loop function. It is having three parts, initialization, test expression, update expression.

Syntax

for(initialize variable; test expression; update expression)
{
  statement 1;
  statement 2;
  statement n;
}

Example
Write a program to print a number 5 times.

#include<iostream.h>
#include<conio.h>

void main()
{
  int i,j=10;
  for(i=0;i<5;i++)
  {
    cout<<j<<"\t";
  }
  getch();
}
Explanation of the program 
The control comes to the loop and initialized the variable as 0 (i=0), then it checks the expression that is true (0 is less than 5), when it founds the condition true it comes inside the loop and executes the statements within the loop, here it prints the value of variable j which is 10, now after completing the executions of the statements within the loop it goes the the third part of updating the expression which is i++, by this the value of i is incremented by 1 and the value becomes 1 (0++ = 1), now again it checks the expression and found it true (1 is less than 5) this process repeats until the expression don't become false.
Share if you liked this Post using your favorite sharing service:

Subscribe Updates, Its FREE!

 
Related Posts Plugin for WordPress, Blogger...