Q12 Write a recursive function to obtain the running sum of first 25 natural numbers.

Write a recursive function to obtain the running sum of first 25 natural numbers.

Program: 133

Write a recursive function in c language to obtain the running sum of first 25 natural numbers.

(1) Without using recursion
(2) Using recursion

How to use recursion to get the sum of first 25 natural numbers.

#include<stdio.h>
int sum(int num);
int rec_sum(int num);
void main()
{
    int n;

    printf("Enter Range: ");
    scanf("%d", &n);
    printf("\nNon-Recursive: Sum of first %d numbers is: %d",n, sum(n));
    printf("\nRecursive: Sum of first %d numbers is: %d",n, rec_sum(n));
}
// This function is for non recursion
int sum(int num)
{
    int res=0;
    while(num) //we can write this condition as while(num!=0) both are same
    {
        res = res + num;
        num = num-1;
    }
    return res;
}

int rec_sum(int num)
{
    while(num)
    {
        return (num+sum(num-1));
    }
}

Output:

Enter Range: 10

Non-Recursive: Sum of first 10 numbers is: 55
Recursive: Sum of first 10 numbers is: 55

Lokesh Kumar: Being EASTER SCIENCE's founder, Lokesh Kumar wants to share his knowledge and ideas. His motive is "We assist you to choose the best", He believes in different thinking.
Related Post
Leave a Comment

This website uses cookies.