Java – For loop

PREV     NEXT

For loop executes a set of statements repeatedly until a specified condition evaluates to false.

Syntax:

For loop has 3 parts

  • Initialization
  • Executes once, initializes the loop variable which causes the loop to iterate
  • Condition
  • Specifies the expression which evaluates to true / false. When this condition becomes false, the loop is terminated.
  • increment/decrement
  • Exceutes at every iteration of the loop, causes the loop variable either to increment or decrement
for (initialization; condition; increment/decrement)


{

//statements to be repeated

}

Example:


COMPILE & RUN

Output:

Number:0

Number:1

Number:2

Number:3

Number:4

Note: The 3 parts of the ‘for’ loop can be made optional if necessary. Without them, it becomes an infinite loop

Example:

COMPILE & RUN

Enhanced for – loop:

Enhanced for loop is the simpler form of the usual ‘for’ loop, usually used to iterate over an array or collection object.

Example:

COMPILE & RUN

Output:

Element of array:1

Element of array:2

Element of array:3

Element of array:4

Element of array:5

Here, each value of ‘arr’ is assigned to ‘element’ as it iterates over the loop from the index 0.

PREV     NEXT

Share this website !!!
Facebook Twitter Linkedin