C Program to print sum of first natural numbers using recursion

Category: C Program

C Program to print sum of first natural numbers using recursion

C Program to print sum of first natural numbers using recursion

#include <stdio.h>

int sumOfNumbers(int);

void main()
{
    int num;

    printf("Enter the number: ");
    scanf("%d", &num);

    printf("Sum: %d", sumOfNumbers(num));
}

int sumOfNumbers(int num)
{
    if (num != 0)
        return num + sumOfNumbers(num - 1);
    else
        return 0;
}

Output

Enter the number: 10
Sum: 55

Recommended Posts