In this tutorial you will learn about the C program to calculate GCD of Two Numbers and its application with practical example.
C program to calculate GCD of Two Numbers
In this tutorial, we will learn to create a C program that will calculate the GCD of Two Numbers in C programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C Programming.
- Arithmetic Operators in C Programming.
- While Loop in the C programming.
What is the GCD of Two Numbers?
In the GCD of two numbers, it means the greatest common divisor of two numbers is the largest number that divides both of them. It can also be called the highest common factor.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variable for taking the input numbers from the user. 2. Taking the input of numbers from the user. 3. Passing that numbers to program code in conditional statements. 4. Find the greatest common divisor number. 5. Printing the greatest divisor number. 6. End The Program. |
Program Description.
In today’s program, we will first take the input numbers from the user in integer format. And after that, we will pass that variable to a for loop and the conditional statements to check the greatest common divisor of two numbers. At last, we will print the result of the greatest common divisor of those numbers to the user.
With the help of the below program, we can calculate the GCD of Two Numbers.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/* C Program to calculate GCD of Two Numbers */ #include <stdio.h> int main() { //Declaring the required variable for the program. int n1, n2, i, gcd; //n1 = input number from the user for the program. //n2 = input number from the user for the program. //gcd = it will hold the GCD of two number. //Taking the input no from the user. printf("Enter two integers: "); //Scanning the required variable for the program. scanf("%d %d", &n1, &n2); //Finding the GCD for(i=1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if(n1%i==0 && n2%i==0) gcd = i; } //Printing the output for the program. printf("G.C.D of %d and %d is %d", n1, n2, gcd); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- n1 = it will store the input integer value.
- n2 = it will store the input integer value.
- i = it will store the integer value for the loop control.
- gcd = it will hold the value for the output gcd.
Taking the input numbers from the user.
Calculating the GCD of two numbers.
Printing the output of the program.