C++ simple question

Nov 17, 2010 at 5:24pm
replace this do-while loop with a while loop. When u do this you will no longer need an if statement.

cout << "Enter an even number: ";
do
{ cin >> number;
if (number % 2 !=0)
cout << "Number must be even. Reenter number: ";
} while (number % 2 !=0);



THANKS--
Nov 17, 2010 at 5:28pm
try.
Nov 17, 2010 at 5:42pm
i did try many times bro it doesn't work
Nov 17, 2010 at 5:42pm
i did try many times bro it doesn't work
Nov 17, 2010 at 5:46pm
Where's the code that "doesn't work"?
Nov 17, 2010 at 5:59pm
1
2
3
4
5
6
7
8

cout << "Enter an even number: ";
do
{ cin >> number;
if (number % 2 !=0)
cout << "Number must be even. Reenter number: ";
} while (number % 2 !=0);
Nov 17, 2010 at 6:00pm
You didn't replace the do-while with a while loop.
Nov 17, 2010 at 6:15pm
i know that is why im asking you to do it because when i tried it doesn't work
Nov 17, 2010 at 6:22pm
We need to see the code you wrote that doesn't work so we can help you fix it. If you post it, we can help you make it work.
Nov 17, 2010 at 6:35pm
This is the syntax for a while loop:

1
2
3
4
while (condition)
{
     // code
}


I don't understand what you can't figure out.
Last edited on Nov 17, 2010 at 6:36pm
Nov 17, 2010 at 6:59pm
please answer it i dun hv time
Nov 17, 2010 at 7:03pm
Apparently you dun hv time to spell out your words either. The only way I could make it simpler is by giving you the answer.

[Edit]: Give it your best attempt and post it.
Last edited on Nov 17, 2010 at 7:07pm
Nov 17, 2010 at 7:07pm
then tell me
Nov 17, 2010 at 7:10pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>
using namespace std;

int main()
{
	int number;
		cout << "Enter an even number: ";
		while (number % 2 != 0);
		{	cin >> number;
		
			cout << "Number must be even. Reenter number: "; }
return 0;
}



here is the code now answer
Nov 17, 2010 at 7:15pm
This is very close. Add cin >> number; between lines 8 and 9, and switch lines 10 and 12.
Nov 17, 2010 at 7:28pm
problem 1. ';' after while(). That just creates an empty loop.
problem 2. comparison happens before input. One way would be to have cin >> number once before the loop and once in it (after cout << ... ). Another one would be while(cin >> number && number %2 != 0){...
Topic archived. No new replies allowed.