This is a C program to find sum of first N numbers using recursion.
The following C program using recursion displays the first N natural number on the terminal.
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.
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); } }
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.
$ 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.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Check C Books
- Apply for Computer Science Internship
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Apply for C Internship