Sum of n Natural Numbers in C Using Recursion

Sum of Natural Numbers in C. A recursive function is a function that calls itself. Recursion is the name for this strategy. Recursion is a problem-solving technique in which the outcome is determined by the solutions to smaller instances of the same problem. Recursion is supported by most computer programming languages by allowing a function to call itself from within its own code.

#include <stdio.h>
int sum(int n);
int main() 
int num, total;
printf("Enter the num");
scanf("%d", &num);
total = sum(num);
printf("sum = %d", total);
return 0;
int sum(int n) 
if (n != 0)
return n + sum(n-1); 
return n;



Enter the num 45

sum = 1035

Function to Execute Sum of Natural Numbers in C

A function is a collection of statements that work together to complete a task. Every C program has at least one function, main(), and even the most simple programs can define additional functions. A function declaration informs the compiler about the name, return type, and parameters of a function.

Types of Function in C

Library Functions: These are functions declared in C header files such as scanf(), printf(), gets(), puts(), ceil(), floor(), and so on.
User-defined functions: These are functions that the C programmer creates so that he or she can use it repeatedly.

If Else in Function

When we log a function call expression, the output is the function’s return value. The return value of a self-invoking (it called itself) anonymous function expression was logged. This demonstrates that we can run a function within a loop.