Convert a positive decimal number to a binary number

Challenge Level: Ready to expand

Learning outcomes

Students will be able to:

Requirement:

Write a program that asks the user to enter any decimal number as the input and displays the binary cards representing that number using '1' for dots showing and '0' for not showing as the output (this converts the decimal number to binary). Do this by working out the largest bit value needed, and then working down through smaller bit values.

Testing examples:

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

Input Output
31 The binary representation for the number 31 is 11111
32 The binary representation for the number 32 is 100000
1 The binary representation for the number 1 is 1

Languages

Scratch

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 ]) (binary number))
if <<(decimal number) > (bit value)> or <(decimal number) = (bit value)>> then
else
end

repeat until <(decimal number) < (bit value)>
end

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

set [bit value v] to [1]

set [binary number v] to []

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

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

set [binary number v] to (join (binary number) [1])

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

set [binary number v] to (join (binary number) [0])
Hints
  • Make variables called:

    • “decimal 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 “decimal number” by doubling value of “bit value” until it is bigger than the “decimal number”.
    • “binary number” is a string variable and stores the binary cards needed (‘1’ for dots showing and ‘0’ for not showing).
  • Set the variable “bit value” to 1 and find the smallest “bit value” which is larger than “decimal number” by multiplying “bit value” by 2 (Use the () * () block under “Operators” to multiply the “bit value” by 2) until it is larger than “decimal number”. You can do this by using a repeat until <> loop.

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

Show Scratch solution

Python