C# program to find GCD using recursion
Here's a C# program that finds the Greatest Common Divisor (GCD) of two numbers using recursion:
using System;
class Program
{
static void Main()
{
int number1 = 48;
int number2 = 18;
int gcd = CalculateGCD(number1, number2);
Console.WriteLine("GCD of " + number1 + " and " + number2 + " is: " + gcd);
}
static int CalculateGCD(int number1, int number2)
{
// Base case: if number2 is 0, return number1 as the GCD
if (number2 == 0)
{
return number1;
}
else
{
// Recursive case: calculate the GCD by recursively calling
// CalculateGCD with number2 and the remainder of number1 divided by number2
return CalculateGCD(number2, number1 % number2);
}
}
}
In this program, we have the CalculateGCD method that takes two integers number1 and number2 as input and returns their Greatest Common Divisor (GCD).
We have a base case where if number2 is 0, we return number1 as the GCD. This is because the GCD of any number and 0 is the number itself.
In the recursive case, we calculate the GCD by recursively calling CalculateGCD with number2 and the remainder of number1 divided by number2. This is based on the Euclidean algorithm for finding the GCD.
The recursive calls continue until we reach the base case (number2 equals 0), at which point the recursion stops and the GCD is calculated.
In the example above, the output would be:
GCD of 48 and 18 is: 6
The GCD of 48 and 18 is calculated as 6.