Do While Loop Challenge - ( Ask to play again() = = 1)

Hey Guys,

This is what I came up with while trying to do the ‘Do - While Challenge’.
It seems to work fine when I output it.

If anyone can explain why this isn’t the best way to do it,
please let me know. So I can learn since it’s different from the tutorial.

Thank you!

1 Like

Maybe because AskToPlayAgain() method is not clearly known that it is Boolean.
This is my guess.

Technically this is correct. The code will execute just as you want it to.

However, it is not immediately apparent what AskToPlayAgain() == 1 means. You asked them if they wanted to play again and they answered one? It would be a little more clear if you assign the return value from AskToPlayAgain() to a boolean.

For example, bool wantsToPlayAgain. Then you can say while (wantsToPlayAgain == true); (use true. not 1, which doesn’t make sense at a glance. It might make sense now but if you haven’t looked at the code for a while it can take a few seconds to register).

Or, simpler, you can use while (wantsToPlayAgain); (without the == true, because the value of wantsToPlayAgain is already true. No need to rewrite it).

Another way you can write it (this is how I prefer) is to use what I said about not needing to rewrite things and just say while (AskToPlayAgain()); This will take whatever the value returned from AskToPlayAgain() is and
check if that is true or false. This is by far the simplest way to write it with the least amount of lines of code, while still being perfectly clear. The only downside of doing it this way is that you are not assigning the result to a variable, so you can’t cout the result or use it another way without recalling the method.

Of course, you can also say while (AskToPlayAgain() == true). A bit redundant, but valid and still clear.

Privacy & Terms