A while
loop allows your program to perform a set of instructions as long as a condition is satisfied.
Here is the structure of a while loop:
while(condition) {
instruction1
instruction2
...
}
Let's check an example:
int count = 1;
while(count <= 5) {
System.out.println("I made a mistake");
count++;
}
System.out.println("Finished!");
The output of this program is:
I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!
And this is what the computer does behind the scenes during this loop:
0. Creates and initializes a variable count = 1
1. First iteration:
a. Is count <= 5
true? <=> Is 1 <= 5
true? Yes.
b. System.out.println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 2
2. Second iteration:
a. Is count <= 5
true? <=> Is 2 <= 5
true? Yes.
b. System.out.println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 3
3. Third iteration:
a. Is count <= 5
true? <=> Is 3 <= 5
true? Yes.
b. System.out.println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 4
4. Forth iteration:
a. Is count <= 5
true? <=> Is 4 <= 5
true? Yes.
b. System.out.println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 5
5. Fifth iteration:
a. Is count <= 5
true? <=> Is 5 <= 5
true? Yes.
b. System.out.println("I made a mistake"); => Output: I made a mistake
c. count++; => count becomes 6
6. Sixth iteration:
a. Is count <= 5
true? <=> Is 6 <= 5
true? No.
b. Terminate the loop.
7. System.out.println("Finished!"); => Output: Finished!
Pro Tip:
A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.
Assignment
Let's print "I promise to learn coding"
5 times using a loop.
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the while
loop in Java, a fundamental control flow statement that allows repeated execution of a block of code as long as a specified condition is true. Understanding loops is crucial for tasks that require repetitive actions, such as iterating over data structures, performing calculations, or automating repetitive tasks.
The while
loop is one of the simplest forms of loops in Java. It repeatedly executes a block of code as long as the given condition evaluates to true. The basic syntax is:
while(condition) {
// code to be executed
}
For example, if you want to print a message five times, you can use a while
loop:
int count = 1;
while(count <= 5) {
System.out.println("I made a mistake");
count++;
}
System.out.println("Finished!");
In this example, the loop continues to execute as long as count
is less than or equal to 5. After each iteration, count
is incremented by 1.
Key concepts to understand when working with while
loops include:
Let's break down the example step-by-step:
int count = 1; // Initialization
while(count <= 5) { // Condition
System.out.println("I made a mistake"); // Loop body
count++; // Iteration
}
System.out.println("Finished!"); // Code after the loop
Here are some examples demonstrating the use of while
loops in different contexts:
int count = 5;
while(count > 0) {
System.out.println("Countdown: " + count);
count--;
}
System.out.println("Liftoff!");
This loop counts down from 5 to 1 and then prints "Liftoff!".
int sum = 0;
int number = 1;
while(number <= 10) {
sum += number;
number++;
}
System.out.println("Sum of numbers from 1 to 10 is: " + sum);
This loop calculates the sum of numbers from 1 to 10.
When using while
loops, be mindful of the following common pitfalls:
Best practices include:
Advanced techniques with while
loops include nested loops and using break
and continue
statements:
int i = 1;
while(i <= 3) {
int j = 1;
while(j <= 2) {
System.out.println("i: " + i + ", j: " + j);
j++;
}
i++;
}
This example demonstrates a nested while
loop, where the inner loop runs completely for each iteration of the outer loop.
break
and continue
int count = 1;
while(count <= 10) {
if(count == 5) {
count++;
continue; // Skip the rest of the loop body for this iteration
}
if(count == 8) {
break; // Exit the loop
}
System.out.println("Count: " + count);
count++;
}
This example uses continue
to skip an iteration and break
to exit the loop early.
Let's implement the assignment to print "I promise to learn coding" 5 times using a while
loop:
int count = 1; // Initialize the counter
while(count <= 5) { // Loop condition
System.out.println("I promise to learn coding"); // Print the message
count++; // Increment the counter
}
When debugging while
loops, consider the following tips:
To test the loop, you can write test cases that verify the expected output for different loop conditions.
When approaching problems involving loops:
Mastering the while
loop is essential for writing efficient and effective Java programs. By understanding the basics, avoiding common pitfalls, and practicing with various examples, you can become proficient in using loops to solve a wide range of problems.
For further reading and practice, consider the following resources: