Find the Sum of Natural Numbers using Recursion in C


Write a C Program to find the sum of natural numbers using recursion.

Click Here to View the Solution!
#include <stdio.h>
int SumNumber(int number);

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
    printf("Sum = %d", SumNumber(num));
    return 0;

int SumNumber(int number) {
    if (number != 0)
        return number + SumNumber(number - 1);
        return number;
Click Here to View the Output!
Enter a positive integer: 7 
Sum = 28 
Click Here to View the Explanation!
  • This program is used to determine sum of all the natural number to the given integer through a recursive call.
  • An SumNumbers function is declared which will take an integer as its parameter.
  • In main(), the program requests the user to enter a positive integer and stores it in the variable num using the scanf() function.
  • Num is then passed to the function SumNumbers and printed.
  • The user-defined function is then created which will take the entered number as its parameter and check if the number is not equal to 0 and add the numbers using recursive calls until num becomes 0.
  • For instance, the user enters 20 which will be passed to the SumNumbers function as an argument.
  • 20 will then be added to the output of SumNumbers(19).
  • In the following function call, 19 will be added to the output of SumNumbers(18) and so on.
  • The recursive calls will continue adding the numbers until num will become equal to 0.
  • This function returns the sum of the integers to the main() method and displays the output.