Write a program in C to find the GCD of two numbers using recursio
Question
Write a program in C to find the GCD of two numbers using recursio
Solution
Sure, here is a simple C program that uses recursion to find the Greatest Common Divisor (GCD) of two numbers:
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("GCD of %d and %d is %d", num1, num2, gcd(num1, num2));
return 0;
}
Here's how it works:
- The
gcdfunction takes two integers as arguments. - If the second number (
b) is 0, it returns the first number (a) as the GCD. - If
bis not 0, it calls itself withband the remainder ofadivided bybas the new arguments. - This process repeats until
bis 0, at which point the function returnsaas the GCD. - In the
mainfunction, the program asks the user to enter two numbers, then prints their GCD by calling thegcdfunction.
Similar Questions
Write programs to find (using recursions) 1. Factorial of a number n (This is an example of using recursion) 2. Fibonacci numbers The program demonstrates the concept of Fibonacci numbers. You must convert it into a recursive function 3. Xn 4. Consecutive sum of n numbers 5. Consecutive sum of n odd numbers 6. The sum of the following sequence: 1 2 + 22 + 32 + ... +n2 7. Find GCD of two numbers
Write a C program to print the Fibonacci series using recursion and without using recursion.
C Program to Calculate Multiplication and Addition, and Check Division Remainder
#include <stdio.h>void solve() { int n = 24; int l = 0, r = 100, ans = n; while(l <= r) { int mid = (l + r) / 2; if(mid * mid <= n) { ans = mid; l = mid + 1; } else { r = mid - 1; } } printf("%d", ans);}int main() { solve(); return 0;}
write a c program Find the largest number among the three numbers.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.