Tutorials

Java Loop Control


Java for loop


We may want a statement or a block of statement to be executed for multiple times purposefully. Loop control in java allows us to achieve our purpose easily. Several loop control that java provides are:

  • For loop
  • While loop
  • Do-while loop
Loop control statement that works with above loop controls are:
  • Break statement
  • Continue statement
For loop
 
‘For loop’ is helpful when we need to execute a statement or a block of statement repeatedly and number of iteration required is known.
 
Syntax:
for (initialization; test-condition; increment or decrement){
  //code to be iterated
}

 
Example:
public class printNumbers {

	public static void main(String[] args) {

	for(int number = 0; number<5; number++){

	System.out.println(number);

	  }
       }
   }	

OUTPUT

0

1

2

3

4

 

How for loop works?

Given below is the ‘for loop’ code snippet taken from above example.
 

      initialization    condition   increment

for(int number = 0; number<5; number++){

      System.out.println(number);

}

Now let's find out the working process: 
  • In side for loop, first we initialize the variable by assigning it value.  In our case, number=0
  • Then we provide test condition which will be validated at the beginning of the each iteration.  In our case, number<5
  • If the condition evaluates to true then only the code inside the loop’s body get executed. In our case 0<5, is true so the for loop body will be executed and value stored in variable number(=0) is printed.
  • Then initialization variable will be incremented by one and again it will have to go through test condition validation. In our case, number value will be incremented from 0 to 1 and again the test condition will be validated. 
  • If test condition returns true then again loop body will get executed. In our case, since 1<5 is true so again loops body will get executed and 1 will be printed. This process will go on until test condition validation results in false.
  • If test condition returns false then control will pass outside the loop. In our case, due to continuous increment of variable ‘number‘ would reach to value of 5. Since 5<5 will fail the validation test the control will pass outside the ‘for loop’. This time body will not be executed hence 5 will not be printed. Thus we see output as 0 1 2 3 4 
  • This will mark the end of iteration of for loop.
Before we conclude this topic let's answer the following question
What is difference between i++ & ++i?
 

 



Please Share this page
Views : 114