Introduction
The while
and do-while
loops are control flow statements in Java that allow
repeated execution of a block of code as long as a specified condition is true. These loops are commonly
used when the number of iterations is not known beforehand.
1. The While Loop
The while
loop evaluates a condition before executing the loop body. If the condition is
true
, the loop body is executed. Otherwise, the loop terminates.
Syntax
while (condition) { // Code to be executed }
Example
int i = 1; while (i <= 5) { System.out.println("Value of i: " + i); i++; }
Output:
Value of i: 1 Value of i: 2 Value of i: 3 Value of i: 4 Value of i: 5
2. The Do-While Loop
The do-while
loop executes the loop body first and then evaluates the condition. This
ensures that the loop body is executed at least once, even if the condition is initially
false
.
Syntax
do { // Code to be executed } while (condition);
Example
int i = 1; do { System.out.println("Value of i: " + i); i++; } while (i <= 5);
Output:
Value of i: 1 Value of i: 2 Value of i: 3 Value of i: 4 Value of i: 5
Key Differences Between While and Do-While Loops
- The
while
loop checks the condition before executing the loop body, so it may not execute at all if the condition isfalse
initially. - The
do-while
loop executes the loop body first and checks the condition afterward, ensuring it runs at least once.
Examples of While and Do-While Loops
1. While Loop to Find the Sum of Numbers
int sum = 0; int i = 1; while (i <= 5) { sum += i; i++; } System.out.println("Sum: " + sum);
Output:
Sum: 15
2. Do-While Loop for User Input
Scanner scanner = new Scanner(System.in); int number; do { System.out.print("Enter a number (0 to stop): "); number = scanner.nextInt(); System.out.println("You entered: " + number); } while (number != 0);
Sample Output:
Enter a number (0 to stop): 5 You entered: 5 Enter a number (0 to stop): 3 You entered: 3 Enter a number (0 to stop): 0 You entered: 0
Unsolved Problems
- Write a program to print 1,2,3,4,5,6,7,8,9,10 using
for
loop. - Write a program to find the sum of all even numbers between 1 and 100 using a
for
loop. - Write a program to print 2,4,6,8,10 using
for
loop. - Write a program to print 1,3,5,7,9 using
for
loop. - Write a program to print 1,4,9,16,,,,81,100 using
for
loop. - Write a program to print 2,6,12,20,,,,90 using
for
loop. - Write a program to print 1/1,1/2,1/3,1/4, 1/10 using
for
loop. - Write a program to print Print the Fibonacci Sequence using
for
loop. - Write a program to generate a multiplication table for a given number using a
for
loop. - Change a given number to its reverse form. 123 will become 321 using
for
loops.