05.02. For loop

For Loop

  • Eclipse: Oxygen
  • Java: 1.8

This tutorial deals with the implementation of for loop. The for loop deals with executing the code continuously over a given range of values specified by the user.

In a programming language, a loop means repeating the execution to the instruction or instruction block with respect to the condition specified by the programmer.

Types of loops in Java

  • while loop
  • for loop
  • do-while loop

For loop

In Java for loop is used to iterate a part of the statement multiple times until a particular condition is satisfied.

Syntax

for(initialization; condition; increment/decrement)

Structure

 

In the basic structure of for loop, there exist three parts

  • Initialization of variable
  • Condition
  • Variable increment /decrement

Initialization of variable

It initializes the variable which starts the loop. It does not matter how many iterations are present. It executed only once at the beginning of the “for” loop.

Condition

It is used for testing the exit condition and returns the Boolean value true or false if the condition is true the body is executed else the loop terminates without executing the statement loop body.

The condition in the loop doesn’t have any restriction; we can use any condition and any number of comparisons.

Variable increment and decrement

The increase and decrease part of for loop is used for updating the variable for the next iteration.

Note:  All of the above is an optional component for a loop.

The following program will demonstrate syntax:

In this program int i=1 is initialization value and i<=10 is condition i++ is increment operator.

Output

1

2

3

4

5

6

7

8

9

10

In this program int i=10 is initialization value and i>=10 is condition i– is decrement operator.

Output

10

9

8

7

6

5

4

3

2

1

Infinite loop

Infinite for-loop is a set of code that repeats itself unless it is forced to stop.

Output

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Testing text

Note: Initialization, condition, increment or decrement are optional.

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments