Bitpath

Boss lesson · Unit 02

FizzBuzz and friends

Loops and conditions together, and the off-by-one error

13 exercisesabout 3 min

What you practise

  • Loops and conditions together: FizzBuzz, summing digits, testing for a prime, the off-by-one error found and fixed

Try a question from this lesson

Pick one

FizzBuzz: count up from 1. Say Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, else the number. What do you say at 15?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Taking a number apart

Two small tools pull the digits out of a whole number.

n % 10 is the last digit: the remainder after dividing by 10.

Math.floor(n / 10) is the number without its last digit. Math.floor rounds down to a whole number, so 47.2 becomes 47.

Repeat both in a loop and you visit every digit, from the right.

TypeScript
let n = 472;
console.log(n % 10);             // 2
console.log(Math.floor(n / 10)); // 47

Concept

A prime test

A prime number can be divided exactly only by 1 and by itself: 2, 3, 5, 7, 11 ...

To test a number, try every possible divider from 2 up to one below it. If any of them leaves no remainder, the number is not prime.

Start by assuming it is prime, and let the loop prove otherwise.

TypeScript
let n = 15;
let prime = true;
for (let d = 2; d < n; d++) {
  if (n % d === 0) {
    prime = false;
  }
}
console.log(prime); // false

10 more exercises in the app

  • 3× multiple choice
  • 1× fill the blanks
  • 4× type the answer
  • 1× order the lines
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy