#Number Guesser

9 messages · Page 1 of 1 (latest)

vale fernBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

hearty frigate
#

First of all variables should be lowercase by convention, but okay.
Well, think about when the else case could run. guess mustn't be larger nor smaller, so it must be equal. If you guessed the number on the very first try it'd actually work as expected.
If you don't get it on the first guess, then you'll eventually guess it correctly, after which the next while-do loop iteration comes in, but that iteration never happens because the do-while loop's condition is false by that time. Also the break at the end is completely irrelevant as it'd be the last statement of the loop anyways.

The easiest way to fix your code would be to turn the do-while loop into a while (1) one, but this doesn't get rid off the redundant scanf calls. Much better would be a small restructuring (I omitted some brackets):

for (;;) {
    scanf("%d", &guess);
    counter += 1;
    if (guess < answer)
        // smaller
    else if (guess > answer)
        // larger
    else
        // equal
        break;
}
#

Also fixes the counter which before was always 1 off the actual guesses. If that behaviour was intended, then just initialize counter to -1 instead of 0

red saffron
hearty frigate
#

A for statement has 3 parts:

for (<intial_setup>, <condition>, <post_iteration>)
#

These are all optional

#

As you may know you can write a loop like this:

for (int i = 0; i < 10; )
```where you omit the `post_iteration` part.
You can also omit the `initial_setup` part:
```c
int i = 0;
for (; i < 10; )

You can also omit the condition part in which case it's treated as truthy for every iteration, meaning the loop can't terminate without a break statement.
Effectively for (;;) is the same as while (1), it's just a bit faster to type imo.

#

Smth like this is obviously also legal:

for (int i = 0; ; i++)
```in which case we have an "infinite" loop incrementing a local variable `i`.
red saffron