Steps to Understand the Program:
- Factorial: The factorial of a number nnn is the product of all positive integers less than or equal to nnn. For example, 3!=3×2×1=63! = 3 \times 2 \times 1 = 63!=3×2×1=6.
- Series Expansion: The given series is:S=11!+22!+33!+⋯+nn!S = \frac{1}{1!} + \frac{2}{2!} + \frac{3}{3!} + \cdots + \frac{n}{n!}S=1!1+2!2+3!3+⋯+n!nwhere each term kk!\frac{k}{k!}k!k involves calculating both the numerator kkk and the factorial of kkk.
- Logic of Program:
- We will use a loop to calculate each term in the series.
- For each kkk, calculate the factorial k!k!k!, then compute kk!\frac{k}{k!}k!k, and add this value to the sum.
#include <stdio.h>
// Function to calculate the factorial of a number
long double factorial(int n)
{
long double fact = 1;
for (int i = 1; i <= n; i++)
{
fact *= i;
}
return fact;
}
int main()
{
int n;
long double sum = 0.0;
// Taking input from the user
printf("Enter the value of n: ");
scanf("%d", &n);
// Loop to calculate the sum of the series
for (int i = 1; i <= n; i++) {
sum += (i / factorial(i)); // Calculating each term of the series
}
// Display the result
printf("Sum of the series is: %.10Lf\n", sum);
return 0;
}
Explanation of the Program:
- Factorial Function:
- The function
factorial(int n)computes the factorial of a given number nnn by multiplying all integers from 1 to nnn. This result is returned as the factorial of nnn.
- The function
- Main Function:
- The program starts by prompting the user to enter the value of nnn (the number of terms in the series).
- A
forloop is used to iterate from 1 to nnn, calculating each term of the series. - For each iteration iii, the program calculates ii!\frac{i}{i!}i!i using the factorial function and adds this value to the variable
sum. - After the loop completes, the final sum of the series is printed.
- Data Types:
- The data type
long doubleis used for storing the sum and factorial values because factorials grow very quickly, and using a regularfloatordoublemay not be precise enough for larger numbers.
- The data type
- Precision:
- In the output, the sum is printed with a precision of 10 decimal places (
%.10Lf), ensuring that even small values in the series are captured accurately.
- In the output, the sum is printed with a precision of 10 decimal places (
Example Output:
Enter the value of n: 5
Sum of the series is: 2.7083333333
Here, for n=5n = 5n=5, the series becomes:S=11!+22!+33!+44!+55!=1+1+0.5+0.1667+0.0417=2.7083S = \frac{1}{1!} + \frac{2}{2!} + \frac{3}{3!} + \frac{4}{4!} + \frac{5}{5!} = 1 + 1 + 0.5 + 0.1667 + 0.0417 = 2.7083S=1!1+2!2+3!3+4!4+5!5=1+1+0.5+0.1667+0.0417=2.7083
Explanation of Output:
- The program computes the sum of the first 5 terms of the series and returns the result. The result is the sum of the fractions computed from each term of the series.
This C program efficiently calculates the sum of the series by iterating through each term and using a function to calculate factorials.