Java While Loop: Repeating Code with Flexible Conditions
Loops are an essential part of programming, enabling repeated execution of code as long as certain conditions are met. In Java, the while
loop is a fundamental looping structure that keeps running a block of code until a specified condition becomes false
. This is especially useful when the exact number of iterations isn’t known beforehand. In this article, we’ll explore the syntax, applications, and practical exercises of the while
loop in Java.
1. What is a While Loop?
The while
loop is a control structure that repeats a block of code as long as a specified condition remains true. The loop checks the condition before executing the block of code, meaning it’s possible for the loop to skip execution if the condition is false
initially.
Basic Structure of the While Loop
while (condition) {
// Code to execute repeatedly
}
- Condition: The condition in a
while
loop must be a boolean expression (true
orfalse
). - Code Block: The code block inside the loop executes as long as the condition remains true.
Example:
int count = 1;
while (count <= 5) {
System.out.println("Count is: " + count);
count++;
}
This code will print numbers from 1 to 5. Once count
becomes 6, the condition count <= 5
becomes false
, and the loop stops.
2. How the While Loop Works
- Condition Check: Before each iteration, the
while
loop checks the condition. - Execution: If the condition is
true
, the loop executes the code block. - Update: Inside the loop, there should be some way to modify the condition, such as incrementing a variable. Without this, the loop could run indefinitely (infinite loop).
- Repeat: The loop repeats until the condition becomes
false
.
3. Infinite While Loop
If the condition in a while
loop never becomes false
, the loop will continue indefinitely. This is known as an infinite loop and is often unintentional.
Example of an Infinite Loop
int count = 1;
while (count <= 5) {
System.out.println("Infinite loop example.");
// Missing increment for count, so the condition never becomes false.
}
To avoid infinite loops, ensure there’s a statement inside the loop that can eventually make the condition false, such as count++
in the example.
4. Common Applications of While Loops
- Reading User Input: Continuously prompting the user until they provide valid input.
- Game Loops: Running a loop until the game’s conditions signal to stop.
- Data Processing: Iterating through data items, like reading records from a file until the end.
- Retry Mechanisms: Retrying actions until success or a maximum retry count is reached.
5. Variations and Patterns of the While Loop
a) Basic Counting Loop
The example we’ve seen with count
is a typical counting loop. Such loops increment a variable each time, like:
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
This loop will print numbers from 0 to 9.
b) Sentinel-Controlled Loop
A sentinel-controlled loop uses a specific value to signify when to exit the loop. This pattern is common for reading input until a specific “sentinel” value is detected.
import java.util.Scanner;
public class SentinelLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
System.out.println("Enter numbers to sum up. Enter 0 to stop.");
int sum = 0;
while ((number = scanner.nextInt()) != 0) {
sum += number;
}
System.out.println("The sum is: " + sum);
}
}
In this example, the loop continues to add numbers until the user enters 0
, which is the sentinel value.
6. Exercises
Exercise 1: Print Even Numbers from 1 to 20
Write a Java program that uses a while
loop to print all even numbers between 1 and 20.
public class EvenNumbers {
public static void main(String[] args) {
int num = 2;
while (num <= 20) {
System.out.print(num + " ");
num += 2; // Increment by 2 to keep numbers even
}
}
}
This loop will output: 2 4 6 8 10 12 14 16 18 20
Exercise 2: Simple Password Checker
Write a Java program that asks the user for a password and keeps prompting until the correct password ("java123"
) is entered.
import java.util.Scanner;
public class PasswordChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String password = "";
while (!password.equals("java123")) {
System.out.print("Enter the password: ");
password = scanner.nextLine();
if (!password.equals("java123")) {
System.out.println("Incorrect password. Try again.");
}
}
System.out.println("Password accepted!");
}
}
This program will repeatedly prompt the user until "java123"
is entered.
Exercise 3: Sum of Natural Numbers
Write a Java program to calculate the sum of all natural numbers up to a given number n
, where n
is input by the user.
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive number: ");
int n = scanner.nextInt();
int sum = 0;
int i = 1;
while (i <= n) {
sum += i;
i++;
}
System.out.println("The sum of natural numbers up to " + n + " is: " + sum);
}
}
If the user inputs 5
, the program will output 15
(since 1 + 2 + 3 + 4 + 5 = 15).
Exercise 4: Guess the Number Game
Create a number guessing game where the program generates a random number between 1 and 10, and the user must guess the number. The game continues until the correct number is guessed.
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
int targetNumber = (int) (Math.random() * 10) + 1;
Scanner scanner = new Scanner(System.in);
int guess = 0;
System.out.println("Guess the number between 1 and 10");
while (guess != targetNumber) {
System.out.print("Enter your guess: ");
guess = scanner.nextInt();
if (guess < targetNumber) {
System.out.println("Too low! Try again.");
} else if (guess > targetNumber) {
System.out.println("Too high! Try again.");
}
}
System.out.println("Congratulations! You guessed the correct number: " + targetNumber);
}
}
This program generates a random number between 1 and 10 and keeps prompting the user to guess until they get it right.
Summary
The while
loop is a flexible and powerful control structure in Java. By using it effectively, you can perform repetitive tasks with varying conditions and design interactive programs that respond to user input. Through the exercises provided, you’ve practiced using while
loops in common programming scenarios, like password checking, summing numbers, and even building a guessing game.