Loops in Java | Java while loop with examples | Loop Control | Control Statements

 As we know loops in Java, are most used when there is a need to repeat a block of statements for a certain number of times. Previously, we discussed about For loops, But in this tutorial we would be referring to while loop, which is an important aspect of Control statements.

Java while loop

While loop is also a control flow statement like for loop, it also do the same work, i.e to repeatedly execute a given block of statements on the basis of given condition. It works similarly to for loop, but here, we are unaware about the total number iterations that would take place. And this loop also continues until the condition gets false.

Syntax:

intialization
while (condition) {
  // code block to be executed
  increment/decrement;
}

Example: 

int i=1;
while(i<=10){
// code block to be executed
i++;
}

How while loop works !


In the syntax of while loop, initialization is done, before going into the loop block, and in the condition checking part, a Boolean condition is provided, which executes the below statements until the condition gets falsed. Even the increment/decrement we used to do, in the for loop bracket , here is done inside the loop body. 
For example:

class Main{
public static void main(String[] args){
int i = 0;
while(i<5){
System.out.println("Programmer Studios");
i++;
}
}
}

OUTPUT
Programmer Studios
Programmer Studios
Programmer Studios
Programmer Studios
Programmer Studios

Here in this example, as the program starts, i is initialized with 0, before entering the loop block. and when the loop block is encountered, condition is checked at that moment, like here, it is checked whether i<5 or not. If condition is true, then the inner body will be executed, else not. Like here, for i=0, condition i<5 is true, so control goes inside the loop. And prints Programmer Studios and after that, i is incremented, and i becomes 1. Since this was the last statement in the loop, So now again, control goes to the condition checking part, and checks the condition for i=1, and again the loop body executes and same process is followed until condition becomes false.

As we can see, In the while loop, the condition is checked before entering the loop, thatswhy it is also known as ENTRY CONTROL LOOP.

while loop as an inifinite loop

public class whileLoopAsInfiniteLoop {

public static void main(String[] args) {
int i;
i=1;
while(i<=10) {
System.out.println("Programmer Studios");
i--;
}

}

}

In this example, due to the wrong increment/decrement statement, the simple while loop is now converted into an infinite loop, and hence, its output would be inifinite no. of times "Programmer Studios"

public class whileLoopAsInfiniteLoopExample2 {  
public static void main(String[] args) {  
    while(true){  
        System.out.println("Programmer Studios");  
    }  
}  
}  

This would also cause an infinite loop, because the condition we gave in the while brackets says to continue executing the statements infinitely as the boolean expression provided in the condition part is not going to change anyways.

* This doesn't mean that we can also give false in the condition part, it would generate an error to remove this block of code. And it would be of no use to us.

Simple problems using while loop

Program 1:  WAP to find the sum of n numbers.

public class sumOfNNumbers {

    public static void main(String[] args) {
        int n = 234;
        int sum = 0;
        int i = 1;
        while(i<=n) {
            sum += i;
            i++;
        }
        System.out.println("sum is "+ sum);

    }

}

OUTPUT

sum is 27495

Program 2:  WAP to find the number of digits in a given number.

public class numberOfDigitsByWhileLoop {

    public static void main(String[] args) {
        int n = 123245;
        
        int digits=0;
        while(n!=0) {
            digits++;
            n/=10;
        }
        System.out.println(digits);

    }

}

OUTPUT

6

Program 3:  WAP to reverse the given number.

public class reverseOfANumberUsingWhileLoop {

    public static void main(String[] args) {
        int n = 12345;
        int rev = 0;
        while (n>0) {
            int last_digit = n%10;
            rev = rev*10 + last_digit;
            n/=10;
        }
        System.out.println(rev);
    }

}

OUTPUT

54321

Program 4:  WAP to reverse a string using while loop.

class reverseTheString
{
    public static void main(String[] args)
    {
    String str;
    str = "ProgrammerStudios";
    System.out.println("Reverse of a String '"+str+"' is  :"); 
    int i=str.length();
    while(i>0)
    {
    System.out.print(str.charAt(i-1)); 
    i--;
    }
        }
}

OUTPUT

soidutSremmargorP

Program 5:  WAP to find the factorial of a number using while loop.

class factorial{
    public static void main(String[] args){
        int n = 5;
        int fact = 1;
        while(n!=0){
            fact = fact * n;
            n--;
        }
        System.out.println(fact);
    }
}

OUTPUT

120

Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post