English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to use recursive functions to find the sum of natural numbers.
To understand this example, you should understand the followingC programming languageTopic:
Positive number1,2,3 ...is called natural numbers. The following program retrieves a positive integer from the user and then calculates the sum of the given number.
Access this page to Natural number sum using loop.
#include <stdio.h> int addNumbers(int n); int main() { int num; printf("Enter a positive integer: "); scanf("%d", &num); printf("Sum = %d", addNumbers(num)); return 0; } int addNumbers(int n) { if (n != 0) return n + addNumbers(n - 1); else return n; }
Output result
Enter a positive integer: 20 Sum = 210
Assuming the user entered20.
Initially, call addNumbers() from main(), and pass in20 as a parameter.
number20 is added to addNumbers(19) result.
to be passed in the next function call from addNumbers() to addNumbers().19, which will be added to the addNumbers(18result. This process continues until n equals 0.
No recursive calls are made when n equals 0. This ultimately returns the integer and passes it back to the main() function.