Write a c program to find the GCD of two numbers using iteration and recursion

 #include <stdio.h>


// GCD using iteration (Euclidean algorithm)

int gcdIterative(int a, int b) {

    while (b != 0) {

        int temp = b;

        b = a % b;

        a = temp;

    }

    return a;

}


// GCD using recursion (Euclidean algorithm)

int gcdRecursive(int a, int b) {

    if (b == 0)

        return a;

    else

        return gcdRecursive(b, a % b);

}


int main() {

    int num1, num2;

    

    printf("Enter two numbers: ");

    scanf("%d %d", &num1, &num2);

    

    // Handle negative numbers by using absolute values

    if (num1 < 0) num1 = -num1;

    if (num2 < 0) num2 = -num2;

    

    printf("\n--- Using Iterative Method ---\n");

    int gcd1 = gcdIterative(num1, num2);

    printf("GCD of %d and %d = %d\n", num1, num2, gcd1);

    

    printf("\n--- Using Recursive Method ---\n");

    int gcd2 = gcdRecursive(num1, num2);

    printf("GCD of %d and %d = %d\n", num1, num2, gcd2);

    

    return 0;

}





Comments