While Loop in Java
Introduction to Loops
Imagine you're in a candy shop and you want to keep buying candies until you've spent all your money. You check your wallet after each purchase, and as long as you have enough money left, you keep buying more candies. Once you run out of money, you stop buying candies.
In programming, loops are used to serve the purpose of repeating a specific block of code.
For instance, you want to write a line of text 100 times, so instead of manually coding the line, we can utilise a loop to accomplish this task more efficiently.
The given example is straightforward, but once you grasp the concept of loops, you can create far more engaging and complex programs.
Now, let's begin our journey into learning about loops!
While Loop
The while loop checks the condition. If it's true, it does something specific. It's a bit like when you do something only if a certain condition is met.
But the interesting part is that it checks that condition over and over again. If it's still true, it keeps doing that thing.
This keeps going until the condition is no longer true. That's when the loop stops doing its thing.
It's syntax is as follows:
while (condition) {
// code to be executed.
}
FlowChart
Seems a bit tricky? Let's see how this works with a fun example!
Example1
class Main {
public static void main(String[] args) {
// declare numberOfTimes variable.
int numberOfTimes = 1;
// code inside while loop will run infinite times.
while(numberOfTimes <= 3) {
System.out.println("Code inside while loop is running.");
}
}
}
In this program, the print statement is enclosed within the curly braces, indicating the body of the loop. When you execute this code, the print statement within the loop are repeated over and over.
Let's understand what's happening in this program:
At the beginning, the variable numberOfTimes
is set to 1. As a result, the boolean expression numberOfTimes <= 3
is evaluated to true, and the loop's body is executed.
The boolean expression numberOfTimes <= 3
is evaluated again, and since it's still true, the loop's body is executed once more.
This process continues to repeat.
Since numberOfTimes <= 3
never becomes false, the loop runs indefinitely. This is what we call an infinite loop. In this case, the code after the loop never gets executed.
Output
Code inside while loop is running.
Code inside while loop is running.
Code inside while loop is running.
.....
To run this loop only for a fixed number of times, we must increase the value of numberOfTimes
inside the loop so that numberOfTimes <= 3
eventually becomes false
. Here's how we can do:
class Main {
public static void main(String[] args) {
// declare numberOfTimes variable.
int numberOfTimes = 1;
// code inside while loop will run 3 times.
while(numberOfTimes <= 3) {
System.out.println("Code inside while loop is running.");
System.out.println("number - " + numberOfTimes);
numberOfTimes = numberOfTimes + 1;
}
System.out.println("Outside while loop body code.");
}
}
Output
Code inside while loop is running.
number - 1
Code inside while loop is running.
number - 2
Code inside while loop is running.
number - 3
Outside while loop body code.
Explanation
Variable | Condition - numberOfTimes <= 3 | Code execution=> |
---|---|---|
numberOfTimes = 1 | true | body inside the loop is executed and numberOfTimes is increased to 2. |
numberOfTimes = 2 | true | body inside the loop is executed and numberOfTimes is increased to 3. |
numberOfTimes = 3 | true | body inside the loop is executed and numberOfTimes is increased to 4. |
numberOfTimes = 4 | false | The loop ends. |
Example2
class Main {
public static void main(String[] args) {
// body inside while loop will run infinite times since the condition is always true.
while(true) {
System.out.println("Code inside while loop is running.");
}
}
}
Output
Code inside while loop is running.
Code inside while loop is running.
Code inside while loop is running.
.....
However, in most cases, we want loops to end after a certain number of iterations. Next, we will create a loop that terminates after running a specific number of times.
Let's look at another example with a slight modification of a previous program to help you understand the concept of a while loop more clear -
class Main {
public static void main(String[] args) {
// declare numberOfTimes variable.
int numberOfTimes = 1;
// code inside while loop will run 2 times.
while(numberOfTimes <= 3) {
numberOfTimes = numberOfTimes + 1;
System.out.println("Code inside while loop is running.");
System.out.println("number - " + numberOfTimes);
}
System.out.println("Outside while loop body code.");
}
}
In the above example, we increment the value of "numberOfTimes" by 1, and then we print the current value of "numberOfTimes".
Output
Code inside while loop is running.
number - 2
Code inside while loop is running.
number - 3
Code inside while loop is running.
number - 4
Outside while loop body code.
Variable | Condition - numberOfTimes <= 3 | Code execution=> |
---|---|---|
numberOfTimes = 1 | true | numberOfTimes is increased to 2, then body inside the loop is executed. |
numberOfTimes = 2 | true | numberOfTimes is increased to 3, then body inside the loop is executed. |
numberOfTimes = 3 | true | numberOfTimes is increased to 4, then body inside the loop is executed. |
numberOfTimes = 4 | false | The loop ends. |
Practice problems
Write a code to to print numbers from 5 to 1 using a while
loop.
Java code
class Main {
public static void main(String[] args) {
// declare number variable.
int number = 5;
// code inside while loop will run 5 times.
while(number >= 1) {
System.out.println(number);
number = number - 1;
}
}
}
Output
5
4
3
2
1
Write a program to find the sum of first n natural numbers using a while
loop.
Java code
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter a number:");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int sum = 0;
int count = 1;
while (count <= n) {
// adding the value of count to sum
sum = sum + count;
count = count + 1;
}
System.out.println("Total sum = " + sum);
input.close();
}
}
Output
Enter a number:
5
Total sum = 15
Explanation
Iteration | count | total | Operation |
---|---|---|---|
1 | 1 | 0+1=1 | total = 1 (total + count) |
2 | 2 | 1+2=3 | total = 3 (total + count) |
3 | 3 | 3+3=6 | total = 6 (total + count) |
4 | 4 | 6+4=10 | total = 10 (total + count) |
5 | 5 | 10+5=15 | total = 15 (total + count) |
Here, "Iteration" denotes the current iteration number. "count" represents the value of the variable during that iteration. "total" represents the running sum up to that point. "Operation" signifies the specific operation being executed during that iteration.
QUIZ
int i = 0;
for(i = 0 ; i < 10; i++){
}
System.out.println(i);
class Main {
public static void main(String[] args) {
int i = 0;
int n = 6;
while (i < n) {
System.out.print(i);
i = i + 2;
}
}
}