If you want to execute certain statements repeatedly we can go for the “for loop”. For loop is one of the control flow statements.
For Loop
The for
loop is used when the number of iterations is known beforehand.
Syntax:
for (initialization; condition; update) {
// Code to execute in each iteration
}
Example:
public class MasterBackend {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}
Explanation:
The loop starts with
i = 1
.The condition
i <= 5
is checked before each iteration.The value of
i
is incremented in each iteration.The loop executes until
i
becomes greater than 5.
While Loop
The while
loop is used when the number of iterations is not known beforehand and depends on a condition.
Syntax:
while (condition) {
// Code to execute as long as the condition is true
}
Example:
public class MasterBackend {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}
}
}
Explanation:
The loop starts with
i = 1
.The condition
i <= 5
is checked before each iteration.The value of
i
is incremented in each iteration.The loop executes until
i
becomes greater than 5.
Do-While Loop
The do-while
loop is similar to the while
loop, but it ensures that the block of code executes at least once before checking the condition.
Syntax:
do {
// Code to execute at least once
} while (condition);
Example:
public class MasterBackend {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);
}
}
Explanation:
The loop starts with
i = 1
.The block executes once before checking the condition.
The condition
i <= 5
is checked after each iteration.The loop executes until
i
becomes greater than 5.
Looping Examples
Printing Natural Numbers from 1 to 30
public class NaturalNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 30; i++) {
System.out.print(i + " ");
}
}
}
Printing Odd Numbers from 1 to 30
public class OddNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 30; i += 2) {
System.out.print(i + " ");
}
}
}
Printing Odd Numbers from 1 to 50
public class OddNumbers50 {
public static void main(String[] args) {
for (int i = 1; i <= 50; i += 2) {
System.out.print(i + " ");
}
}
}
Printing Even Numbers from 1 to 50
public class EvenNumbers {
public static void main(String[] args) {
for (int i = 2; i <= 50; i += 2) {
System.out.print(i + " ");
}
}
}