Writing a while-loop?

I was given this assignment:

Write a C++ code segment using the while loop to find the sum of the even integers 2,4,6,8,...,500. Display the resulting sum. Be sure to give code to declare and initialize variables used.

This is what I have so far, but I'm not sure if it's correct or not, nor do I really know how to progress. Feedback/assistance would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
  #include <iostream>
  using namespace std;

  int main()

  {
    int number1 = 2
  
    while (number1 + 2 <= 500)
    {
So it looks like you started with the right idea with starting with the number 2, which is certainly an even number. At this point all you would need to do is generate the next even number which is relatively straight forward, adding 2. So with this in mind you would need to take this value and add it to some total value, which implies another variable of say sum. So you could maybe have something along the lines of
1
2
sum = sum + number1; 
number1 = number1 + 2;


Of course, this requires some initialization of an additional variable with the appropriate starting value. I'll let you figure this part out. I don't want to steal all the fun ;)


Hope this helps.

Happy coding.
Hambone
You may also code Hambone's suggestion above as: number1 += 2;

Which is my personal preference because it takes less key strokes to type out.
This is the same thing as number1 = number1 + 2;
So, would this be an adequate code?

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

int main()
{
   int number1 = 2
   int sum = 0

   while (number1 + 2 <= 500)
   {
     number1 = number1 +2
     sum = sum + number 1
   }
   cout<<"Sum = "<<sum<<endl;

   return 0;
}
So, would this be an adequate code?

No,
Missing semicolon on lines 6,7,11 and 12.
"number 1" instead of "number1" on line 12.

Edit:
You can print out "number1" in the loop to see one more problem you have.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
	int number1 = 2;
	int sum = 0;

		while (number1 + 2 <= 500)
		{
			cout << number1 << " ";
			number1 = number1 + 2;
			sum = sum + number1;
		}
	cout << "Sum = " << sum << endl;
	return 0;
}

It's skipping the number "500", which you probably don't want. Change the condition to
while(number1 <= 500)
Last edited on
Thank you very much!
Topic archived. No new replies allowed.