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.

IntermediateRecursionBase caseNatural numbers

PROBLEM UNDERSTANDING

Input and expected output

Sample input
10
Sample output
Sum = 55

COMPLETE C PROGRAM

Complete C implementation

sum-natural-numbers-recursion.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Sum = 55
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Add N to the recursive sum ending at N−1 until the base case zero.
  3. 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.