Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS151 / KCS251 Programming for Problem Solving - Using C Language
Lab Exercises
22. Write a program to calculate the GCD of given numbers using recursion.
/*
File: Prgrm22.c
Author: Aditya Saini
Date: Jan 17, 2021
Description: Program to calculate the GCD of given numbers using recursion.
*/
#include <stdio.h>
int gcd_calculator (int, int);
int main (void)
{
int num_1, num_2;
int gcd;
//Input number
printf ("Input first number: ");
scanf ("%d", &num_1);
printf ("Input second number: ");
scanf ("%d", &num_2);
//Fucntion call
gcd = gcd_calculator (num_1, num_2);
//Print result
printf ("Greatest Common Divisor (GCD): %d", gcd);
};
int gcd_calculator (int num_1, int num_2)
{
//Calculate gcd
//Base Case
if (num_1 == 0)
return num_2;
else
//Recursive call
return gcd_calculator (num_2 % num_1, num_1);
};
Output
Input first number: 657
Input second number: 894
Greatest Common Divisor (GCD): 3
No comments:
Post a Comment
Please do not post spam links.