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!
#include <iostream>
usingnamespace 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;
}
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)
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...
#include <iostream>
usingnamespace 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;
}