Anyone assist me with this...... please

Below was my try , doesnt seem so fine

// program to calculate 1+1/2 + 1/3.......1/100
#include <iostream>
using namespace std;
int main ( )
{
double n = 1 ;
long double sum = 0;
while (n >=10)
{
n ++;
sum = sum + (1/n);
}
cout << sum << endl;
return 0;
}
n shouldn't be a double. It should be an int (since you only want integer values).

Your while loop condition is wrong, go through it like you are the computer and see if you can figure out why. I would also suggest replacing the while loop with a for loop instead.
Well I have modified it to this: but still its giving me a zero

// program to calculate 1+1/2 + 1/3.......1/100
#include <iostream>
using namespace std;
int main ( )
{
int sum = 0;
for (int n=1;n >=10; n++)
{
sum = sum + (1/n);
}
cout << sum << endl;
return 0;
}
Of course that it keeps writing zero.

Look at your for loop carefully: for (int n=1;n >=10; n++)

You initialize n with value 1 and your condition is n >=10 so the loop will never execute.

And that's not the only bug in your code, ex. sum has to be declared as a floating-point number.
#include <iostream>
using namespace std;
int main ( )
{
float sum = 0;
for (int n=1;n <=10; n++)
{
sum+=(1/(float)n);
}
cout << sum << endl;
return 0;
}
Topic archived. No new replies allowed.