Loops: Loops help to execute the set of code blocks repeatedly many times till the condition is met.
Why do we need loops?
Let’s say we want to add 2 numbers which can be easily done by number1+number2
But what if there is a requirement to add 100 numbers? Well, here loops play an important role
As mentioned in the definition, the code block in the loop will run 100 times hence we’ll get the desired output, So loops are very efficient to execute the same instructions again and again.
Java Programming language has different types of loops:
- For loop
- While loop
- Do while loop
In this, we will learn about the while loop and Do while loop.
While loop:
While loop executes a code block as far as the condition specified is true.
Syntax:
How while loop works:
- The while loop evaluates the condition which is inside the parentheses after the “while” keyword
- If the condition is found to be true it will execute the block of code inside the loop
- Step 2 will occur again and again till the condition is false
- If the condition is false control will come out of the loop.
Refer to the flowchart for a better understanding
Flow chart:
Let’s see an example of how the while loop works internally:
Printing numbers from n to 1
Note: What if there is no “n- -” statement?
If there is no decrementation of n, then the while loop will execute an infinite number of times because the condition (base case to terminate loop) will never get false.
Program to print numbers from 1 to 10 in reverse order using while loop
Code:
Java Code
public class TUF {
public static void main(String[] args) {
int n = 10;
while (n > 0) {
System.out.print(n + " ");
n--; //decrementing n by 1
}
}
}
Output: 10 9 8 7 6 5 4 3 2 1
Do while loop:
Do while loop is also similar to the while loop, Do while loop also executes the statements inside the loop repeatedly till the condition turns out to be false, but the only difference is Do while loop executes the code first and then checks for the condition.
Syntax:
Flow chart:
Code:
Java Code
public class TUF {
public static void main(String[] args) {
int n = 1;
do {
System.out.println(n);
n++;
}while (n<3);
}
}
Output:
1
2
Explanation:
First, the statements present in do will be executed without checking for condition, with n = 1, so 1 will be printed and n is incremented by 1 now n is 2
After 1st iteration the condition will be checked with the current value of n, the condition turns out to be true (2<3), again do will be executed and 2 is printed and n is incremented (n=3),
Now the condition is false(3<3) so, the loop will be terminated.
Special thanks to Sai bargav Nellepalli for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article