cpp code for euclids GCD

#include <iostream>

int euclideanGcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main() {
    int a, b;
    std::cout << "Enter two numbers: ";
    std::cin >> a >> b;
    std::cout << "GCD of " << a << " and " << b << " is " << euclideanGcd(a, b) << std::endl;
    return 0;
}

Step-by-Step Explanation:

  1. The code begins with the inclusion of the iostream library, which provides input and output capabilities.

  2. The function euclideanGcd is defined, which takes two integer parameters a and b and returns an integer.

  3. Inside the function, a while loop is used to calculate the GCD using the Euclidean algorithm. The loop continues until b becomes 0.

  4. Inside the loop, the value of b is stored in a temporary variable temp to avoid losing its value during the calculation.

  5. The value of b is updated to the remainder of a divided by b using the modulo operator %.

  6. The value of a is updated to the value stored in temp, which is the original value of b.

  7. Once the loop ends, the function returns the value of a, which is the calculated GCD.

  8. In the main function, two integer variables a and b are declared.

  9. The user is prompted to enter two numbers using the std::cout and std::cin statements.

  10. The GCD of the entered numbers is calculated by calling the euclideanGcd function with a and b as arguments.

  11. The result is displayed using the std::cout statement.

  12. Finally, the main function returns 0 to indicate successful execution of the program.