The "FooBar" Interview Question

Posted by Tariq Abughofa on September 25, 2019 · 5 mins read #interview

I was asked this question at the interview that got me my first job and I nailed it. The goal from this problem is not to test knowledge of a specific language but the thought process and the coding skills. I found later that it is a common question to ask junior developers so I thought I should share it.

The problem

You have to print the numbers from 1 to 100 each in a new line. But for every number that is a multiple of 5 print “Foo” instead of the number, for every multiple of 7 print “Bar” instead, and for every multiple of both 5 and 7 print “FooBar” instead.

The solution

Let’s start by simplifying the problem: printing the numbers from 1 to 100. The requires a for loop that goes until 100 and for each number it will print the value and a new line:

for (int i=1; i<=100; i++) {
  println(i);
}

Now if the number is a multiple of 5 it will print “Foo”. That’s a branching statement to be added:

for (int i=1; i<=100; i++) {
  if (i % 5 == 0) {
    println("Foo")
  } else {
  	println(i);
  }
}

The same for multiples of 7:

for (int i=1; i<=100; i++) {
  if (i % 5 == 0) {
    println("Foo")
  } else if (i % 7 == 0) {
    println("Bar")
  } else {
  	println(i);
  }
}

Now the tricky part. How can you make it print both “Foo” and “Bar”, no new line in between? The naiive solution is to add another branch inside the first one:

for (int i=1; i<=100; i++) {
  if (i % 5 == 0) {
    if (i % 7 == 0) {
    	println("FooBar")
    } else {
      println("Foo")
    }
  } else if (i % 7 == 0) {
    println("Bar")
  } else {
  	println(i);
  }
}

It works, but a more elegant solution which shows the undestanding of branching without else statements is like this:

for (int i=1; i<=n; i++) {
  if (i % 5 != 0 && i % 7 != 0) {
    println(i);
  } else {
    if (i % 5 == 0) {
      print("Foo")
    }
    if (i % 7 == 0) {
      print("Bar")
    }
	  println();
  }
}

The first if statemnt prints the number if it’s not a multiple of 5 or 7. Otherwise, it prints Foo or Bar (without a new line) depending on what it’s a multiple of. If both it will go into both branches and print both. After that it will add a new line.

I wrote all the code blocks in C++. Try to run it and let me know how it goes :).


Card image cap
How to Ace the Job Interview? - Sort Algorithms

Sorting algorithms are used to apply a specific order according by a comparison operator on...

Card image cap
How to Load Data into an SQL database

Data storage is the most integral part of a transactional database system. In this article,...