LearnFrenzy
Sign in Take a free test

Decision Making · Decision Making Programs · Question 8

FizzBuzz without the % operator in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Print FizzBuzz for 1 to 15 without using %: decide with counters instead.

Solution
main.c
#include <stdio.h>

int main(void) {
    int three = 0, five = 0;
    for (int i = 1; i <= 15; i++) {
        three++;
        five++;
        if (three == 3 && five == 5) {
            printf("FizzBuzz ");
            three = five = 0;
        } else if (three == 3) {
            printf("Fizz ");
            three = 0;
        } else if (five == 5) {
            printf("Buzz ");
            five = 0;
        } else {
            printf("%d ", i);
        }
    }
    printf("\n");
    return 0;
}

Output Verified by compiling and running

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Two counters reset at 3 and 5 replace the divisibility tests. The combined case must be checked first, and it resets both counters – otherwise the next Fizz or Buzz would be off by one.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links