Lets write a C program to add first seven terms of the following series 1 / 1! + 2 / 2! + 3 / 3! + ….. + 7 / 7!
We’ve also written the C program to ask the user to enter the number of terms of the series that has to be added. You can find code to both of it below.
Related Read:
For Loop In C Programming Language
while loop in C programming
C Program To Find Factorial of a Number using For Loop
C Program To Find Sum of Series 1/1! + 2/2! + 3/3! + …. + n/n!
[youtube https://www.youtube.com/watch?v=Nok-OqhKpDY]
Source Code: C Program To Find Sum of Series 1/1! + 2/2! + 3/3! + …. + 7/7!
int main() { int num = 1, count; float sum = 0.0, fact; while(num <= 7) { fact = 1; for(count = 1; count <= num; count++) { fact = fact * count; } sum = sum + (num / fact); num++; } printf("Sum of series is %f\n", sum); return 0; }
Output:
Sum of series is 2.718056
In above code, while loop iterates from 1 to 7. For each iteration for loop calculates the factorial of the selected number – which is present in variable num. Outside for loop, we add the individual series elements. At the end of while loop execution, variable sum will have sum of 7 terms of the series.
Source Code: C Program To Find Sum of Series 1/1! + 2/2! + 3/3! + …. + n/n!
int main() { int num = 1, count, limit; float sum = 0.0, fact; printf("Enter the number of terms\n"); scanf("%d", &limit); while(num <= limit) { fact = 1; for(count = 1; count <= num; count++) { fact = fact * count; } sum = sum + (num / fact); num++; } printf("Sum of %d terms of series is %f\n", limit, sum); return 0; }
Output 1:
Enter the number of terms
7
Sum of 7 terms of series is 2.718056
Output 2:
Enter the number of terms
8
Sum of 8 terms of series is 2.718254
In above code, we ask the user to enter the number of terms in the series that needs to be added. While loop iterates until the user entered number of times. Inside for loop we calculate the factorial of the selected number(number is selected by while loop and it’ll be present in variable num). Outside the for loop we add the individual series element. At the end of execution of while loop we’ll have sum of the series until user entered number of terms in the series.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert