w3resource logo
C Programming Exercises

C Exercises: Find GCD of two numbers

C Recursion : Exercise-7 with Solution

Write a program in C to find GCD of two numbers using recursion.

Sample Solution:

C Code:

#include<stdio.h>

int findGCD(int num1,int num2);
int main()
{
  int num1,num2,gcd;
  printf("\n\n Recursion : Find GCD of two numbers :\n");
  printf("------------------------------------------\n");  
  printf(" Input 1st number: ");
  scanf("%d",&num1);
  printf(" Input 2nd number: ");
  scanf("%d",&num2);
  
  gcd = findGCD(num1,num2);
  printf("\n The GCD of %d and %d is: %d\n\n",num1,num2,gcd);
  return 0;
}

int findGCD(int a,int b)
{
     while(a!=b)
     {
          if(a>b)
              return findGCD(a-b,b);
          else
             return findGCD(a,b-a);
     }
     return a;
}

Sample Output:

 Recursion : Find GCD of two numbers :                                                                        
------------------------------------------                                                                    
 Input 1st number: 10                                                                                         
 Input 2nd number: 50                                                                                         
                                                                                                              
 The GCD of 10 and 50 is: 10

Flowchart:

Flowchart: Find GCD of two numbers.

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.