# Very simple problem.

• October 27th, 2012, 09:49 AM
Shinisama
Very simple problem.
Hello guys, Thank you for your help on my last question. I have another very simple question. I have been trying to figure this out for a while, and since my professor doesn't help me in the class I have to turn to you guys. Here is the assignment:
-----------------
Write a C++ program that inputs a number from the keyboard between 0 and 49 and then uses a for or while loop to display every integer that follows the integer that is input and that is evenly divisible by 4. The last number that will be displayed is 100. In other words, if the number you input from the keyboard is 45, your program will output
48 52 56 60 … 92 96 100
Or if your input is 40, your program will output
44 48 52 56 … 92 96 100

Your program does not have to run multiple times. One line of numbers per a.out is sufficient.
Place an error trap in your program that will reject any keyboard inputs < 0 or > 49. Use any wording you wish for the input prompt.
--------------
Now here is what I have come up with so far. I am pretty close to getting it, I am just missing one thing I think.

Code:

#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Input a number between 0 and 49." << endl;
cin >> n;
while (n < 100)
{
n = n + 4;
cout << n << ", ";
}
if (n < 0 || n > 49 )
cout << "The number you entered is less than 0. Invalid entry.";

return 0;
}

When I compile this program and run it it works but not as I want it to.
When I enter a number, any number at all, it will list all the numbers that follow it up to 100 - which is correct; but it also outputs "the number you have entered is less than 0. Invalid entry". I have been trying to figure this out and i know it is a simple fix, I just can't figure it out.

• October 27th, 2012, 11:07 AM
Eri523
Re: Very simple problem.
You're performing the input range check after the loop which is wrong in the first place: The loop isn't supposed to even be executed at all in case of invalid input, and that can't be accomplished when you do the check at a point when the loop has finished already.

Also, when the loop is done, n will always have the value 100, since the code in the loop has modified it, and of course that will always trigger your error message.
• October 27th, 2012, 03:35 PM
GCDEF
Re: Very simple problem.
n = n + 4;
cout << n << ", ";

That can't possibly do what you want it to. Using your example of 45, it's going to output 49, 53, 57, etc. Here's a hint.

http://www.cprogramming.com/tutorial/modulus.html