Question 4

OCR Computer Science June 2023 Algorithms and problem solving (H046-02)AS10 marks

On the specification

(a)
1.4 Data types, data structures and algorithms2.2 Problem solving and programming
(b)
2.2 Problem solving and programming
Question text

4 A function, toBinary(), is needed to calculate the binary value of a denary integer between 0 and 255. toBinary() needs to: • take an integer value as a parameter • divide the number by 2 repeatedly, storing a 1 if it has a remainder and a 0 if it doesn’t • combine the remainder values (first to last running right to left) to create the binary number • return the binary number. For example, to convert 25 to a binary number the steps are as follows: 25 / 2 = 12 remainder 1 12 / 2 = 6 remainder 0 6 / 2 = 3 remainder 0 3 / 2 = 1 remainder 1 1 / 2 = 0 remainder 1 return value = 11001 (a) Write the function toBinary(). You should write your function using pseudocode or program code. [6] (b) The main program: • asks the user to enter a denary number between 1 and 255 • checks that the input is valid between 1 and 255 • If valid call the function toBinary() and pass the input as a parameter • outputs the return value • If not valid, repeatedly asks the user to input a number until the number is valid. Write the algorithm for the main program. You should write your algorithm using pseudocode or program code. [4]