C Program to Find Sum of 1+11+111 Using Recursive Function
In this program, we first read number of terms n
from user. Then we pass value of n
to recSum()
which calculates sum of 1 + 11 + ...
series up to n
terms recursively.
This C program calculates sum of 1 + 11 + 111 + 1111 + .... up to n terms using recursive function.
C Source Code
#include<stdio.h>
int recSum( int n );
int main()
{
int n,res;
printf("Enter number of terms:\n");
scanf("%d",&n);
res=recSum(n);
printf("Required sum = %d", res);
return 0;
}
int recSum( int n )
{
if (n<=0)
{
return 0;
}
else
{
return ( n + 10 * recSum ( n-1 ) );
}
}
Output
Enter number of terms: 4 ↲ Required sum = 1234 Note: ↲ indicates ENTER is pressed.