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:

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: 

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: 

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
Do while loop in java
for each loop in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

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 […]