Here are five examples of Java programs that use a while loop.
Each example demonstrates a
different application of this loop.
1. Simple Counter
This program uses a while loop to print numbers from 1 to 5.
public class SimpleCounter {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count is: " + i);
i++;
}
}
}
2. Sum of Digits
This example calculates the sum of the digits of a number. The loop continues as long as the
number is greater than zero.
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum = sum + digit;
number = number / 10;
}
System.out.println("The sum of the digits is: " + sum);
}
}
3. Factorial Calculation
This program calculates the factorial of a number. The while loop multiplies the numbers in
descending order until it reaches 1.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
long factorial = 1;
int i = number;
while (i > 0) {
factorial *= i;
i--;
}
System.out.println("Factorial of " + number + " is: " +
factorial);
}
}
4. Guessing Game
This example creates a simple guessing game. The loop continues to prompt the user until they
guess the correct number.
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int secretNumber = 7;
int guess = 0;
while (guess != secretNumber) {
System.out.print("Guess a number between 1 and 10: ");
guess = scanner.nextInt();
if (guess != secretNumber) {
System.out.println("Incorrect guess. Try again!");
}
}
System.out.println("Congratulations! You guessed the correct
number.");
}
}
5. Infinite Loop (with a break condition)
This example shows an intentional infinite loop (while (true)) that can be exited using a break
statement. This is useful for loops that should run indefinitely until a specific condition is met,
like processing user commands.
import java.util.Scanner;
public class BreakExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a command (type 'exit' to quit):
");
String command = scanner.nextLine();
if (command.equalsIgnoreCase("exit")) {
System.out.println("Exiting program.");
break;
}
System.out.println("You entered: " + command);
}
}
}