for loop in java

In previous posts, we have seen while loop and Do ..while loop. In this post, we will see working of for loop.

Suppose, we have some repetitive statements that need to be executed n no. of times. A for loop can be used to executes a same set of statements with the parameters how many times those statements need to be executed.

Syntax of for loop:

for (initialization; condition ; increment) {
    Statement1
    Statement2
    .
    .
    .
    StatementN
}

In the above syntax, there are 3 parameters named as initialization, condition and increment which are separated by a semi colon (;). The statements which need to be executed comes under a pair of curly braces.

What are these initialization, condition and increment?

Intialization: 

  • It is an integer value which can be initialized like 0,1, 2, 3 etc.
  • Initialized statement is executed once.
  • IT can be called as a loop control variable.

Condition:

This parameter determines until when loop need to be executed. It is nothing but an expression or condition which returns true or false. It it is true loop continues executing else false.

increments:

This parameters is used to increment or decrements the value of control variable of the loop. We can increment value by using (variable++) and decrements value by using (variable–).

Let’s see an example of for loop with increment value: 

public class ForLoopEx {

	public static void main(String[] args) {
		for(int i=0; i< 5; i++){
			System.out.println("The number is "+i);
		}	        
	}
}
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

In the above example, we have initialized the variable ‘i’ to 0. The condition is given like “executes the loop until i is less than 5. The value of i is incremented by 1 with each execution of the loop.


 

Let’s see an example of for loop with decrements value: 

public class ForLoopEx {

	public static void main(String[] args) {
		for(int i=5; i>=0; i--){
			System.out.println("The number is "+i);
		}	        
	}
}
Output:
The number is 5
The number is 4
The number is 3
The number is 2
The number is 1
The number is 0

In the above example, we are running the loop in reverse order. So, we have initialized variable ‘i’ as 5 and checking the condition “executes loop until i is equal and greater than 0”. The value of i is decremented by 1 with each execution of the loop.

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 10, 2015

    […] the previous post, we have seen the working of for loop. In this post, we will learn about for each […]