Wednesday, 5 February 2014

A Program that Displays Sum of Series Using Do-while Loop

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:


  1. Line 1 & 2: add the header files required to run all the functions in our program.
  2. Line 3: introduce the main() function with a return type: void.
  3. Line 4: start of the body of main() function.
  4. Line 5: clrscr() clears all the outputs from the screen.
  5. Line 6: Declare and initialize a variable of integer datatype, its initial value=1 depends upon our requirement.
  6. Line 7: Declare and initialize a variable of float datatype. Again the value depends upon our requirement.
  7. Line 8: Introduce a do-while loop.
  8. Line 9: Body of do-while loop starts.
  9. 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).
  10. 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...)
  11. Line 12: End of the body of do-while loop.
  12. 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.
  13. 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.
  14. Line 15: getch() will hold the output on the screen until the user press any key from his keyboard.
  15. Line 16: end of the body of main() function.

Output:

The output of the code given above is given below:
Output of above given CPP Program
Result of Sum of Series Program

No comments:

Post a Comment