The for Statement
Finally let us cover the for Statement.
Three separate parts control a loop:
- an initialization,
- a continuation condition, and
- an update.
You'll see what I'm talking about when you see the code.
The syntax for the for statement is
for (initialization; continuation condition; update) statement;
The initialization, the continuation condition, or the update may be empty.
Here is an example:
 | |  | | | #include <iostream.h>
int main()
{
int n1, sum;
cout << "Enter a number to be counted: ";
cin >> n1;
for(int i = 0; i < n1; i++)
{
sum = i+1;
cout << sum << "n";
}
return 0;
} |
|  |
|
This program will ask the user to enter a number, and then once it receives the number it will count up to that number and stop. Here the initialization is int i = 0, the continuation condition is i < n1, and the update is i++. In the for loop, the sum is the counter i + 1, each time it goes threw the loop it will add one to the sum. The first time around the sum is changed to 1, the 2nd time it is 2 and so on. Please Rate this Code: