As another loop, for loop is used to make any statement is executed repeatedly, as long as the condition is true, just like while loop.
But for loop has more complete format than while loop.
See the format below:
for (initialization; condition; counter) statement;
For loop has initialization and counter
1. Initialization is used to define a start value for the counter, and will be executed once.
2. Condition is checked by the program, whether it is true or false. If the condition is true, the loop will be continued, if not, the statement will be skipped.
3. Statement is the main instruction we gave to the program, and will be executed as long as the condition is true.
4. Counter is used to increase or decrease the value of the variable.
To increase use ++ and to decrease use --.
Let’s try to make a simple program, to count down start from the top number and stop at the end number that entered by the user.
See the syntax below:
#include "iostream.h"
#include "conio.h"
main ()
{
int top, end, i;
cout<< "Enter top number: "; cin>>top;
cout<< "Enter end number: "; cin>>end;
cout<< "\nOUTPUT : \n";
for (i=top; i>=end; --i)
{
cout<< i<< ", ";
}
getch();
}
See the picture as the result:
0 comments:
Post a Comment