While Loop in Java


The while loop is Java's most fundamental loop statement. It repeats a statement or block while its controlling expression is true.The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop.

  • If the condition to true, the code inside the while loop is executed.
  • The condition is evaluated again.
  • This process continues until the condition is false.
  • When the condition to false, the loop stops.

Syntax:
   while(Condition)
   {
       // body of loop;
       // Increment (or) Decrement;
   }

This Java program prompts the user to input a number and then prints out all the integers from 1 up to that number using a while loop. Here is a breakdown of the code:

  • The program starts by importing the Scanner class to allow user input.
  • The class is defined as while_loop and the main method is declared.
  • The program prompts the user to enter a limit and waits for the user to input a number.
  • The input number is stored in the variable n.
  • The variable i is initialized to 1.
  • The while loop starts with the condition i <= n, which means that the loop will continue to run as long as the value of i is less than or equal to the value of n.
  • Inside the while loop, the program prints out the value of i using the println method.
  • The value of i is then incremented by 1 using the i++ shorthand notation.
  • The loop continues to run until the condition i <= n is no longer true.
  • Once the loop is finished, the program terminates.

Source Code

import java.util.Scanner;
 
public class while_loop {
    public static void main(String args[])
    {
        System.out.println("Enter The Limit : ");
        Scanner in =new Scanner(System.in);
        int n=in.nextInt();
        int i=1;
        while(i<=n)
        {
            System.out.println(i);
            i++;
        }
    }
}
 

Output

Enter The Limit :
10
 
1
2
3
4
5
6
7
8
9
10
To download raw file Click Here

Basic Programs