Here's a C program to find LCM and GCD of the given two numbers using while loop and IF condition with output and proper explanation.

# include <stdio.h> # include <conio.h> void main() { int n1, n2, prod, gcd, lcm ; clrscr() ; printf("Enter the two numbers : ") ; scanf("%d %d", &n1, &n2) ; prod = n1 * n2 ; while(n1 != n2) { if(n1 > n2) n1 = n1 - n2 ; if(n2 > n1) n2 = n2 - n1 ; } gcd = n1 ; lcm = prod / gcd ; printf("\nThe GCD is : %d", gcd) ; printf("\n\nThe LCM is : %d", lcm); getch() ; }

**Output of above program is**

Enter the two numbers : 10 8

The GCD is : 2

The LCM is : 40

**Explanation of above program**

**GCD Calculation**-

We're calculating GCD of two numbers n1 and n2 inside the while loop. The while loop wil run until both the numbers n1 and n2 become equal. The process of gcd calculation is as follows -

- If n1 > n2 then update the value of n1 as - n1 = n1 - n2.
- If n2 > n1 then update the value of n2 as - n2 = n2 - n1.
- If n1 != n2 then repeat step 1 and 2 otherwise n1 or n2 is the value of GCD.

**LCM Calculation -**

LCM can be calculated using a simple formula -

**LCM = Product of numbers / GCD of numbers = n1 * n2 / gcd.**

Suppose, n1 = 10 and n2 = 8 then steps of GCD calculation are as follows -

- n1 > n2 i.e. 10 > 8 so n1 = n1 - n2 = 10 - 8 = 2. Therefore now, n1 = 2 and n2 = 8.
- n2 > n1 i.e. 8 > 2 so n2 = n2 - n1 = 8 - 2 = 6. Therefore now, n1 = 2 and n2 = 6.
- n2 > n1 i.e 6 > 2 so n2 = n2 - n1 = 6 - 2 = 4. Therefore now, n1 = 2 and n2 = 4.
- n2 > n1 i.e. 4 > 2 so n2 = n2 - n1 = 4 - 2 = 2. Therefore now, n1 = 2 and n2 = 2.
- Now n1 = n2 so gcd = n1 or n2 = 2.

can you please post a program to find largest of n data using recursive function?

What if the two numbers don't have a GCD? for example: 7 and 12.

it will tell me GCD is 5 but we know it doesn't have a GCD

The program will return 1 as GCD of 7 and 12.

Say n1 = 7 and n2 = 12. So,

While n1 != n2 the following steps are performed:

1) n2 > n1. So n2 = 12 - 7 = 5. n2 = 5

2) n1 > n2. So n1 = 7 - 5 = 2. n1 = 2

3) n2 > n1. So n2 = 5 - 2 = 3. n2 = 3

4) Again, n2 > n1. So, n2 = 3 - 2 = 1. n2 = 1

5) Now, n1 > n2. So, n1 = n1 - n2 = 2 - 1 = 1

Now since n1 = n2, therefore GCD is n1 or 1

That is very interesting; you are a very skilled blogger. I have shared your website in my social networks! A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article.

Php course in chennai