In this tutorial, we will learn how to use for loop in Java with the help of examples.
In computer programming, loops are used to repeatedly execute a block of statements. For example, if you want to print message 100 times, then rather than typing the same code 100 times, you can use a loop.
There are three types of loops in Java:
In java for loop is used to run a block of code for a certain number of times. It is particularly used in cases where the number of iterations is fixed.
The for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
Syntax:
for(initialization expr; condition expr; update exp){
// body of the loop
// statement or code to be executed
}
// Java program to print number form 1 to 10
class Simple{
public static void main(String args[]){
for(int i = 1; i <= 10; i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
class Simple{
public static void main(String args[]){
for(int i = 1; i <= 10; i++){
System.out.println("Coder");
}
}
}
Output:
Coder
Coder
Coder
Coder
Coder
Coder
Coder
Coder
Coder
Coder
If we set the test expression in such a way that it never evaluates to false, the for loop will run forever. This is called infinite for loop.
// Infinite for Loop
class Simple{
public static void main(String args[]){
for(int i = 0; i <= 1; i--){
System.out.println(i);
}
}
}
Output:
0
-1
-2
-3
-4
-5
-6
-7
.
.
.
ctrl+c
Note: ctrl+c is used for stop the execution of this program and exit form the program.