Finding Sum of ln(1+x) Using Recursive Function

This program calculates sum of series ln(1+x) up to n terms using recursion in C programming language.

Program


#include<stdio.h>
#include<conio.h>
#include<math.h>

/* Function prototype */
float logfun(float x, int n);

/* Main Function */
int main()
{
 float x, result;
 int n;
 clrscr();
 printf("Enter value of x:\n");
 scanf("%f", &x);
 printf("Enter number of terms:\n");
 scanf("%d", &n);
 /* Function Call */
 result = logfun(x,n);
 printf("ln(1+%0.2f) = %0.4f", x, result);
 getch();
 return 0;
}

/* Function Definition */
float logfun(float x, int n)
{
 if(n< 0)
 {
  return 0;
 }
 else
 {
  return pow(-1, n) * pow(x, n+1)/(n+1) + logfun(x,n-1); /* Recursive function */
 }
}

Output

Enter value of x:
0.5 ↲
Enter number of terms:
10 ↲
ln(1+0.50) = 0.4055

Note: ↲ indicates ENTER is pressed.