Loop Problems

Hey all.

I got an assignment today : 2) ch4ex8.cpp Write a C++ program that sums the integers from 1 to 50 (so that is, 1+2+3+4+...+49+50) and displays the result.


I have been working on this program 2 nights running now. I can't quite figure out how to go about it. I originally had a "for" loop:
1
2
3
4
5
6
7
8
9
10
11

void main(void)
{
  int counter;
  int total;
    for(counter = 0; counter < 51; counter++)
       {
           total = counter + counter++;
       }
  cout << total;
}



I think that a for loop will work. My question is how to I add the last number to the next number?

NOTE: It made more sense to me to put the numbers in an array. I am not sure how to add the first array element to the next one though.

Any Ideas?
Thanks all in advance
You don't need an array. This problem is extremely trivial. Your code is more complex than it needs to be.
1. initialize total (set it to 0 so that it doesn't contain garbage.
2. for counter = 1 to 50
3. total = total + counter.
You're close...

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

int main()
{
		
  int counter;
  int total = 0;
    for(counter = 1; counter < 50; counter++)
       {
           total = total += counter ;
		   
		}
  cout << total;


	cin.ignore().get();
	return 0;
}



edit; looks like I was too slow this time...
Last edited on
While loop works too.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
   int counter = 1;
   int total = 0;

   while (counter < 50)
   {
      total += counter;
      ++counter;
   }
   cout << total << endl;
   return 0;
}
*Slaps head* Doh! I guess I was making it too hard on my self. Thanks for the help all!
Topic archived. No new replies allowed.