A Small Collection of FizzBuzz Solutions

Author’s Note: This is just a small collection of solutions in various programming languages that I’m learning in order to solve the FizzBuzz problem. None of the programs are particularly sophisticated, and the use of the modulo operator or remainder function in the various languages makes these programs slow. The Scheme implementation of this problem is especially messy, because of the need to use the (newline) function for each operation, and my use of iterative recursion rather than the (do) construct.

C:

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 1; i <= 100; i++) {
	if (i % 3 == 0)
	    printf("Fizz");
	if (i % 5 == 0)
	    printf("Buzz");
	if (i % 3 && i % 5)
	    printf("%d", i);
	putchar('\n');
    }
    return 0;
}

C – using embedded ternary operators:

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 1; i <= 100; i++) {
	i % 3 == 0 ? (i % 5 == 0 ? printf("FizzBuzz\n") : printf("Fizz\n")) :
	    (i % 5 == 0 ? printf("Buzz\n") : printf("%d\n", i));
    }
    return 0;
}

Python:

for i in range(1, 101):
    if i % 3 == 0 && i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Scheme:

(define (fizzbuzz)
  (define (counter n)
    (cond ((> n 100) 'done)
          ((and (zero? (remainder n 3))
                (zero? (remainder n 5)))
                (display "FizzBuzz") (newline)
                (counter (1+ n)))
          ((zero? (remainder n 3))
                (display "Fizz") (newline)
                (counter (1+ n)))
          ((zero? (remainder n 5))
                (display "Buzz") (newline)
                (counter (1+ n)))
          (else (display n) (newline)
                (counter (1+ n)))))
  (counter 1))

FORTRAN 77:

c FORTRAN 77 compliant "FizzBuzz" procedure      
      PROGRAM FZZBZZ
      INTEGER I
      DO 10, I=1,100
         CALL COUNT(I)
 10   CONTINUE
      END

      SUBROUTINE COUNT(I)
      INTEGER I
      IF (MOD(I, 3) .EQ. 0 .AND. MOD(I, 5) .EQ. 0) THEN
         WRITE (*,*) 'FizzBuzz'
      ELSE IF (MOD(I, 3) .EQ. 0) THEN
         WRITE (*,*) 'Fizz'
      ELSE IF (MOD(I, 5) .EQ. 0) THEN
         WRITE (*,*) 'Buzz'
      ELSE
         WRITE (*,*) I
      END IF
      END
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: