Q:

Write C program to find sum of natural numbers in given range using recursion

0

Write C program to find sum of natural numbers in given range using recursion

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used Code::blocks 12 compiler for debugging purpose. But you can use any C programming language compiler as per your availability.

#include <stdio.h>
 
 
// Function declaration
int sumofnnumbers(int start, int end);
 
int main()
{
    int start, end, sum;
 
    // Inputting lower and upper limit from user
    printf("Enter lower limit: ");
    scanf("%d", &start);
    printf("Enter upper limit: ");
    scanf("%d", &end);
 
    sum = sumofnnumbers(start, end);
 
    printf("Sum of natural numbers from %d to %d : %d", start, end, sum);
 
    return 0;
}
 
 
//Recursively find the sum of natural number
 
int sumofnnumbers(int start, int end)
{
    if(start == end)
        return start;
    else
        return start + sumofnnumbers(start + 1, end);
}

Result:

Enter lower limit: 1

Enter upper limit: 5

Sum of natural numbers from 1 to 5 : 15

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write C program to print even or odd numbers in gi... >>
<< Write C program to find power of a number using re...