Q:

Write a C Program to display numbers from 1 to n and their sum by recursion

0

Write a C Program to display numbers from 1 to n and their sum. How to find sum of natural numbers in a given range in C programming. C program to find sum of natural numbers in given range. Logic to find sum of all natural numbers in a given range in C program.

All Answers

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

Recursion : :


  • Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.
  • The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.
  • Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.

Below is the source code for C Program to display numbers from 1 to n and their sum by recursion which is successfully compiled and run on Windows System to produce desired output as shown below :

 
 

SOURCE CODE : :

/* Program to display numbers from 1 to n and their sum*/



#include<stdio.h>
int summation(int n);
void display1(int n);
void display2(int n);

int main( )
{
        int n;
        printf("Enter number of terms : ");
        scanf("%d", &n);

        display1(n);
        printf("\n");

        display2(n);
        printf("\n");

        printf("sum = %d\n", summation(n));

        return 0;

}
/*End of main()*/


int summation( int n)
{
        if(n==0)
                return 0;
        return ( n + summation(n-1) );
}/*End of summation()*/

/*displays in reverse order*/
void display1(int n)
{
        if( n==0 )
           return;
        printf("%d ",n);
        display1(n-1);
}/*End of display1()*/

void display2(int n)
{
        if( n==0 )
           return;
        display2(n-1);
        printf("%d ",n);
}/*End of display2()*/

OUTPUT  : :


//OUTPUT ::


Enter number of terms : 15
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

sum = 120

Process returned 0

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

total answers (1)

C Recursion Solved Programs – C Programming

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C Program to convert decimal number to Binary, Oct... >>
<< Write a C Program to find factorial by recursion a...