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.
Test Data :
Input 1st number: 10
Input 2nd number: 50
Expected Output :

`The GCD of 10 and 50 is: 10 `

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;
}
```

Flowchart :

C Practice online:

```#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;
}```

Improve this sample solution and post your code through Disqus.

﻿