C GCD Using Recursion Program
The "GCD Using Recursion" program in C calculates the Greatest Common Divisor (GCD) of two integers using a recursive approach. The GCD of two numbers is the largest positive integer that divides both numbers without leaving a remainder.
Recursive Approach to GCD
The GCD can be calculated using the Euclidean algorithm, which is based on the following principles:
- If , then .
- Otherwise, .
Implementation of GCD Using Recursion
Here's a simple implementation of the GCD program using recursion in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: This header file is included for standard input and output functions.
Function Declaration:
int gcd(int a, int b)
: This function takes two integers,a
andb
, and returns their GCD.
Base Case:
- The base case checks if
b
is 0. If it is, the function returnsa
, as per the definition of GCD.
- The base case checks if
Recursive Case:
- If
b
is not 0, the function calls itself withb
anda % b
as arguments. This process continues untilb
becomes 0.
- If
Main Function:
- The program starts by prompting the user to enter two integers.
- It uses
scanf()
to read the input values.
Calling the Function:
- The
gcd()
function is called with the input numbers, and the result is stored in theresult
variable.
- The
Output:
- The program prints the GCD of the entered numbers.
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter two integers when prompted.
Example Input/Output
Input:
Output:
Conclusion
The "GCD Using Recursion" program in C illustrates the use of recursion to compute the greatest common divisor of two numbers. This method is efficient and concise, making it a preferred technique for solving problems that can be defined recursively. The Euclidean algorithm is particularly effective for calculating GCD, demonstrating the power of recursive functions in mathematical computations.