While Loop In Java: Syntax, Flowchart, and Practical Examples

While loop is the basic looping statement in Java. It is used for executing statements repeatedly in programs. If the condition is true then the statement will be executed. When developers don’t know in advance, how many times the loop will be executed then they go for a while loop.

In this article, we will study the working of a while loop in Java. And, we also look at syntax, flowcharts, and programming examples.

What is a while loop in Java?

While loop is also called an entry-controlled loop because the condition is checked before loop execution.

If the condition is true then the body of the loop will be executed. This execution continues as long as the condition remains true.

If the condition is false then the body of the loop will be skipped and the control jumps to the outside of the loop (next statement).

Syntax

while (condition) {
    // Code to be executed repeatedly
}

Explanation

  1. while Keyword: This starts the loop and tells Java to keep checking a condition.
  2. Condition: Placed inside the parentheses(), this is a true-or-false test. If true, the loop runs. If false, the loop stops.
  3. Curly Braces {}: The code inside these braces is the loop’s body. It gets executed repeatedly as long as the condition is true.
  4. How It Works: The loop checks the condition first. If it’s true, the loop runs the code inside the braces and then checks the condition again. This repeats until the condition becomes false, and the loop stops.

Flowchart

while loop in java flowchart

let’s understand the working of a while loop with the help of a flowchart.

  1. First, control starts from the top.
  2. Then, the test condition is checked if it is true then the body of the loop will be executed.
  3. After the loop body execution, the control goes to the test condition again and now again test condition is checked if it is true again the body of the loop will be executed again.
  4. After the loop body execution a second time, again control goes to the test condition, and again the test condition is checked, suppose now the condition is false then the control jumps to outside of the while loop (means the next statement in the program).

Simple while loop program in Java

public class SimpleWhileLoop {
    public static void main(String[] args) {
        int number = 1; // Initialize the counter variable

        // While loop that runs as long as number is less than or equal to 5
        while (number <= 10) {
            System.out.println("Number: " + number); // Print the current number
            number++; // Increment the counter variable
        }
    }
}

Explanation

  1. Set-Up:
    • Start with number = 1.
  2. Loop Condition:
    • Continue looping while number is less than or equal to 10.
  3. Inside the Loop:
    • Print the current value of number.
    • Add 1 to number.
  4. Stop:
    • The loop stops when number becomes greater than 10.
  5. Finish:
    • The program ends after the loop.

Output

Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10

Prime number program using while loop in Java

public class PrimeNumberCheck {
    public static void main(String[] args) {
        int number = 29; // The number to check if it's a prime
        boolean isPrime = true; // A flag to check the prime status

        // Starting the loop with the smallest possible divisor
        int i = 2;

        // Loop to check divisibility starting from 2 up to the square root of the number
        while (i <= Math.sqrt(number)) {
            // If the number is divisible by any number other than 1 and itself
            if (number % i == 0) {
                isPrime = false; // Set the flag to false if it's divisible
                break; // Exit the loop early since we found a divisor
            }
            i++; // Increment the loop counter
        }

        // Check the flag to see if the number is prime
        if (isPrime && number > 1) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number + " is not a prime number.");
        }
    }
}

Explanation

  1. Variable Initialization:
    • int number = 29;: This is the number we want to check if it’s a prime. You can change this number to test other values.
    • boolean isPrime = true;: We start by assuming the number is prime. We’ll change this later if we find it’s not.
    • int i = 2;: We start checking from 2, the smallest prime number.
  2. while Loop:
    • while (i < number) {: The loop runs as long as i is less than the number. This means we check every number from 2 up to number - 1.
  3. Checking Divisibility:
    • if (number % i == 0) {: This checks if number is divisible by i without a remainder. If it is, then number is not a prime number.
    • isPrime = false;: If we find any number that divides, we set isPrime it to false.
    • break;: We stopped checking further since we already found a divisor.
  4. Increment the Counter:
    • i++;: We increase i to check the next number.
  5. Final Check and Output:
    • if (isPrime && number > 1) {: We check if isPrime is still true and that the number is greater than 1 (since 1 is not considered prime).
    • System.out.println(number + " is a prime number.");: This prints if the number is prime.
    • System.out.println(number + " is not a prime number.");: This prints if the number is not prime.

Output

Output
29 is a prime number.

Calculate Factorial Using while Loop in Java

import java.util.Scanner;

public class FactorialCalculator {
    public static void main(String[] args) {
        // Create a Scanner object to get input from the user
        Scanner input = new Scanner(System.in);

        // Ask the user for a number
        System.out.print("Enter a positive number to find its factorial: ");
        int number = input.nextInt(); // Read the user input

        int result = 1; // This will hold the final factorial result
        int count = 1; // Counter starting at 1

        // Calculate the factorial using a while loop
        while (count <= number) {
            result = result * count; // Multiply current count with result
            count++; // Increment the counter
        }

        // Display the result
        System.out.println("Factorial of " + number + " is: " + result);
    }
}

Explanation

  1. Import Scanner Class:
    • import java.util.Scanner;: This imports the Scanner class to take input from the user.
  2. Setting Up the Scanner:
    • Scanner input = new Scanner(System.in);: We create a Scanner object named input to read user input from the console.
  3. User Input:
    • System.out.print("Enter a positive number to find its factorial: ");: We prompt the user to enter a positive integer.
    • int number = input.nextInt();: We read the integer input from the user and store it in the number variable.
  4. Initializing Variables:
    • int result = 1;: We initialize result to 1. This variable will hold the factorial result.
    • int count = 1;: We initialize count to 1, which will be used as our loop counter.
  5. while Loop to Calculate Factorial:
    • while (count <= number) {: The loop runs as long as count is less than or equal to number.
    • result = result * count;: We multiply the current result by count and store it back in result.
    • count++;: We increment count by 1.
  6. Displaying the Result:
    • System.out.println("Factorial of " + number + " is: " + result);: We print the final factorial result to the console.

Output

Output
Enter a positive number to find its factorial: 5
Factorial of 5 is: 120

Conclusion

In this article, we’ve covered the basics of the while loop in Java, including its syntax, flowchart, and practical examples. The while loop is useful for repeating actions as long as a condition is true, making it perfect for tasks like continuously reading data or checking user input. By mastering the while loop, you can create more efficient and dynamic Java programs. Keep experimenting with different scenarios to get comfortable using the while loop, and you’ll soon find it an indispensable part of your coding toolkit.

We’d Love to Hear From You!

Do you have questions or feedback about the while loop in Java? We’re here to help! Whether you need further clarification, have suggestions, or simply want to share your thoughts, please leave a comment below. Your feedback is invaluable in helping us improve our content and support others in their learning journey. Don’t hesitate to reach out—we’re excited to hear from you!

Read More: Switch case in Java: Syntax, Flowchart, and Practical Examples

Additional Resource: Want to read more about it then go to the Oracle documentation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Aitechray