English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C program uses recursion to find G.C.D (greatest common divisor)

Comprehensive Collection of C Programming Examples

In this example, you will learn to find the GCD (greatest common divisor) of two positive integers entered by the user using recursion.

To understand this example, you should understand the followingC programming languageTopic:

This program takes two positive integers as user input and uses recursion to calculate the GCD.

Visit this page to learn howUsing a loop to calculate GCD.

Using recursion to calculate the greatest common divisor (GCD) of two numbers

#include <stdio.h>
int hcf(int n1, int n2);
int main() {
    int n1, n2;
    printf("Please enter two positive integers: ");
    scanf("%d %d", &n1, &n2);
    printf("%d and %d's G.C.D is %d.", n1, n2, hcf(n1, n2));
    return 0;
}
int hcf(int n1, int n2) {
    if (n2 != 0)
        return hcf(n2, n1 % n2);
    else
        return n1;
}

Output Result

Enter two positive integers: 366
60
366and6The G.C.D of 0 is6.

In this program, recursive calls are made until the value n2equals 0.

Comprehensive Collection of C Programming Examples