LCM using while Loop and if Statement
Java Programming Language Decision Making and Looping in java (Article) Decision Making and Looping in java (Program)
23
Program:
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; } } }
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:
-
Initialization:
- Two integers
n1
andn2
are initialized with values 72 and 120 respectively. - Another integer
lcm
is initialized without a value.
- Two integers
-
Finding the Maximum:
- The program compares
n1
andn2
using the ternary operator (? :
) and assigns the maximum of the two numbers to the variablelcm
. - This step ensures that the variable
lcm
initially holds the larger of the two numbers.
- The program compares
-
Calculating the LCM:
- The program enters a
while
loop with the conditiontrue
, indicating an infinite loop. - Inside the loop, it checks if
lcm
is divisible by bothn1
andn2
using the modulo operator (%
). - If
lcm
is divisible by bothn1
andn2
, it prints the LCM using theprintf
method and breaks out of the loop. - If
lcm
is not divisible by bothn1
andn2
, it incrementslcm
by 1 and continues the loop.
- The program enters a
-
Output:
- The program prints out the calculated LCM of
n1
andn2
using theprintf
method.
- The program prints out the calculated LCM of
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
.
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.