Programs

C++ Program to Find GCD

C++ Program to Find GCD

The Greatest Common Divisor (GCD), also known as the Greatest Common Factor (GCF), of two or more integers is the largest positive integer that divides each of the integers without a remainder. For two integers ( a ) and ( b ), the Euclidean algorithm is a common way to find their GCD.

Here’s a Turbo C++ program that calculates the GCD of two numbers using the Euclidean algorithm:

#include <iostream.h>
#include <conio.h>

// Function to find GCD of two numbers
int gcd(int a, int b) {
    if (b == 0)
        return a;
    else
        return gcd(b, a % b);
}

void main() {
    clrscr();  // Clear the screen (specific to Turbo C++)

    int num1, num2;

    // Input two numbers from the user
    cout << "Enter first number: ";
    cin >> num1;

    cout << "Enter second number: ";
    cin >> num2;

    // Call the gcd function and display the result
    cout << "GCD of " << num1 << " and " << num2 << " is " << gcd(num1, num2) << endl;

    getch();  // Wait for user input (specific to Turbo C++)
}

To compile and run this program in Turbo C++:

  1. Open Turbo C++.
  2. Create a new file and copy-paste the above code into it.
  3. Save the file.
  4. Compile the code (usually by pressing Alt + F9).
  5. Run the program (usually by pressing Ctrl + F9).

After entering two integers, the program will display their GCD.