Posted by: 
                                  saidesh
                                  Posted date:  
                                  
June 17, 2021
                                  /
                                
C language interview programs
                                    ,
                                  
c programming examples for beginners
- To check GCD of two numbers first we need to read input from user. i.e ask user to enter two numbers
- Store those two numbers in two integer variables
- Check if number is factor of given two numbers by iterating in for loop.
- #include <stdio.h>
- // program to check gcd of two numbers in c 
- // write a c program to find gcd of two integers
- // www.instanceofjava.com
- int main()
- {
-     int number1, number2, i, gcd;
-     // read input from user
-     printf(" please enter any two numbers: ");
-     scanf("%d %d", &number1, &number2);
 
-     for(i=1; i <= number1 && i <= number2; ++i)
-     {
-         // checking  if i is divisible by both numbers / factor of both numbers
-         if(number1%i==0 && number2%i==0)
-             gcd = i;
-     }
 
-     printf("GCD of %d and %d is %d", number1, number2, gcd);
 
-     getch();
- }
Output:
 
- #include <stdio.h>
- // Function to compute Greatest Common Divisor using Euclidean Algorithm
- int gcd(int a, int b) {
-     while (b != 0) {
-         int temp = b;
-         b = a % b;
-         a = temp;
-     }
-     return a;
- }
 
- int main() {
-     int num1, num2;
 
-     // enter  two numbers from the user
-     printf("Enter two numbers to find their GCD: ");
-     scanf("%d %d", &num1, &num2);
 
-     // Ensure numbers are positive
-     if (num1 < 0) num1 = -num1;
-     if (num2 < 0) num2 = -num2;
 
-     // Calculate and display the GCD
-     int result = gcd(num1, num2);
-     printf("The GCD of %d and %d is: %d\n", num1, num2, result);
 
-     return 0;
- }
 
Explanation:
- Input:- The user enters two numbers.
 
- Logic:- The findGCDfunction uses the Euclidean algorithm:- Replace a with b and b with a%b until b=0.
- The final value of a is the GCD.
 
 
- Output:- The program prints the GCD of the two input numbers.