Display the binary cards needed to represent any decimal number

Challenge Level: Ready to expand

Learning outcomes

Students will be able to:


Write a program that asks the user to enter any decimal number as the input and displays the binary cards representing that number (B for displaying black cards with no dots, and W for displaying white cards with dots) as the output.

Testing examples:

Your program should display the outputs shown in this table for the given inputs provided:

Input Output
11 The binary representation for the number 11 is WBWW
255 The binary representation for the number 255 is WWWWWWWW
256 The binary representation for the number 256 is WBBBBBBBB



What it should look like

Click on the green flag, enter the inputs provided in the “testing examples” to see the expected output of your program.

Recommended blocks
when green flag clicked

ask [Please enter a decimal number:] and wait

say (join (join (join [The binary representation for the number ] (answer)) [ is ]) (cards))
repeat until <(number) < (bit value)>

if <<(number) > (bit value)> or <(number) = (bit value)>> then

repeat until <(bit value) = [1]>
set [number v] to (answer)

set [bit value v] to [1]

set [cards v] to []

set [bit value v] to ((bit value) * (2))

set [bit value v] to ((bit value) / (2))

set [cards v] to (join (cards) [W])

set [number v] to ((number) - (bit value))

set [cards v] to (join (cards) [B])
  • Make variables called:

    • “number” and set its value to the input number given by the end user.
    • “bit value” and set its value to ‘1’. Find the smallest bit value which is larger than the “number” by doubling value of “bit value” until it is bigger than the “number”.
    • “cards” is a string variable and stores the binary cards needed (‘B’ for black cards and ‘W’ for white cards).
  • Set the variable “bit value” to 1 and find the smallest “bit value” which is larger than “number” by multiplying “bit value” by 2 (Use the () * () block under “Operators” to multiply the “bit value” by 2) until it is larger than “number”. You can do this by using a repeat until <> loop.

  • Now divide the “bit value” by 2 and check if “number” is greater than or equal to “bit value”. If it is, add ‘W’ to string variable “cards” and subtract “bit value” from the “number”. If not, add ‘B’ to string variable “cards”. Repeat until “bit value” is equal to 1. Display the value of “cards” as the output.

  • Test your program with some values on the boundaries (for example test it with numbers 255 and 256).

Show Scratch solution