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>
usingnamespace 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;
}
#include <iostream>
usingnamespace 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;
}
#include <iostream>
int main() {
constint from = 1 ;
constint 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
constint 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