LCM using while Loop and if Statement
Java Programming Language Decision Making and Looping in java (Article) Decision Making and Looping in java (Program)
96
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
n1andn2are initialized with values 72 and 120 respectively. - Another integer
lcmis initialized without a value.
- Two integers
-
Finding the Maximum:
- The program compares
n1andn2using the ternary operator (? :) and assigns the maximum of the two numbers to the variablelcm. - This step ensures that the variable
lcminitially holds the larger of the two numbers.
- The program compares
-
Calculating the LCM:
- The program enters a
whileloop with the conditiontrue, indicating an infinite loop. - Inside the loop, it checks if
lcmis divisible by bothn1andn2using the modulo operator (%). - If
lcmis divisible by bothn1andn2, it prints the LCM using theprintfmethod and breaks out of the loop. - If
lcmis not divisible by bothn1andn2, it incrementslcmby 1 and continues the loop.
- The program enters a
-
Output:
- The program prints out the calculated LCM of
n1andn2using theprintfmethod.
- 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.