What are looping statements?
Looping statements are used to execute a block of code repeatedly based on a condition.
1. for Loop: Executes a block of code a specific number of times.
Example : for Loop #
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
}
}
}
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
The for loop executes the block of code five times, incrementing i each time.
2. while Loop: Repeatedly executes a block of code as long as the condition is true.
Example : while Loop #
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
i++;
}
}
}
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
The while loop keeps executing as long as i is less than or equal to 5.
3. do-while Loop: Similar to the while loop, but the block of code is executed at least once, even if the condition is false.
Example : do-while Loop #
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("i = " + i);
i++;
} while (i <= 5);
}
}
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
The do-while loop ensures that the code block runs at least once.