While Loop in Java

In Java, a while loop is a fundamental control flow statement used for executing a block of code repeatedly based on a condition. It continues to execute the block of code as long as the specified condition evaluates to true.


  • Basic Syntax of while Loop:
  • while (condition) {
     // Statements to be executed as long as the condition is true..
    }

    i.The condition is a boolean expression. If the condition evaluates to true, the code inside the loop will execute. If it evaluates to false, the loop will terminate, and the program will continue with the code following the loop.
    ii.The code inside the curly braces '{}' is the body of the loop. It contains the statements that you want to execute repeatedly.


  • Real-life examples :
  • 1. Question: print numbers from 1 to 7 using while loop.

    import java.util.*; class PBAINST { public static void main(String args[]) { int n = 1; while (n <= 7) { System.out.print(n+","); n++; } } }

    OUTPUT:

    1,2,3,4,5,6,7,

  • Explanation:
  • i.We initialize an integer variable 'n' to 1 outside the loop.
    ii.The while loop checks if 'n' is less than or equal to 7.
    iii.If the condition is true, it prints the value of 'n' and then increments 'n' by 1.
    iv.This process repeats until 'n' is no longer less than or equal to 7.


    Question-2:Write a program to accept a number from user and check whether its Palindrome or not. A palindrome number is a number that is same after reverse. For example 121, 34543, 343, 131, 48984 are the palindrome numbers

    import java.util.Scanner; class PBAINST { public static void main(String[] args) { Scanner scr = new Scanner(System.in); int i, n, sum = 0, temp ; System.out.println("Enter the number:"); n = scr.nextInt(); temp=n; while (n > 0) { int digit = n % 10; sum = sum * 10 + digit; n = n / 10; } if (sum == temp) { System.out.println("This is palindrome"); } else { System.out.println("Not palindrome"); } } }

    OUTPUT: Enter the number: 121 This is palindrome.

  • Practice Exercises:
  • 1. Write a program to print your name 7 times..
    2. Write a program to display all the Armstrong numbers from 1 to 1000. Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370,371 and 407 are the Armstrong numbers. 153 = (1*1*1) + (5*5*5) + (3*3*3) = 1 + 125 + 27 = 153.