Search code examples
cfizzbuzz

Why not use a while loop for FIZZBUZZ in C?


Only been coding in C for about a month, but wondered why the while loop wasn't used more often for FIZZBUZZ. Is it not as clean or some other reason? Here's what I came up with:

int main()
{
    int num=1;
    while(num<=100)
    {
        if (num%3==0 && num%5==0)
        {
            printf("FIZZBUZZ!!!\n");
        }
        else if (num%3==0)
        {
            printf("FIZZ!!!\n");
        }
        else if (num%5==0)
        {
            printf("BUZZ!!!\n");
        }
        else
        {
            printf("%d\n", num);
        }
        num++;
    }

    return 0;

}


Solution

  • Your loop can be neatly folded into a for loop:

    for(int num = 1; num <= 100; ++num)
    

    There are two advantages here:

    • num is scoped inside the loop, when before it was bleeding into whatever scope followed the while. Restricting variables to the minimum possible scope is a good rule of thumb, because it minimizes the amount of variables to think about at any given point.

    • The range over which your program will operate is now summarized in a single place: you can see the bounds (1 to 100) and the step (1) inside the for. That kind of ranges is pretty well balanced to be read and memorized quickly before reading the body of the loop. For example, if you now wanted to only check odd numbers, it would be immediately clear from reading the num += 2 in the for header, rather than stumbling upon it at the very end of the loop's body.