Java While Loop
In the world of programming, loops are essential tools that allow developers to execute a block of code repeatedly. One such loop is the humble while loop, a fundamental construct in the Java programming language. Understanding how to effectively use while loops can empower developers to create efficient and dynamic programs. The article gives a thorough introduction to the while loop in JAVA, examining its syntax, use cases and possible drawbacks.
Syntax of While Loop:
while (condition){
//code to be executed
Increment / decrement statement
}
The Anatomy of a While Loop
As long as the specified condition is true, a while loop is a control structure that repeatedly executes a block of code. The syntax of a while loop consists of three key components:
Condition: The loop’s condition is a boolean expression that is evaluated before each iteration. If the condition is true, the loop body is executed; otherwise, the loop terminates.
Loop Body: This is the code block containing the instructions to be executed repeatedly as long as the condition remains true.
Iteration: Within the loop body, there should be a mechanism to alter the loop’s condition, ensuring that it eventually becomes false. This prevents the loop from running infinitely.
While loop FlowChart:
Use Cases for While Loops:
While loops are versatile and find application in various programming scenarios, such as:
Input Validation: Continuously prompting the user for input until valid data is provided.
Iterating Through Collections: Traversing arrays, lists, or other data structures.
Dynamic Algorithms: Implementing algorithms where the number of iterations is not known beforehand.
Example 1: Countdown Timer
class DataFlairWhileLoopDemo {
public static void main(String[] args) {
int c = 10;
while (c > 0) {
System.out.println(c);
c--;
}
}
}
Output:
10
9
8
7
6
5
4
3
2
1
Time Complexity: O(n)
Auxiliary Space: O(1)
Program working:
| Iteration | Value of the variable(c) | Condition:
c>0 |
Action | Decrement:
c– |
| 1st | c=10 | 10>0
True |
10 is printed | 10 is decremented to 9 |
| 2nd | c=9 | 9>0
True |
9 is printed | 9 is decremented to 8 |
| 3rd | c=8 | 8>0
True
|
8 is printed | 8 is decremented to 7 |
| 4th | c=7 | 7>0
True |
7 is printed | 7 is decremented to 6 |
| 5th | c=6 | 6>0
True |
6 is printed | 6 is decremented to 5 |
| 6th | c=5 | 5>0
True |
5 is printed | 5 is decremented to 4 |
| 7th | c=4 | 4>0
True |
4 is printed | 4 is decremented to 3 |
| 8th | c=3 | 3>0
True |
3 is printed | 3 is decremented to 2 |
| 9th | c=2 | 2>0
True |
2 is printed | 2 is decremented to 1 |
| 10th | c=1 | 1>0
True |
1 is printed | 1 is decremented to 0 |
| 11th | c=0 | 0>0
false |
The loop Terminated |
Example 2: Factorial Calculation
class DataFlairWhileLoopDemo {
public static void main(String[] args) {
//to get user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int factorial = 1;
while (number > 0) {
factorial *= number;
number--;
}
System.out.println("Factorial: " + factorial);
}
}
Output:
Enter a number: 3
Factorial: 6
Time Complexity: O(n)
Auxiliary Space: O(1)
Example 3: Infinite Loop
class DataFlairWhileLoopDemo {
public static void main(String[] args) {
while (true) {
System.out.println("This is an infinite loop!");
}
}
}
Output:
This is an infinite loop!
This is an infinite loop!
This is an infinite loop!
This is an infinite loop!
ctrl+c
Time Complexity: Not applicable (N/A) or Infinite (∞)
Auxiliary Space: O(1)
Example 4 While Loop without Curly Braces
public class DataFlairWhileLoopDemo {
public static void main(String[] args) {
int count = 5;
while (count > 0)
System.out.println("DataFlair-Java While Loop");
count--;
}
}
Output:
DataFlair-Java While Loop
DataFlair-Java While Loop
DataFlair-Java While Loop
DataFlair-Java While Loop
ctrl+c
Time Complexity: Not applicable (N/A) or Infinite (∞)
Auxiliary Space: O(1)
Please remember that even though the indentation might suggest otherwise, the loop body without curly braces includes only the immediately following statement. In this case, only the System.out.println statement is part of the loop. The count–; statement is executed after the loop, not as part of it. To include both statements in the loop, you should use curly braces.
Do-While Loop:
The do-while loop is a control flow structure in programming that allows you to repeatedly execute a block of code as long as a specified condition is true. Unlike the while loop, the do-while loop ensures that the loop body is executed at least once before checking the condition.
Syntax of Do-while Loop:
do {
// body of loop
} while(textExpression);
Components of the do-while loop:
Do: This keyword marks the beginning of the do-while loop. The code block following the do keyword will be executed at least once, regardless of the condition.
Code to be executed: This is the block of code that you want to repeat. It can consist of one or more statements. This block of code will be executed first before checking the condition.
While: This keyword is followed by a condition enclosed in parentheses. The condition is evaluated after the loop body executes. The loop continues executing when the condition is checked as true; if it turns out to be not true, this loop will end.
Condition: This is the boolean expression that determines whether the loop should continue executing. If the condition evaluates to true, the loop will repeat; if it evaluates to false, the loop will exit.
Flow Chart Of Do-While Loop:
Key points to note about the do-while loop:
- Even if the condition is initially false, the loop body shall be executed at least once.
- The condition will be evaluated as soon as the loop is repeated.
- Be cautious with the loop condition to avoid unintended infinite loops.
Example 1: Sum of the Numbers
import java.util.Scanner;
public class DataFlairDoWhileLoopDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
int sum = 0;
do {
System.out.print("Enter a number (negative number to stop): ");
number = scanner.nextInt();
if (number >= 0) {
sum += number;
}
} while (number >= 0);
System.out.println("Sum of the entered numbers: " + sum);
}
}
Output:
Enter a number (negative number to stop): 3
Enter a number (negative number to stop): 5
Enter a number (negative number to stop): 20
Enter a number (negative number to stop): 44
Enter a number (negative number to stop): -6
Sum of the entered numbers: 72
Time Complexity: O(n)
Auxiliary Space: O(1)
Example 2: Infinite Loop
class DataFlairDoWhileLoopDemo{
public static void main(String[] args) {
do {
System.out.println("This is an infinite do while loop!");
} while (true);
}
}
Output:
This is an infinite do-while loop!
This is an infinite do-while loop!
This is an infinite do-while loop!
This is an infinite do-while loop!
Ctrl+c
Time Complexity: Not applicable (N/A) or Infinite (∞)
Auxiliary Space: O(1)
Summary:
In summary, the “while” and “do-while” loops are indispensable tools in the Java developer’s toolkit. They provide the means to control repetition, iterate over data structures, and create interactive user experiences. Mastery of these loop structures, along with a solid understanding of loop conditions and termination criteria, contributes to writing robust and maintainable code in the Java programming language.


