Table of Contents
For loop in Java language with example
In this article, we will discuss the For loop in Java language with example
Loops in Java
Java has three types of basic loops
- for loop
- while loop
- Do-while loop
for loop
The for loop used to evaluate and execute the set of Java statements repeatedly, until the test condition is false of the java program.
The for loop executes program when the Boolean expression evaluates and the condition is satisfied.
- initialization statement
- boolean expression (true / false)
- increment or decrement statement (+/_)
for loop flowchart
syntex of for loop here
- The loop begins with initialization part it is executed only once
- Then check the test expression, boolean expression may return true/false when boolean expression is true, codes inside the body of for loop is executed.
- Then control goes to increment part or decrement part and update statements is executed
- Test expression of for loop evaluates on each iteration until the boolean expression returns false.
- When the test expression is returned to false, for loop is terminated
for loop Example
Example 1
this program display 1 to 10 natural number
class forloop{
public static void main(String args[]){
for(int x=0;x<=10; x++)
{
System.out.print(x); // print in same line because use print(x);
}
}
}
out put
Example 2
This program display first ten square number, using for loop
Output
1
4
9
16
25
36
49
64
81
100
Infinite for loop
If you use two semicolons (;;) in the for loop, it will be infinitive for loop
Output
This is infinite for loop
This is infinite for loop
This is infinite for loop
This is infinite for loop
This is infinite for loop
This is infinite for loop
This is infinite for loop
Ctr+c – control the flow
Output
1
2
3
4
5
6
7
8
9
10
…
…
…Ctr+c- to exit from the flow