Before coding the C program to find LCM of a two number you must know about
LCM is the lowest positive number that is perfectly divisible by both given numbers. For example, LCM of 20 and 30 is 60.
C program to calculate LCM of two number using if-else statement and while loop.
#include<stdio.h> #include<conio.h> void main() { int a, b, max; printf("\n Enter First positive number"); scanf("%d", &a); printf("\n Enter Second positive number"); scanf("%d", &b); if(a>b) { max=a; } else { max=b; } while(1) //always true { if(max%a==0&&max%b==0) { printf("\n LCM of %d and %d is %d", a, b, max); break; } max++; } getch(); } |
- In this program, the first integer given by the user is stored in the variable a.
- Similarly, the second positive number is stored in variable b.
- Moreover, the if-else statement checks the largest number between a and b the maximum number hold by the variable max.
- In each iteration the condition if(max%a==0&&max%b==0) is checked.
- If the condition does not satisfy then out of the part of if statement max++; increase the value of max by 1. And the process will be repeated until the condition satisfied.
Example:
Let the user entered First positive number is 5. It is stored in a variable. And the second number is 4. (it is stored in b variable) The part if(a>b) { max=a; } else { max=b; } Check the largest number 4 and 5 and the largest number is 5 while(1) is always true
if(max%a==0&&max%b==0) check the condition as (5%4==0&&5%5==0) it is false because 5 is not divisible by 4.
max++; Increase the value of max by 1 and 5 convert into 5+1 then the max becomes 6
Continuously, The process will be continue until the condition if(max%a==0&&max%b==0) is true.
When value of max reach 20 printf("\n LCM of %d and %d is %d", a, b, max); print the LCM of 4 and 5 is 20
break; End the program. |
C program to calculate LCM of two number greatest common divisible (GDC)
LCM = ( number 1 * number 3)/GCD
#include<stdio.h> #include<conio.h> void main() { int a, b, i, gdc, lcm; printf("\n Enter First positive number"); scanf("%d", &a); printf("\n Enter Second positive number"); scanf("%d", &b); for(i=1;i<a&&i<b;++i) { if(a%i==0&&b%i==0) { gdc = i; } } lcm = (a*b)/gdc; printf("\n LCM of %d and %d is %d", a, b, lcm); } |
Output
Download code
- In this program, the first integer given by the user is stored in the variable a.
- Similarly, the second positive number is stored in variable b.
- for(i=1;i<a&&i<b;++i) iteration executes if both a and b are exactly divisible by i.
- if(a%i==0&&b%i==0) Condition checks the a and b is exactly divisible by i. If the condition is true then the GDC is i.
- (a*b)/gdc; Find the LCM of a and b.



0 Comments
Please do not enter any spam link on comment box