While Loop in Java

The while loop is used to iterate a part of the program repeatedly until the specified Boolean condition is true. As soon as the Boolean condition becomes false, the loop automatically stops.

The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is recommended to use the while loop

Syntax:

while(condition)

{

//code to be executed

increment/decrement statement

}

 

1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. When the condition becomes false, we exit the while loop.

Example:

i <=100

2. Update expression: Every time the loop body is executed, this expression increments or decrements loop variable.

Example:

i++;

 

Example

package com.practice;

import java.util.Scanner;


class Loop {

    public static void main(String[] args) {
        int sum = 0;

        // create an object of Scanner class
        Scanner input = new Scanner(System.in);

        System.out.println("Enter a number");
        int number = input.nextInt();
          
        while (number >= 0) {
         
          sum += number;

          System.out.println("Enter a number");
          number = input.nextInt();
        }
          
        System.out.println("Sum = " + sum);
        input.close();

    }

}

Output

Enter a number
21
Enter a number
34
Enter a number
5
Enter a number
-13
Sum = 60

 

No comments:

Post a Comment