Pages

Tuesday, 16 June 2015

GCD of N numbers using recursion

GCD of N numbers using recursion

Coding:

#include<stdio.h>
int gcd(int a,int b)
{
if(a%b==0)
return b;
else
return gcd(b,a%b);
}
void main()
{
int no1,no2,n,i;
printf("Please enter the number of terms(>1):");
scanf("%d",&n);
for(i=0;i<n-1;i++)
{
if(i==0)
{
printf("\nPlease enter the number %d:",i+1);
scanf("%d",&no1);
}
printf("Please enter the number %d:",i+2);
scanf("%d",&no2);
no1=gcd(no1,no2);
}
printf("GCD is %d",no1);
}

Output:
Please enter the number of terms(>1):4

Please enter the number 1:4
Please enter the number 2:12
Please enter the number 3:6
Please enter the number 4:8
GCD is 2