The for Loop
It is a simple loop. Loop means repeating the same things again and again until the condition has been met.
It is called the simplest because all the loop control elements gathers at same place making it more convenient to use.Syntax: for(initialization expression; test expression; update expression)
body of the loop;
Program:
#include<iostream.h>#include<conio.h>
void main()
{
clrscr();
int i;
for(i=1; i<=10; i++)
cout<<i<<" ";
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10i=1: The loop starts with the initialization.As soon as the variable's value had assigned then comes the test expression.
i<=10 : it will check whether the condition is true or false. If true, it will execute the loop and then comes the update expression.
i++: this will update the value of i from 1 to 2.
Now it will check again the test expression. It will be true again so it will run the loop. This will go on until the i becomes 11. Now the test expression will become false. So the loop will terminate.
For loops are generally used for making patterns, borders etc.
No comments:
Post a Comment