Table of contents | |
Introduction | |
What is a while loop? | |
Syntax of a while loop | |
How does a while loop work? | |
Examples of while loops | |
Output | |
Sample Problems | |
Conclusion |
When writing programs, it is often necessary to repeat a set of instructions multiple times until a certain condition is met. This is where loops come into play. In Java, one of the most commonly used loops is the while loop. This article aims to provide a comprehensive guide to understanding while loops, including their syntax, working principles, and practical examples.
A while loop is a control flow statement that allows a block of code to be repeated as long as a specified condition is true. It is called a "pre-test loop" because the condition is checked before the block of code is executed. If the condition evaluates to true, the code inside the loop is executed. If the condition evaluates to false, the loop is terminated, and the program continues with the next statement.
The syntax of a while loop in Java is as follows:
while (condition) {
// code to be executed
}
The condition is a boolean expression that determines whether the loop should continue or terminate. The code inside the loop is enclosed within curly braces {}.
When a while loop is encountered, the condition is evaluated. If the condition is true, the code block is executed. Afterward, the condition is evaluated again, and if it is still true, the code block is executed again. This process continues until the condition becomes false, at which point the loop terminates, and the program moves on to the next statement.
It's important to ensure that the condition inside the while loop eventually becomes false; otherwise, the loop will run indefinitely, resulting in an infinite loop.
Let's explore some examples to illustrate how while loops work.
Example 1: Counting from 1 to 5
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
1
2
3
4
5
Explanation: In this example, we start with count initialized to 1. The condition count <= 5 is evaluated, and since it is true, the code block inside the loop is executed. The value of count is printed, incremented by 1, and the condition is evaluated again. This process repeats until count becomes 6, at which point the condition becomes false, and the loop terminates.
Example 2: Summing numbers
int sum = 0;
int number = 1;
while (number <= 10) {
sum += number;
number++;
}
System.out.println("Sum: " + sum);
Output
Sum: 55
Explanation: In this example, we initialize sum to 0 and number to 1. The loop continues as long as number is less than or equal to 10. Inside the loop, the value of number is added to sum, and number is incremented. This process repeats until number becomes 11, at which point the loop terminates. Finally, the sum is printed.
Example 3: User input validation
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int age = 0;
while (age <= 0) {
System.out.print("Enter your age: ");
age = scanner.nextInt();
if (age <= 0) {
System.out.println("Invalid age. Please enter a positive value.");
}
}
System.out.println("Valid age: " + age);
Output
Enter your age: -5
Invalid age. Please enter a positive value.
Enter your age: 25
Valid age: 25
Explanation: In this example, the program prompts the user to enter their age. The input is stored in the age variable. The loop continues as long as the value of age is less than or equal to 0. If the user enters a negative or zero value, an error message is displayed, and the loop repeats. Once the user enters a positive value, the loop terminates, and the valid age is printed.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int factorial = 1;
int i = 1;
while (i <= number) {
factorial *= i;
i++;
}
System.out.println("Factorial of " + number + " is " + factorial);
2. Modify the previous program to validate that the user enters a positive number.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int number = -1;
while (number <= 0) {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
if (number <= 0) {
System.out.println("Invalid number. Please enter a positive value.");
}
}
int factorial = 1;
int i = 1;
while (i <= number) {
factorial *= i;
i++;
}
System.out.println("Factorial of " + number + " is " + factorial);
In this article, we have explored the while loop in Java. We discussed its syntax, working principles, and provided examples demonstrating different use cases. Understanding while loops is crucial for building programs that involve repetitive tasks. By practicing and applying while loops effectively, you can create more efficient and dynamic Java programs.
60 videos|37 docs|12 tests
|
|
Explore Courses for EmSAT Achieve exam
|