# C Program to Find GCD and LCM of Two Numbers

Howdy readers, today you will learn how to write a program to find the gcd and lcm of two numbers using the C Programming language.

The Greatest Common Divisor (GCD) of two numbers is the largest possible number which divides both the numbers exactly. For example: The GCD of 15 and 30 is 5.

The Least Common Multiple (LCM) of two or more numbers is the smallest number among all common multiples of the given numbers. For example: The LCM of 2 and 5 is 10.

In the below program, we compute the gcd using for loop and lcm with the help of below formula.

• LCM(a, b) = (a x b) / GCD(a, b)

So, without any delay, let’s begin this tutorial.

## C Program to Find GCD and LCM of Two Numbers

C Program

```// C Program to Find GCD and LCM of Two Numbers
#include <stdio.h>
int main(){
int num1, num2, gcd, lcm;

printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);

// Calculating the gcd
for (int i = 1; i <= num1 && i <= num2; i++){
if (num1 % i == 0 && num2 % i == 0){
gcd = i;
}
}

// Calculating the lcm
lcm = (num1 * num2) / gcd;

// Displaying result
printf("GCD of %d and %d is: %d \n", num1, num2, gcd);
printf("LCM of %d and %d is: %d", num1, num2, lcm);

return 0;
}
```

Output

```Enter the first number: 15
Enter the second number: 100
GCD of 15 and 100 is: 5
LCM of 15 and 100 is: 300
```

Explanation

```    int num1, num2, gcd, lcm;
```

In the above example, we have declared four int data type variables named `num1`, `num2`, `gcd` and `lcm`.

```    // Asking for input
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
```

The user is asked to enter two numbers. These values get stored in the `num1` and `num2` named variables.

```    // Calculating the gcd
for (int i = 1; i <= num1 && i <= num2; i++){
if (num1 % i == 0 && num2 % i == 0){
gcd = i;
}
}
```

GCD is calculated using `for loop` statement.

```    // Calculating the lcm
lcm = (num1 * num2) / gcd;
```

Similarly, the lcm is calculated using the formula lcm(a, b) = (a x b) / gcd(a, b).

```    // Displaying result
printf("GCD of %d and %d is: %d \n", num1, num2, gcd);
printf("LCM of %d and %d is: %d", num1, num2, lcm);
```

The GCD and LCM calculated above is printed on the screen using printf() function.

## Conclusion

I hope after reading this post, you get to know how to write a program to find the gcd and lcm of two numbers using the C Programming language.

If you have any doubt regarding the tutorial, then let us know in the comment section. We will be pleased to solve all of your queries.