Programming Example
Program to find GCD of two numbers using the recursive and iterative method
Program to find GCD of two numbers using the recursive and iterative method
#include<stdio.h>
int GCD(int a, int b);
int gcd(int a, int b);
main()
{
int a, b;
printf("Enter a and b : \n");
scanf("%d%d",&a, &b);
printf("%d\n",GCD(a,b));
printf("%d\n",gcd(a,b));
}/*End of main()*/
/*Recursive*/
int GCD(int a, int b)
{
if(b==0)
return a;
return GCD(b, a%b);
}/*End of GCD()*/
/*Iterative*/
int gcd(int a, int b)
{
int rem;
while(b != 0)
{
rem = a%b;
a = b;
b = rem;
}
return a;
}/*End of gcd()*/
Enter a and b :
12
15
3
3
Press any key to continue . . .
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.