The for statement allows executing a block of code a fixed number of times.
You could use a while loop to execute a block of code a fixed number of times:
1
2
3
4
5
6
7
8
9
| int i = 1;int sum = 0;// Add up numbers 1-10while (i <= 10){ sum += i; i++;} |
You can do this a little more conveniently using a for loop.
1
2
3
4
5
| int sum = 0;// Add up numbers 1-10for (int i = 1; i <= 10; i++) sum += i; |
The expression after the for keyword includes three clauses, separated by a semicolon:
- The initialization clause specifies variables to initialize before the loop starts executing
- The condition clause specifies the conditions under which the loop continues to execute
- The iteration clause specifies an operation to perform after executing the body of the loop

