Q-08: Write a C/C++ program to calculate GCD of two numbers:
(i) Using Recursion
(ii) Using Iteration
  

Recursion Using - C


#include<stdio.h> int GCD(int a, int b); void main() { int a, b; printf("Enter two Positive Integers: "); scanf("%d %d", &a, &b); printf("G.C.D of %d and %d is %d.", a, b, GCD(a, b)); } int GCD(int a, int b) { if (b != 0) return GCD(b, a % b); else return a; }

OUTPUT

Enter two Positive Integers:  40   60
G.C.D of 40 and 60 is 20.
  

Iteration Using - C


#include<stdio.h> int GCD(int a, int b); void main() { int a, b; printf("Enter two Positive Integers: "); scanf("%d %d", &a, &b); printf("G.C.D of %d and %d is %d.", a, b, GCD(a,b)); } int GCD(int a, int b) { int i, gcd; for(i=1; i <= a && i <= b; ++i) { if(a%i==0 && b%i==0) gcd = i; } return gcd; }

OUTPUT

Enter two Positive Integers:  144   24
G.C.D of 144 and 24 is 24.
        

Rescursion Using - C++


#include<iostream> using namespace std; int GCD(int a, int b); int main() { int a, b; cout<< "Enter two Positive Integers: "; cin>> a>> b; cout<< "G.C.D of "<< a<< " and "<< b<< " is "<< GCD(a,b); return 0; } int GCD(int a, int b) { if (b != 0) return GCD(b, a % b); else return a; }

OUTPUT

Enter two Positive Integers:  30  6
G.C.D of 30 and 6 is 6
  

Iteration Using - C++


#include<iostream> using namespace std; int GCD(int a, int b); int main() { int a, b; cout<< "Enter two Positive Integers: "; cin>> a>> b; cout<< "G.C.D of "<< a<< " and "<< b<< " is "<< GCD(a,b); return 0; } int GCD(int a, int b) { int i, gcd; for(i=1; i <= a && i <= b; ++i) { if(a%i==0 && b%i==0) gcd = i; } return gcd; }

OUTPUT

Enter two Positive Integers: 150   50
G.C.D of 150 and 50 is 50