Ads block

Banner 728x90px

Display and Summation of series

In this section we will write a program to display the series as well as find the sum of this series by the use of recursive function.
Let us take a simple series of numbers from 1 to n.

For example if the number of terms is 5, then our function should give this output.

1 + 2 + 3 + 4 + 5 = 15

Here we display the series and sum of the series of the given n number without the use of loop.

#include<stdio.h>
int rseries(int n);

main()
{
    int n;
    printf("Enter number of term: ");
    scanf("%d", &n);
    printf("\b\b = %d\n\n", rseries(n));
}
int rseries(int n)
{
    int sum;
    if (n == 0)
        return 0;
    return (n + rseries(n-1));
    printf("%d + ", n);
}

Sum of Digits and Displaying Sequence of Integer

Now we will see another problem of this series. Here is a program code to solve the problem of finding sum of digits of a number and displaying an integer as sequence of character.

Let's take an example-

Suppose, we have to find sum of digits 45832, then first we pass this value in function sumdigits( ) as an argument then we can proceed as-

sumdigits(45832) = 2 + sumdigits(4583)
sumdigits(4583) = 3 + sumdigits(458)
sumdigits(458) = 8 + sumdigits(45)
sumdigits(45) = 5 + sumdigits(4)
sumdigits(4) = 4

The number n passes in the function sumdigits( ) and inside the function, there is a condition that checks the number n divisible by 10 is zero or not. If it is equal to zero then it returns the number n otherwise it process next statement.

int sumdigits(long int n)
{
    if(n/10 == 0)   /* if n is a single digit number */
        return n;
    return(n%10 + sumdigits(n/10));
}
void display(long int n)
{
    if(n/10 == 0)
    {
        printf("%d" ,n);
        return;
    }
    display(n/10);
    printf("%d", n%10);
}