# C Program to Find Sum of N Numbers using Recursion

«
»

This is a C program to find sum of first N numbers using recursion.

Problem Description

The following C program using recursion displays the first N natural number on the terminal.

Problem Solution

The user enters the Nth number as the input, the program then calculates the sum of first N numbers using recursion and then displays the final result.

Program/Source Code

Here is the source code of the C program to display first N numbers. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

```/*
* C Program to find Sum of N Numbers using Recursion
*/
#include <stdio.h>

void display_sum(int);

int main()
{
int num;

printf("Enter the Nth number: ");
scanf("%d", &num);
display_sum(num);
return 0;
}

void display_sum(int num)
{
static int sum = 0;

if (num == 0)
{
printf("Sum of first N numbers is %d\n", sum);
return;
}
else
{
sum += num;
display_sum(--num);
}
}```
Program Explanation

In this C program, we are reading the integer number using the ‘num’ variable. To find Sum of N Numbers using Recursion, call the display_sum() by passing the num variable value as argument.

In function display_sum(), initialize the value of ‘sum’ variable with 0 value. Here, sum variable is defined as static so that only one copy of that object will be there upon repeated invocation of that function. If else conditional statement is used to check the value of ‘num’ variable. If the value of ‘num’ variable is non zero, we will increment the value of sum variable by num and then call display_sum() recursively by reducing the value of num variable by 1.

Once num becomes 0, we know that we have completed the recursion and we will display the final result stored in the ‘sum’ variable.

Runtime Test Cases
```
\$ cc pgm33.c
\$ a.out
Enter the Nth number: 3
Sum of first N numbers is 6

\$ a.out
Enter the Nth number: 5
Sum of first N numbers is 15```

Sanfoundry Global Education & Learning Series – 1000 C Programs. 