Control Statements — Part 8
In this chapter, we are going to discuss for statement.
For-Loop Statement
Please read the previous chapter before reading this one. This is similar to the do-while statement. Let's see the do-while statement again and convert it to a for-loop statement. First the do-while example again:
Now let us convert the above program using the for-loop statement:
This is the simplest form of the for loop:
Following is the comparison between the while-do and for statement;
Get rakibul rushel’s stories in your inbox
Join Medium for free to get updates from this writer.
For loop:
for(;;) {
System.out.println(counter);
}If we consider the while-do example the statement inside the red box is executed once. In the case of the for statement, this is the same. The statement inside the red box is executed once. Let us modify the for loop:
for(int counter = 1;;) {
System.out.println(counter);
}Now the expression inside the while-do statement in the green box is evaluated, the same goes for the for statement. If the expression is evaluated to true the body of the for loop which contains a single statement “System.out.println(counter);” is executed. Otherwise, the next statement after the for statement executes. The for loop now:
for(int counter = 1; counter <= 3;) {
System.out.println(counter);
}After the execution of the body in the while-do statement we incremented the variable counter. The statement “counter++” is in the blue box. The same increment is included in the for loop also marked by the blue box. So, now the for statement looks like this:
for(int counter = 1; counter <= 3; counter++) {
System.out.println(counter);
}If you read and understood the previous chapter there is nothing else to say here.
The for statement steps (These are the steps you will find yourself writing mostly):
- Initialization statement (executed only once).
- Evaluate the expression
- if the expression is evaluated to be true then statements in the body of the for statement are executed and go to step 5.
- Otherwise, the next statement if any following the for statement will be executed.
- Generally, increment or decrement the variable initialized at step 1. Go to step 3.
Note: In the for statement after counter++ there is no semicolon.
There is another statement which is called for-each statement which will be discussed later in some upcoming chapter.
We discussed the for statement in its simplest form which is used mostly. There are other control statements that we are going to discuss in the next chapter called branching statements.







