Programming and Java Fundamentals
While and Do-While Loops
আপনি একটি free preview lesson দেখছেন।
While and Do-While Loops
Lesson Overview
A for loop is generally useful when the number of repetitions is known in advance.
However, in many situations, we do not know beforehand exactly how many times a loop will run.
For example:
- Keep asking for input until the user provides valid input
- Keep showing a menu until the user selects the exit option
- Read data until a special value is received
- Continue a process while a condition remains true
For this kind of condition-controlled repetition, Java provides while and do-while loops.
In this lesson, we will learn:
whiledo-while- Entry-controlled and exit-controlled loops
- Counter-controlled
while - Input validation
- Sentinel values
- Menu loops
- Choosing between
for,while, anddo-while - Infinite loops
- Common loop mistakes
Learning Objectives
After completing this lesson, you will be able to:
- Explain the execution flow of a
whileloop - Run a loop while a condition remains true
- Write a counter-controlled
while - Create an input validation loop
- Use a sentinel value
- Use
do-while - Understand at-least-once execution
- Create a simple menu loop
- Choose an appropriate loop among
for,while, anddo-while - Identify common causes of infinite loops
What Is a while Loop?
while is a condition-controlled loop.
The loop body executes while the condition remains true.
Syntax:
while (condition) {
// Repeated statements
}
Example:
int number = 1;
while (number <= 5) {
System.out.println(number);
number++;
}
Output:
1
2
3
4
5
How Does while Work?
Execution flow:
- The condition is checked
- If the condition is
true, the body executes - After the body finishes, the condition is checked again
- When the condition becomes
false, the loop ends
Example:
int number = 1;
while (number <= 3) {
System.out.println(number);
number++;
}
Flow:
number = 1
1 <= 3 → true
Print 1
number becomes 2
2 <= 3 → true
Print 2
number becomes 3
3 <= 3 → true
Print 3
number becomes 4
4 <= 3 → false
Stop
while Is Entry-Controlled
A while loop checks its condition before executing the body.
int number = 10;
while (number < 5) {
System.out.println(number);
}
The condition is false from the beginning:
10 < 5 → false
Therefore, the body does not execute even once.
Counter-Controlled while
In a while loop, initialization, condition, and update are written separately.
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
Here:
Initialization
int count = 1;
Condition
count <= 5
Update
count++;
Backward Counting
int number = 5;
while (number >= 1) {
System.out.println(number);
number--;
}
Output:
5
4
3
2
1
Custom Step
int number = 0;
while (number <= 10) {
System.out.println(number);
number += 2;
}
Output:
0
2
4
6
8
10
Accumulator with while
An accumulator can be used to collect a result while a loop runs.
int number = 1;
int total = 0;
while (number <= 5) {
total += number;
number++;
}
System.out.println(total);
Output:
15
When Should You Use while?
A while loop is a good choice when:
- The repetition count is not known in advance
- The loop should continue while a condition is true
- User input controls the loop
- Input should continue until a special termination value is received
- A process should repeat until some state changes
Input Validation with while
Suppose a valid age is:
0 to 150
If the user enters an invalid age, we want to ask again.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
System.out.print(
"Enter your age: "
);
int age =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
while (age < 0 || age > 150) {
System.out.println(
"Invalid age"
);
System.out.print(
"Enter an age between 0 and 150: "
);
age =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
}
System.out.println(
"Valid age: " + age
);
scanner.close();
}
}
The Value Used by the Condition Must Be Updated
Wrong:
int age = -10;
while (age < 0 || age > 150) {
System.out.println("Invalid age");
}
age never changes.
Therefore, the condition remains true.
Result:
Infinite loop
The loop body must provide an opportunity for the condition to change.
Non-Blank Input Validation
System.out.print(
"Enter your name: "
);
String name =
scanner
.nextLine()
.strip();
while (name.isBlank()) {
System.out.println(
"Name is required"
);
System.out.print(
"Enter your name: "
);
name =
scanner
.nextLine()
.strip();
}
If the input is blank, the loop displays the prompt again.
Sentinel Value
A sentinel is a special value that signals the end of an input sequence.
Example:
Enter -1 to stop
Here:
-1
is the sentinel.
Sentinel-Controlled Loop
import java.util.Scanner;
public class Main {
static final int SENTINEL = -1;
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int total = 0;
System.out.print(
"Enter a number or -1 to stop: "
);
int number =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
while (number != SENTINEL) {
total += number;
System.out.print(
"Enter a number or -1 to stop: "
);
number =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
}
System.out.println(
"Total: " + total
);
scanner.close();
}
}
Possible interaction:
Enter a number or -1 to stop: 10
Enter a number or -1 to stop: 20
Enter a number or -1 to stop: 5
Enter a number or -1 to stop: -1
Total: 35
The sentinel is a termination signal, so it is not added to the total.
What Is a do-while Loop?
A do-while loop executes the body first, then checks the condition.
Syntax:
do {
// Repeated statements
} while (condition);
The semicolon at the end is required:
;
Basic do-while
int number = 1;
do {
System.out.println(number);
number++;
} while (number <= 5);
Output:
1
2
3
4
5
do-while Is Exit-Controlled
A do-while loop checks the condition after the body executes.
Therefore, the body executes at least once.
int number = 10;
do {
System.out.println(number);
} while (number < 5);
Output:
10
Even though the condition is false from the beginning, the body executes once.
while vs. do-while
while
while (condition) {
// Body
}
- The condition is checked first
- The body executes zero or more times
do-while
do {
// Body
} while (condition);
- The body executes first
- The condition is checked afterward
- The body executes at least once
Input Validation with do-while
Input must be taken at least once.
For this flow, do-while is natural:
Prompt
→ Read input
→ Validate
→ Repeat if invalid
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int mark;
do {
System.out.print(
"Enter a mark between 0 and 100: "
);
mark =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
if (mark < 0 || mark > 100) {
System.out.println(
"Invalid mark"
);
}
} while (mark < 0 || mark > 100);
System.out.println(
"Valid mark: " + mark
);
scanner.close();
}
}
Menu with do-while
A menu must usually be shown at least once.
Therefore, do-while is useful here.
import java.util.Scanner;
public class Main {
static final int VIEW_COURSES = 1;
static final int CREATE_COURSE = 2;
static final int EXIT = 3;
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int option;
do {
System.out.println();
System.out.println(
"1. View courses"
);
System.out.println(
"2. Create course"
);
System.out.println(
"3. Exit"
);
System.out.print(
"Choose an option: "
);
option =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
switch (option) {
case VIEW_COURSES ->
System.out.println(
"Loading courses"
);
case CREATE_COURSE ->
System.out.println(
"Opening course form"
);
case EXIT ->
System.out.println(
"Goodbye"
);
default ->
System.out.println(
"Invalid option"
);
}
} while (option != EXIT);
scanner.close();
}
}
The menu repeats until the user selects 3.
for, while, or do-while?
| Loop | Good Choice When |
|---|---|
for | Repetition count or range is known in advance |
while | Repeat while a condition remains true |
do-while | The body must execute at least once |
Use for
For example:
Print 1 to 100
Read exactly 5 marks
Traverse String indexes
Use while
For example:
Repeat until valid input is received
Read input until a sentinel is received
Process until a condition changes
Use do-while
For example:
Show a menu at least once
Read input at least once
Ask whether the user wants to continue
The Same Counter Loop: for vs. while
for:
for (int number = 1; number <= 5; number++) {
System.out.println(number);
}
Equivalent while:
int number = 1;
while (number <= 5) {
System.out.println(number);
number++;
}
For counter-based fixed repetition, for is more concise.
For condition-driven flow, while is more natural.
Infinite while Loop
Intentional infinite loop:
while (true) {
System.out.println("Running");
}
The condition is always true.
This loop does not terminate by itself.
Common Mistakes
Missing Update
Wrong:
int number = 1;
while (number <= 5) {
System.out.println(number);
}
number does not change.
Correct:
number++;
Wrong Update Direction
Wrong:
int number = 1;
while (number <= 5) {
System.out.println(number);
number--;
}
The counter moves away from making the condition false.
Correct:
number++;
Extra Semicolon
Wrong:
while (number <= 5); {
number++;
}
The semicolon creates an empty loop body.
Correct:
while (number <= 5) {
number++;
}
Assignment Instead of Boolean Logic
Wrong:
boolean active = false;
while (active = true) {
System.out.println("Running");
}
Here, true is being assigned.
Preferred:
while (active) {
System.out.println("Running");
}
Not Refreshing Input
Wrong:
String name = "";
while (name.isBlank()) {
System.out.println(
"Name is required"
);
}
name never receives a new value.
Correct:
while (name.isBlank()) {
System.out.print(
"Enter your name: "
);
name =
scanner
.nextLine()
.strip();
}
Forgetting the Semicolon After do-while
Wrong:
do {
number++;
} while (number <= 5)
Correct:
do {
number++;
} while (number <= 5);
Updating at the Wrong Position
int number = 1;
while (number <= 5) {
number++;
System.out.println(number);
}
Output:
2
3
4
5
6
If the expected output is 1–5:
while (number <= 5) {
System.out.println(number);
number++;
}
Loop Trace
int number = 1;
int total = 0;
while (number <= 3) {
total += number;
number++;
}
| Iteration | number before | total after | number after |
|---|---|---|---|
| 1 | 1 | 1 | 2 |
| 2 | 2 | 3 | 3 |
| 3 | 3 | 6 | 4 |
Final:
number = 4
total = 6
Complete Example: Validated Grade Input
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
int mark;
do {
System.out.print(
"Enter a mark between 0 and 100: "
);
mark =
Integer.parseInt(
scanner
.nextLine()
.strip()
);
if (mark < 0 || mark > 100) {
System.out.println(
"Invalid mark"
);
}
} while (mark < 0 || mark > 100);
String grade;
if (mark >= 80) {
grade = "A";
} else if (mark >= 70) {
grade = "B";
} else if (mark >= 60) {
grade = "C";
} else if (mark >= 50) {
grade = "D";
} else if (mark >= 40) {
grade = "E";
} else {
grade = "F";
}
System.out.println(
"Grade: " + grade
);
scanner.close();
}
}
Important Terms
while
Repeats the body while a condition remains true.
Entry-Controlled Loop
Checks the condition before executing the body.
do-while
Checks the condition after executing the body.
Exit-Controlled Loop
Checks the condition after the body.
Sentinel
A special value used to terminate an input sequence.
Infinite Loop
A loop that does not terminate as expected.
Loop Condition
A boolean expression that determines whether the loop should continue.
Practice Exercise 1: Count 1 to 10
Use while to print from 1 to 10.
Practice Exercise 2: Reverse Countdown
Print from 10 down to 1.
Practice Exercise 3: Even Numbers
Use while to print even numbers from 2 to 20.
Practice Exercise 4: Sum
Use while to calculate the sum from 1 to 100.
Expected:
5050
Practice Exercise 5: Valid Age
Repeat the input until the user enters a valid age.
Valid range:
0 to 150
Practice Exercise 6: Valid Mark with do-while
Repeat the prompt until a valid mark in the 0–100 range is entered.
Practice Exercise 7: Non-Blank Name
If the user provides blank input, ask for the name again.
Practice Exercise 8: Sentinel Total
The user enters numbers.
Input should end when the user enters:
-1
Calculate the total of all entered numbers except the sentinel.
Practice Exercise 9: Menu
Menu:
1. View courses
2. Create course
3. Exit
Use do-while to repeat the menu until the user exits.
Practice Exercise 10: Fix the Infinite Loop
int number = 1;
while (number <= 5) {
System.out.println(number);
}
Explain the problem and fix it.
Practice Exercise 11: Choose the Loop
Choose for, while, or do-while for each situation:
- Print exactly 10 times
- Show a menu until the user exits
- Repeat until valid input is received
- Traverse all indexes of a String
- Read exactly 5 marks
- Read numbers until a sentinel is received
Knowledge Check
Question 1
What is while?
Question 2
When is the while condition checked?
Question 3
If the condition is false from the beginning, how many times does the body execute?
Question 4
What can happen if the counter is not updated?
Question 5
What is a sentinel value?
Question 6
Should a sentinel be processed as normal data?
Question 7
When is the do-while condition checked?
Question 8
What is the minimum number of times a do-while body executes?
Question 9
Is a semicolon required at the end of do-while?
Question 10
Why is do-while useful for input validation?
Question 11
What is the main difference between for and while?
Question 12
Why is do-while useful for menus?
Question 13
What does while (true) create?
Question 14
What can an incorrect update direction cause?
Question 15
Which loop is entry-controlled?
Question 16
Which loop is exit-controlled?
Knowledge Check Answers
Answer 1
while is a loop that repeats a block of code while a condition remains true.
Answer 2
Before every iteration.
Answer 3
Zero times.
Answer 4
It can cause an infinite loop.
Answer 5
A special value used as a signal to end an input sequence.
Answer 6
No, if the sentinel is used only as the termination signal.
Answer 7
After the body executes.
Answer 8
At least once.
Answer 9
Yes.
} while (condition);
Answer 10
Because input must be read at least once before its validity can be checked.
Answer 11
for is concise for fixed or counter-based repetition. while is more natural for condition-controlled repetition.
Answer 12
Because the menu normally needs to be displayed at least once.
Answer 13
An infinite loop.
Answer 14
The counter can move away from making the condition false, causing the loop not to terminate.
Answer 15
while.
Answer 16
do-while.
Lesson Summary
In this lesson, we learned:
whilerepeats while a condition remains truewhilechecks its condition before the body- If the condition is false initially, the body may not execute at all
- In a counter-controlled
while, initialization, condition, and update are written separately - Failing to update a value related to the condition can create an infinite loop
whileis useful for input validation- A sentinel can terminate an input sequence
do-whileexecutes the body before checking the condition- A
do-whilebody executes at least once do-whilerequires a semicolon at the enddo-whileis useful for menus and at-least-once input flowsforis more concise for fixed repetitionwhileis appropriate for unknown condition-based repetition- Wrong update direction, missing updates, and extra semicolons are common loop bugs