Problem:
Write a program that displays the sum of the following series using do-while loop:1 + 1/4 + 1/8 + ... + 1/100
Solution:
Here is the code that solves the problem given above:#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n=1;
float sum=0.0;
do
{
sum=sum+(1.0/n);
n=n+4;
}
while(n<=100);
cout<<"Result="<<sum;
getch();
}
Explanation:
- Line 1 & 2: add the header files required to run all the functions in our program.
- Line 3: introduce the main() function with a return type: void.
- Line 4: start of the body of main() function.
- Line 5: clrscr() clears all the outputs from the screen.
- Line 6: Declare and initialize a variable of integer datatype, its initial value=1 depends upon our requirement.
- Line 7: Declare and initialize a variable of float datatype. Again the value depends upon our requirement.
- Line 8: Introduce a do-while loop.
- Line 9: Body of do-while loop starts.
- Line 10: Add 1/n value to current value of sum (for the first time it will add 1/1 to the sum variable, next time it will add 1/4 then 1/8 and so on).
- Line 11: Make an increment of 4 in the value of n (because we want a series with the difference of 4 in the denominator of 1: 1, 1/4, 1/8, 1/12 and so on...)
- Line 12: End of the body of do-while loop.
- Line 13: The condition, on the basis of which the do-while loop will run. In this case, loop will run until the variable n remains less-than or equal-to 100.
- Line 14: Show the output. We're using sum variable with cout because the final result which has to be shown is stored in sum.
- Line 15: getch() will hold the output on the screen until the user press any key from his keyboard.
- Line 16: end of the body of main() function.
Output:
The output of the code given above is given below:
![]() |
| Result of Sum of Series Program |

No comments:
Post a Comment