Home / Programs / LCM using while Loop and if Statement
🚀 Programming Example

LCM using while Loop and if Statement

👁 106 Views
💻 Practical Program
📘 Step Learning

📌 Information & Algorithm

💻 Program Code

public class Main {
  public static void main(String[] args) {

    int n1 = 72, n2 = 120, lcm;

    // maximum number between n1 and n2 is stored in lcm
    lcm = (n1 > n2) ? n1 : n2;

    // Always true
    while(true) {
      if( lcm % n1 == 0 && lcm % n2 == 0 ) {
        System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
        break;
      }
      ++lcm;
    }
  }
}
                        

🖥 Program Output

The LCM of 72 and 120 is 360.
                            

📘 Explanation

This Java program calculates the Least Common Multiple (LCM) of two numbers using a while loop.

Here's a breakdown of how the code works:

  1. Initialization:

    • Two integers n1 and n2 are initialized with values 72 and 120 respectively.
    • Another integer lcm is initialized without a value.
  2. Finding the Maximum:

    • The program compares n1 and n2 using the ternary operator (? :) and assigns the maximum of the two numbers to the variable lcm.
    • This step ensures that the variable lcm initially holds the larger of the two numbers.
  3. Calculating the LCM:

    • The program enters a while loop with the condition true, indicating an infinite loop.
    • Inside the loop, it checks if lcm is divisible by both n1 and n2 using the modulo operator (%).
    • If lcm is divisible by both n1 and n2, it prints the LCM using the printf method and breaks out of the loop.
    • If lcm is not divisible by both n1 and n2, it increments lcm by 1 and continues the loop.
  4. Output:

    • The program prints out the calculated LCM of n1 and n2 using the printf method.

In summary, this program calculates the LCM of two given numbers (n1 and n2) using a while loop and prints the result. It starts with the larger of the two numbers as the initial guess for the LCM and increments it until it finds a number that is divisible by both n1 and n2.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.