summation with loop

Feb 24, 2014 at 3:43am
I am writing a program to add integers 1+2+3...etc. The sum can not exceed
2500. But after i output the sum, it shows 2556. Can anyone help me fixing it. Thank you so much.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
int number=1,sum=0;
while(sum<2500)
{
sum=sum+number;
number++;
}
cout<<sum;

return 0;
}
Feb 24, 2014 at 4:03am
while(sum + number < 2500)
Feb 24, 2014 at 7:34am
+1 to Smac89
Feb 27, 2014 at 6:07pm
Try to make that program using a for loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>

int main()
{
int i=0;
int sum=0;

for(int i=0; i<=2500; i++)
{
sum=i+sum;
}
cout<<sum
return 0;
}


Last edited on Feb 28, 2014 at 4:41pm
Feb 27, 2014 at 6:29pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
int number=1,sum=0;
while(sum<2500)
{
sum=sum+number;
//number++;<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
cout<<sum;

return 0;
}
Topic archived. No new replies allowed.