Adding Reciprocals - Loop

How to do the problem below using loop?

Using loop...
Output the total of the reciprocals of the numbers from 1 to 10:
1/1 + 1/2 + 1/3 + 1/4 ... + 1/10 = 2.928968
Do you know how to write a loop?
http://www.cplusplus.com/doc/tutorial/control/

Do you know how to calculate a fraction?
I know how to write some loops and I know how to calculate fractions...just not sure how I would add them all up in a loop.

This is what I have so far but it's giving what the reciprocal of each number is from 1 to 10.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

using namespace std;

int main(){
{
   double a = 1;

   while( a <= 10 )
   {
       cout << 1/a <<endl;
	   a++;
   }
 
   return 0;
}
}
That may only iterate 9 times. I would use an int for your loop iterations. Also for a set number of iterations I tend to use for loops.

1
2
3
4
5
double result = 1.0;
for(unsigned i = 2; i < 11; ++i) //2->10 as we set it equal to 1 to start
{
    result += 1.0 / i;
}


This is what I have so far but it's giving what the reciprocal of each number is from 1 to 10.
Well look closely at cout << 1/a <<endl; if you want the actual result output after the function and add it to the previous as I mentioned above.
Topic archived. No new replies allowed.