Technical Interview Question – Fizz Buzz

Here is a common question that’s usually asked in the first-round interview stage. The typical question is something like:

Print out the numbers 1 to 100. Where the number is a multiple of 3, print ‘Fizz’, otherwise if it is a multiple of 5 print ‘Buzz’. If the number is a multiple of 3 and 5, print ‘FizzBuzz’.

// PHP

for ($i = 1; $i <= 100; $i++)
{
    if ($i % 3 == 0 && $i % 5 == 0) {
        echo 'FizzBuzz';
    }
    else if ($i % 3 == 0) {
        echo 'Fizz';
    }
    else if ($i % 5 == 0){
        echo 'Buzz';
    }
    else {
        echo $i;
    }
}
# PERL

for (my $count = 1; $count <= 100; $count++)
{
    if (($count % 3 == 0) && ($count % 5 == 0)) {
        print "FizzBuzz\n";
    }
    elsif ($count % 3 == 0) {
        print "Fizz\n";
    }
    elsif ($count % 5 == 0) {
        print "Buzz\n";
    }
    else {
        print $count . "\n";
    }
}
// JAVASCRIPT

for (var count = 1; count <= 100; count++)
{
    if ((count % 3 == 0) && (count % 5 == 0)) {
        console.log('FizzBuzz');
    }
    else if (count % 3 == 0) {
        console.log('Fizz');
    }
    else if (count % 5 == 0) {
        console.log('Buzz');
    }
    else {
        console.log(count);
    }
}
// JAVA

public class FizzBuzz {                      
    public static void main(String[] args) {   
        for(int i = 1; i <= 100; i++) {                    
            if (((i % 5) == 0) && ((i % 3) == 0))            
                System.out.println("FizzBuzz");    
            else if (i % 3 == 0) {
                System.out.println("Fizz"); 
            }
            else if (i % 5 == 0) {
                System.out.println("Buzz"); 
            }
            else {
                System.out.println(i);
            }
        }
    }
}
// PYTHON

for count in xrange(1,101):
    if count % 5 == 0 and count % 3 == 0:
        print "FizzBuzz"
    elif count % 3 == 0:
        print "Fizz"
    elif count % 5 == 0:
        print "Buzz"
    else:
        print count

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