### Homework error?

For an assignment I'm supposed to make a program that calculates the even numbers between 1 and a user defined 'n.' The program is supposed to continue until the user wants it to stop with an entry of '0'. I thought all was well and good it seemed to be working fine but if I keep entering test cases it screws up. For example if I enter 16, 21, and 42 the answers will be correct. But if after 42 I enter a lower number like say 12, it will just continue to produce 42's answer until I enter a number higher than 42. Where did I go wrong? Thanks so much for any and all help!

 ``12345678910111213141516171819202122232425262728`` ``````#include using namespace std; int main() { int sum = 0; int n = 0; int j = n%2; cout << "Please enter an integer [0 to stop]: " ; cin >> n ; while (n > 0) { while (j <= n) { sum = sum + j ; j = j + 2 ; } cout << "The sum of the even numbers between 1 and " << n << " is " << sum << endl ; cout << "Please enter an integer [0 to stop]: " ; cin >> n ; } system("pause"); return 0; }``````
You never modify j after you done with it and got a new n
What is the purpose of line 8? Since n is zero won't j always be zero? Maybe you need to do this test elsewhere, maybe in the loop?

MiiNiPaa - I'm sorry to be daft, but in what way am I to modify j?

jlb - j changes according to what the user enters for n. If the user enters an even integer, j should = 0 and if the user enters an odd integer j should = 1. (At least that's how my professor described it)
But you calculate this value before the user enters anything. Shouldn't the calculation be done after you get your user input?
Ok, I altered the code a bit with your suggestion but I'm still getting errors, it will calculate even numbers correctly but not odd numbers. I should get the answer 110 for the sum of all even numbers between 1 and 21, but I get 121 instead. Here is my updated code:

Edit: I attempted changing `int j = n%2` to `int j = 0`, but that made everything weird and lower numbers than the number previously entered would equal 0...

 ``12345678910111213141516171819202122232425262728293031`` ``````#include using namespace std; int main() { int sum = 0; int n = 0; int j = n%2; cout << "Please enter an integer [0 to stop]: "; cin >> n ; while (n != 0) { int sum = 0; j = n%2; while (j <= n) { sum = sum + j ; j = j + 2 ; } cout << "The sum of the even numbers between 1 and " << n << " is " << sum << endl ; cout << "Please enter an integer [0 to stop]: " ; cin >> n ; } system("pause"); return 0; } ``````
Last edited on
Solved I figured it out, thank you so much!!!
Topic archived. No new replies allowed.