-4
#include <stdio.h>

int main()
{
    int num, count;
    count = 0;
    num = 8;

    while (num != 0)
    {
        if (num % 2 == 0)
        { // checks if num is even
            num = num / 2;
            count = count + 1; // increases counter by 1
        }
        else
        {
            num = num - 1;
            count = count + 1;
        }

        printf("%d", count); // prints counter
    }
    return 0;
}

For some reason the output is 1234 instead of 4, can anyone please explain why? I tried calling scanf() instead of setting num value to 8 as well, but the output is the same.

Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23
Elachi
  • 3
  • 1
  • 3
  • 2
    Close to a typo: the `printf` is **inside** the loop... – Serge Ballesta Mar 30 '22 at 06:51
  • 2
    You should take this as a good opportunity to learn how to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your programs. For example a minute stepping through the code statement by statement in a debugger should have shown you the problem. – Some programmer dude Mar 30 '22 at 06:55
  • A simple typo mistake, your call to `printf()` function is a part of `while` loop, actually in `1234` at last you got `4`. – Darth-CodeX Mar 30 '22 at 06:55
  • 2
    It's Karma - you are getting punished by the universe for having such sloppy code formatting. Time to adopt a conventional coding style. – Lundin Mar 30 '22 at 06:59
  • 1
    @Mathieu Don't fix the code formatting on questions where code formatting _is_ the problem! This should be closed as simple typo anyhow, not polished. – Lundin Mar 30 '22 at 07:00
  • Seriously, I will report the next person who tries to "fix" this post for vandalism. 3 times now, _pay attention to edit history and comments_! – Lundin Mar 30 '22 at 09:21

1 Answers1

0

You are printing the counter inside a loop and you are not printing it with a newline character. So you print "1", "2", "3", and then "4" and it looks like "1234" in your terminal. Use proper indentation so you can see what's going on visually and notice that your printf is inside a loop.

David Grayson
  • 84,103
  • 24
  • 152
  • 189