Write a C program to calculate the LCM of two numbers

Write a C program to calculate the LCM of two numbers, In this C program example, we will see how to calculate the LCM of two numbers.

Sample input

Enter any two numbers

5

8

Sample output

LCM of 5 and 8 is: 40

What is the LCM?

LCM stands for ‘Least common multiple’ in LCM the multiple of two numbers are common in that the only least common multiple is the LCM of that numbers, for example,

the multiple of 5 = 10, 15, 20, 25, 30, 35,40, 45, 50, 55, 60, 65, 70, 75, 80 …………………..,

the multiple of 8=16, 24, 32, 40, 48, 56, 64, 72, 80, 88, ……………………,

common multiple in 5 and 8 is 40, 80, ……………..,

now, the least common factor is 40 so the LCM of 5 and 8 is 40.

Algorithm to calculate  the LCM of two numbers

  • Declare three variables.
  • Take input from the user.
  • Create logic for LCM in loop and statements.
  • Print with an appropriate message.

C program to calculate  the LCM of two numbers

#include<stdio.h>
void main (){
 int a,b,r;
   printf("enter any two number:\n");
   scanf("%d", &a);
   scanf("%d",&b);
     for(r=1;r<=a*b;r++)
    if(r % a == 0 && r % b == 0)
     break;
    printf("LCM of %d and %d is: %d",a,b,r);	
}

Explanation of this C program

Step 1: Start.

Step 2: Create h header file and include the library in it.

Step 3: Create a void main method.

Step 4: Declare three variable ( a,b,r).

Step 5: Create two inputs with the help of scanf for taking two numbers from the user.

Step 6: Create one for loop and give condition and logic of LCM, that is= ‘r=1;r<=a*b;r++’.

Step 7: Create if statement in for loop to give condition to divide the input r, (r % a == 0 && r % b == 0).

Step 8: Create a break because after executing the program the value of LCM is came out and the loop will not run again.

Step 9: Print an appropriate message with the help of printf.

Step 10: End.

The output of this C program

 

In this way, we learned how to write a C program to calculate the LCM of two numbers