Deitel C++ How To Program 9th Edition Chapter 6 Exercise 6.41

15 Jul 2024 - Syed Muhammad Shahrukh Hussain

Write a program which inputs two integer and calculate GCD (Greatest Common Divisor).

Terminal

Input number 1:10
Input number 2:6
GCD:2

Solution

#include <iostream>

using namespace std;

int gcd(int x, int y);

int main() {
  int input1;
  int input2;

  cout << "Input number 1:";
  cin >> input1;
  cout << "Input number 2:";
  cint >> input2;
  cout << "GCD:" << gcd(input1, input2) << endl;
  return 0;
}

int gcd(int x, int y) {
  if (y == 0) {
    return x;
  } else {
    return gcd(y, x % y);
  }
}

Sources