C PROGRAMMING PROGRAM • FUNCTIONS & RECURSION
Find the Sum of Natural Numbers Using Recursion
Learn how to find the sum of natural numbers using recursion using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
10
Sample output
Sum = 55
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
long long sumTo(int number)
{
if (number == 0) return 0;
return number + sumTo(number - 1);
}
int main(void)
{
int number;
printf("Enter a non-negative integer: ");
scanf("%d", &number);
if (number < 0) return 1;
printf("Sum = %lld\n", sumTo(number));
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sum = 55
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Add N to the recursive sum ending at N−1 until the base case zero.
- Display the computed result.
Add N to the recursive sum ending at N−1 until the base case zero.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
