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