While Loop

Please guide tell me where i went wrong
Write a program which will display the summation of
numbers from 1 to 1000.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main (void)
{
	int num=1, sum=0;
	
	while(num<=1000)
	{
		sum =sum+num;
		num =num+1;
	}
	
	cout<<"Sumation of Number from 1 to 1000 is: " <<sum;
	
	return 0;
}

Last edited on
Your program seems to work. Why do you think it isn't working correctly?

The only errors I see are that "summation" has two m's and you should output a newline after the sum.

Remember to use code tags in the future: http://www.cplusplus.com/forum/articles/16853/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main() {
    int num = 1, sum = 0;

    while (num <= 1000) {
        sum += num;
        num++;
    }

    cout << "Summation of integers from 1 to 1000 is " << sum << '\n';

    return 0;
}

Last edited on
Hello the code is working but i want my answer to be "500500" i want the summation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int main() {

    const int from = 1 ;
    const int to = 1000 ;
    static_assert( from>=0 && from <= to, "sanity check failed" ) ;

    // sum of non-negative numbers [from,to] is sum of numbers [1,to] - sum of numbers [1,from] + from
    const int expected_result = ( to*(to+1)/2 ) - ( from*(from+1)/2 ) + from ;

    int sum = 0;
    int num = from ; // starting with 'from'

    while( num <= to ) { // up to including 'to'

        sum += num; // add the numbers to 'sum'
        ++num;
    }

    std::cout << "Sum of integers from " << from << " to " << to << " is " << sum << '\n'
              << "The expected result is " << expected_result << '\n' ;
}

Sum of integers from 1 to 1000 is 500500
The expected result is 500500

http://coliru.stacked-crooked.com/a/eb96f1997389995c
Topic archived. No new replies allowed.