Starter Tutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » C Programming » Programs » Functions » C program to find gcd of given two numbers using recursion
Suryateja Pericherla Categories: Functions. No Comments on C program to find gcd of given two numbers using recursion
Join Our Newsletter - Tips, Contests and Other Updates
Email
Name

In this article we will learn to implement a C program to find gcd of given two numbers using recursion. A C program is provided below to read two numbers and find their GCD.

 

Program is as follows:

/*
 * C program to find GCD of given two integers using recursive and non-recursive functions
 * Author: P.S.SuryaTeja
*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>

int gcd(int num1, int num2)
{
	int i, hcf;
	if(num1 < num2)
	{
		for(i = 1; i <= num1; i++)
		{
			if((num1 % i == 0) && (num2 % i == 0))
				hcf = i;
		}
	}
	else
	{
		for(i = 1; i <= num2; i++)
		{
			if((num1 % i == 0) && (num2 % i == 0))
				hcf = i;
		}
	}
	return hcf;
}

int rgcd(int num1, int num2)
{
	while(num1 != num2)
	{
		if(num1 > num2)
			return rgcd(num1 - num2, num2);
		else
			return rgcd(num1, num2 - num1);
	}
	return num1;
}

int main(int argc, char **argv)
{
	int num1, num2;
	printf("Enter two numbers: ");
	scanf("%d%d", &num1, &num2);
	printf("\nGCD of %d and %d using non-recursion is: %d", num1, num2, gcd(num1, num2));
	printf("\nGCD of %d and %d using recursion is: %d", num1, num2, rgcd(num1, num2));
    getch();
    return 0;
}

 

Input and output for the above program is as follows:

Enter two numbers: 24 6

GCD of 24 and 6 using non-recursion is: 6
GCD of 24 and 6 using recursion is: 6

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory