Lab06 LoopsForWhile
Lab06 LoopsForWhile
while)
Looping statements in Java allow executing a block of code multiple times until a certain
condition is met.
The for loop is used when we know how many times we need to execute the loop.
Output:
The while loop is used when the number of iterations is not known but depends on a
condition.
while(condition) {
// Code to be executed
}
Output:
Printing numbers from 1 to 5 using while loop:
1
2
3
4
5
Explanation: The while loop starts with i equal to 1 and sum equal to 0.
It adds i to sum, increments i by 1, and repeats this process as long as i is
less than or equal to 5.
The do-while loop is similar to the while loop, but the condition is checked after executing
the loop body at least once. The syntax is:
do {
// Code to be executed
} while(condition);
Ensures the loop runs at least once, even if the condition is false initially.
Program using do-while Loop
class DoWhileExample {
public static void main(String[] args) {
int num = 1;
System.out.println("Printing numbers from 1 to 5 using do-while
loop:");
do {
System.out.println(num);
num++;
Looping Statements (for, while, do..while)
Output:
Printing numbers from 1 to 5 using do-while loop:
1
2
3
4
5
import java.util.Scanner;
Output:
Menu: Menu: Menu:
1. Option 1 1. Option 1 1. Option 1
2. Option 2 2. Option 2 2. Option 2
3. Exit 3. Exit 3. Exit
Enter your Enter your Enter your
choice: 1 choice: 2 choice: 3
You selected You selected Exiting...
Option 1. Option 2.
Comparison of Loops
Feature for loop while loop do-while loop
Use case When the number of When the condition Ensures at least one
iterations is known determines execution execution
Condition Before each iteration Before each iteration After each iteration
Check
Execution May execute 0 times if May execute 0 times if Always executes at
Guarantee condition is false condition is false least once
initially initially
Best Used For Counting loops Running until a When at least one
condition is met execution is needed