For loop in Java with example
Loops are used to execute a set of statements repeatedly untll a particular condition is satisfied. In
Java we have tive® types of basic loops: for, while and do-hileIn ths tutorial we wil learn howto
use for loop” in lava,
‘Syntax of for loop:
or(iscsaLtzaions constion + snerenet/dacrenae)
‘
seatenert (a):
»
Flow of Execution of the for Loop
[Asa program executes, ne interpreter always keeps track of which statement Is about to be
‘executed, We call tls the contol flow, or the flow of execution ofthe program.
[Code inside Loop)
First step: n fr oop, ntilization happens frst and only one time, which means that the
Initialization pat of for loop only executes once.
‘Second step: Concition in fr loop Is evaluated on each Iteration, f the condition Is true then the
statements inside for loop body gets executed. Once the condition retums false the statements in
‘or Loop does not execute and the control gets transferred tothe next statement in the program
after fr oop.First step: In for Loop, initialization happens first and only one time, which means that the
initialization part of for Loop only executes once.
‘Second step: Concition in for loop is evaluated on each iteration, if the condition is true then the
statements inside for loop body gets executed. Once the condition returns false, the statements in
for loop does not execute and the control gets transferred to the next statement in the progrem
aftor far Inn
Third step: After every execution of for Loop’s body, the increment/decrement part of for loop
executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition Is re-evaluated.
Example of Simple For loop
class ForLoopéxanple {
public static void main(String ergst]){
. for(int
Systen-out.println("The value of i is:
Ba; A)
?
+
The output of this program is:
Je value of i de
The value of i és
vhs value of 4 ae:
The value of ¢ er
Je value of i der
The value of i és
°
7
The value of i is: 6
5
4
The value of Lis: 3
2
The value of i der
In the above program:
is initialization expression