c
  1. c-program-to-find-the-sum-of-natural-numbers-using-recursion

Program to Find the Sum of Natural Numbers using Recursion - (C Programs)

Example

#include <stdio.h>

int sum(int n);

int main()
{
    int n;
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("Sum of first %d natural numbers is %d", n, sum(n));
    return 0;
}

int sum(int n)
{
    if (n == 0)
        return 0;
    else
        return n + sum(n - 1);
}

Output

Enter the value of n: 5
Sum of first 5 natural numbers is 15

Explanation

This program finds the sum of the first n natural numbers using recursion. The function sum takes an integer n as its argument and returns the sum of the first n natural numbers.

The base case of the recursion is when n is equal to zero, in which case the function returns zero. Otherwise, the function recursively adds n to the sum of the first n-1 natural numbers (which is computed by calling the sum function with n-1 as the argument).

Use

This program can be used to compute the sum of the first n natural numbers. It can be incorporated into other C programs that require the sum of the first n natural numbers.

Summary

In this C program, we learned how to find the sum of the first n natural numbers using recursion. The program defines a recursive sum function that takes an integer n as its argument and returns the sum of the first n natural numbers. The program uses a base case of n=0, and recursively adds n to the sum of the first n-1 natural numbers until n=0. The program is useful for calculating the sum of the first n natural numbers in other C programs.

Published on: