Java For Loop Vs While Loop Vs Do While Loop
Java For Loop Vs While Loop Vs Do While Loop
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions
become true. There are three types of loops in java.
for loop
while loop
do-while loop
Introduction The Java for loop is a control flow The Java while loop is a The Java do while loop is
statement that iterates a part of control flow statement a control flow statement
the programs multiple times. that executes a part of that executes a part of
the programs repeatedly the programs at least
on the basis of given once and the further
boolean condition. execution depends upon
the given boolean
condition.
When to use If the number of iteration is fixed, If the number of iteration If the number of iteration
it is recommended to use for loop. is not fixed, it is is not fixed and you must
recommended to use have to execute the loop
while loop. at least once, it is
recommended to use the
do-while loop.
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the
variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues
execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
Flowchart:
Example:
Test it Now
Output:
1
2
3
4
5
6
7
8
9
10
Example:
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Pyramid Example 1:
Output:
*
* *
* * *
* * * *
* * * * *
Pyramid Example 2:
Output:
* * * * * *
* * * * *
* * * *
* * *
* *
*
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array){
//code to be executed
}
Example:
Test it Now
Output:
12
23
44
56
78
Usually, break and continue keywords breaks/continues the innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Example:
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the default behavior of any loop.
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Syntax:
for(;;){
//code to be executed
}
Example:
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c