471,831 Members | 1,317 Online

# program that computes and displays the sum of all integers...

Im doing a program for one of my classes and im no good.
here is the question

Write a program that computes and displays the sum of all integers from 1 to an ENDING number, using a while loop. Prompt the user for the ending number. For example, if the user enters 99, then the program will compute the sum of all the integers from 1 to 99 and would display the final sum of 4950.

Im no sure how to do the while loop and add the intergers. If some can show me how to write this program then i just might understand it. All help is appreciated.
Sep 23 '06 #1
3 15230
Banfa
9,065 Expert Mod 8TB
While loops go like

Expand|Select|Wrap|Line Numbers
1. int ix = 0;
2.
3. while(ix<50)
4. {
5.    printf("ix = %d\n", ix);
6. }
7.

Expand|Select|Wrap|Line Numbers
1. int a, b, c;
2.
3. a = 5;
4. b = 6;
5. c = 0;
6.
7. printf("A=%d, b=%d, c=%d\n", a, b, c);
8.
9. a++;
10.
11. printf("A=%d, b=%d, c=%d\n", a, b, c);
12.
13. a += b;
14.
15. printf("A=%d, b=%d, c=%d\n", a, b, c);
16.
17. c = a + b;
18.
19. printf("A=%d, b=%d, c=%d\n", a, b, c);
20.
21.
Sep 23 '06 #2
This is what i have so far, its rough but does have an output
[
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
int I;
int sum = 0;
int n = 1;
cout <<"Enter Positive Interger" << endl;
cin >> I;
//Add all intergers from 1 to I to sum
while (n <= I)
{
//add the sum and n together, and assign this new value to verible sum
sum = sum + n;
n++;
//Display the sum of the added intergers
cout << "The Total is " << sum << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
}
]
Sep 23 '06 #3
Banfa
9,065 Expert Mod 8TB
You have a brace inthe wrong place. This would be obvious if you indented you code correctly

Expand|Select|Wrap|Line Numbers
1. #include <cstdlib>
2. #include <iostream>
3.
4. using namespace std;
5.
6. int main()
7. {
8.     int I;
9.     int sum = 0;
10.     int n = 1;
11.     cout <<"Enter Positive Interger" << endl;
12.     cin >> I;
13.     //Add all intergers from 1 to I to sum
14.     while (n <= I)
15.     {
16.         //add the sum and n together, and assign this new value to verible sum
17.         sum = sum + n;
18.         n++;
19.         //Display the sum of the added intergers
20.         cout << "The Total is "  << sum << endl;
21.         system("PAUSE");
22.         return EXIT_SUCCESS;
23.     }
24. }
25.
You have

cout << "The Total is " << sum << endl;
system("PAUSE");
return EXIT_SUCCESS;

inside the while loop this means the program outputs the result, "PAUSE"s and returns on the first itteration of the while loop.

These statements should come after the while loop.
Sep 24 '06 #4