Java While Loop Examples

Welcome to The Coding College! In this tutorial, we’ll explore practical examples of the while loop in Java. The while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

Syntax

while (condition) {
    // Code to be executed
}
  • condition: A Boolean expression evaluated before each iteration.
  • The loop continues as long as the condition is true.

Example 1: Print Numbers from 1 to 5

public class WhileExample {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 5) {
            System.out.println("Number: " + i);
            i++;
        }
    }
}

Output:

Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5

Example 2: Sum of Natural Numbers

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

        while (i <= 10) {
            sum += i; // Add i to sum
            i++;
        }

        System.out.println("Sum of numbers from 1 to 10: " + sum);
    }
}

Output:

Sum of numbers from 1 to 10: 55

Example 3: User Input Validation

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number;

        System.out.print("Enter a positive number: ");
        number = scanner.nextInt();

        while (number <= 0) {
            System.out.print("Invalid input. Enter a positive number: ");
            number = scanner.nextInt();
        }

        System.out.println("You entered: " + number);
        scanner.close();
    }
}

Output Example:

Enter a positive number: -5  
Invalid input. Enter a positive number: 0  
Invalid input. Enter a positive number: 7  
You entered: 7

Example 4: Infinite While Loop

public class InfiniteLoop {
    public static void main(String[] args) {
        int i = 1;

        while (true) {
            System.out.println("Iteration: " + i);
            i++;

            if (i > 5) {
                break; // Exit the loop when i is greater than 5
            }
        }
    }
}

Output:

Iteration: 1  
Iteration: 2  
Iteration: 3  
Iteration: 4  
Iteration: 5

Example 5: Find Factorial Using While Loop

public class FactorialWhile {
    public static void main(String[] args) {
        int number = 5;
        int factorial = 1;

        while (number > 0) {
            factorial *= number; // Multiply factorial by number
            number--;
        }

        System.out.println("Factorial: " + factorial);
    }
}

Output:

Factorial: 120

Example 6: Reverse a Number

public class ReverseNumber {
    public static void main(String[] args) {
        int number = 12345;
        int reverse = 0;

        while (number != 0) {
            int digit = number % 10;
            reverse = reverse * 10 + digit;
            number /= 10;
        }

        System.out.println("Reversed number: " + reverse);
    }
}

Output:

Reversed number: 54321

Example 7: Count Digits in a Number

public class CountDigits {
    public static void main(String[] args) {
        int number = 12345;
        int count = 0;

        while (number != 0) {
            number /= 10; // Remove the last digit
            count++;
        }

        System.out.println("Number of digits: " + count);
    }
}

Output:

Number of digits: 5

Example 8: Nested While Loops

public class NestedWhile {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 3) {
            int j = 1;

            while (j <= 3) {
                System.out.println("i = " + i + ", j = " + j);
                j++;
            }

            i++;
        }
    }
}

Output:

i = 1, j = 1  
i = 1, j = 2  
i = 1, j = 3  
i = 2, j = 1  
i = 2, j = 2  
i = 2, j = 3  
i = 3, j = 1  
i = 3, j = 2  
i = 3, j = 3

Practice Problems

  1. Write a program to calculate the sum of all even numbers between 1 and 50 using a while loop.
  2. Create a while loop to print the Fibonacci sequence up to a given number.
  3. Use a while loop to determine whether a given number is a palindrome.

Conclusion

The while loop is a fundamental tool in Java programming, enabling repetitive execution of code based on a condition. By understanding how to use it effectively, you can solve a wide variety of programming challenges.

For more Java tutorials and examples, visit The Coding College. Happy coding! 🚀

Leave a Comment