Calculate sum of first 1000 integers

Asked By 10 points N/A Posted on -
qa-featured

I need a program in C++ language for calculating the sum of first 1000 integers using while loop. And print the result.

SHARE
Best Answer by Aristono Martin
Best Answer
Best Answer
Answered By 20 points N/A #124159

Calculate sum of first 1000 integers

qa-featured

Hi Eleanor,

You can try to use the sample program below:

include <iostream>
using namespace std;
int main()
{
// declarations of the variables
int sum,num;
//initialization of the variables
sum = 0;
num = 1;
//using the while loop to find out the sum of fist 1000 integers starting from one.
while number <= 1000)
{

//Adding the integers to the contents of sum
sum = sum + number;
//Generate the next integer by adding 1 to the integer
number = number + 1;
}
cout <<"The sum of the first 1000 integers starting from 1 is " <<sum;
}

Aristono

Answered By 0 points N/A #124160

Calculate sum of first 1000 integers

qa-featured

Let me make you clear that the previous answer to the question has only one problem. "num to be replaced by number.".

However I give you a fresh code.

#include < iostream.h >

void main ( ) {

int sum=0;            //Initialize the sum variable

int ctr = 1;                 // count for 1000 integers

while  ( ct r<= 1000 ){                      //check whether 1000 integers are done.

sum = sum + ctr;                   //sum integer with the previous sum.

ctr = ctr + 1;                 //increment to next integer

}

}

cout<<"Printing the result on the standard output : Sum is :  "<<sum;                   //Print the Summed result to standard output

In a more compact form

#inlcude < iostream.h >

void main ( ) {

int sum=0 , ctr = 1;            //Initialize the sum  and ctr variables

while  ( ct r<= 1000 )                      //check whether 1000 integers are done.

sum = sum + ctr++;                   //sum integer with the previous sum and then increment.

cout<<"Printing the result on the standard output : Sum is :  "<<sum;                   //Print the Summed result to standard output

}

 

Related Questions