Homework Answers So Far
Homework Answers So Far
Homework Answers So Far
2 – Programming fundamentals
Challenges
Contents
Variable naming, input and output......................................................................................................7
Easy challenges!............................................................................................................................. 7
Question 1:.................................................................................................................................. 7
Question 2:.................................................................................................................................. 7
Question 3:.................................................................................................................................. 7
Question 4:.................................................................................................................................. 7
Question 5:.................................................................................................................................. 7
Question 6:.................................................................................................................................. 7
Medium challenges!........................................................................................................................ 8
Question 7:.................................................................................................................................. 8
Question 8:.................................................................................................................................. 8
Variable Data Types........................................................................................................................... 9
Easy challenges!............................................................................................................................. 9
Question 1:.................................................................................................................................. 9
Question 2:.................................................................................................................................. 9
Question 3:................................................................................................................................ 10
Question 4:................................................................................................................................ 10
Medium challenges!...................................................................................................................... 11
Question 5:................................................................................................................................ 11
Question 6:................................................................................................................................ 11
Question 7:................................................................................................................................ 11
Variables Operators.......................................................................................................................... 12
Easy challenges!........................................................................................................................... 12
Question 1:................................................................................................................................ 12
Question 2:................................................................................................................................ 12
Question 3:................................................................................................................................ 13
Question 4:................................................................................................................................ 13
Question 5:................................................................................................................................ 13
Question 6:................................................................................................................................ 13
Question 2
Explain what makes a good variable name.
Question 3
Describe how a constant is different from a variable.
Question 4
Code a solution that will prompt the user to input a number, multiply it by ten and output the result to the
user.
Question 5
Modify that solution to output the result to the user in this format: <original number> + “x10=” + <result>.
Question 6
Code a solution that will ask the user for three numbers and then output the numbers in the opposite
order from which they were input.
Question 8
Given 2 variables, code a solution that swaps their values.
Question 2
For each of these variables, choose the most appropriate data types, provide a sample value and justify
your choice:
1 Username
2 PhoneNumber
3 Registered
4 Counter
5 DivisionResult
6 PIN
7 FileName
8 AmountOwed
9 Male
10 YearOfBirth
11 DateOfBirth
12 Sorted
13 VotedYes
14 SecretMessage
15 SPEED_OF_LIGHT
Question 4
Given four variables holding words, join them with spaces into a readable sentence.
Question 6
A pupil wrote the following lines of code:
YearOfBirth=”1990”
CurrentYear=”2016”
Age=CurrentYear-YearOfBirth
OUTPUT Age
Can you spot any problems with this code? If yes, how would you fix them?
Question 7
Write a program that can generate a random 4-digit PIN, made up of digits 0-9.
Question 2
For each of these operators, identify the associated data type (could be more than one):
Operator Data type
1 Addition
2 AND
3 ASCII
4 CHR
5 Concatenation
6 Division
7 Equal
8 Escape/whitespace characters
9 Exponentiation
10 integer division
11 Larger
12 Lowercase
13 modular division
14 Modulus
15 Negation
16 NOT
17 Not equal
18 OR
20 Smaller
21 Split
22 Subtraction
23 Titlecase
24 UPPERCASE
Question 3
Volume of a sphere: V=4/3(PI*(r**3))
Question 4
Volume of a cylinder: V=PI*(r**2)*h
Question 5
Volume of a cone: V=PI*(r**2) *h/3
Question 6
A pupil wants to write a program that can tell if a number is odd or even. Which operator can he use for
this and why this operator?
Question 7
Here is an assignment statement for a Boolean variable:
Question 10
Convert 4 character string of a binary number to a decimal value, e.g. “0110” is 6.
Question 11
A pupil has been struggling to keep up with making notes in class. It was taking too long for her to write
things in full. She develops a shorthand system, where all words longer than 5 characters, are shortened
to two first characters, followed by a dash, followed by the two last characters of that word.
For example, “plus” would not be shortened, but “addition” becomes “add-on”, “economics” becomes
“ec-cs”, etc.
Design a program that will use this system on any text string.
Question 1
What is the output, if the inputs are 5,6?
Question 2
Rewrite this process in pseudocode.
Question 3:
Create a flowchart for any of the algorithms we have covered.
Question 4
Create a pseudocode solution for any of the algorithms we have covered.
Num:=5
FUNCTION Doubler(x)
RETURN x*2
END FUNCTION
OUTPUT Doubler(Num) // Prints “10”
Question 6
Rewrite the procedure in Question E2A.1D to have parameters
Question 7
State the names of the parameters of the subroutine.
Question 8
This code contains an error. Identify it and provide a correction.
Question 9
What kind of an error is it?
Question 10
Give an example of how you would refer to this code from elsewhere in a program.
A mobile network operator allows customers to call the automated support number. Once a customer
connects, they are asked to listen to the … choices and enter a number on their phone corresponding to
the menu. At any time, a customer can press zero to hear the first/main menu again.
The following procedures and functions exist to control the process, in no particular order:
customerCallReceived()
terminateCall()
getCustomerPassword()
connectToSales()
getMenuChoice()
tellBalance()
retrieveCustomerDetails()
connectToTechSupport()
Question 12
Which of these are functions and which are procedures? Justify your answer.
Question 13
Design a top-down solution that would model the operation of this vending machine (pseudocode or
flowchart). Your solution will contain the following subprograms:
Question 14
Some of these subprograms feature variable names inside the brackets. What is the meaning of these?
Question 15
Take one of the subprograms and design it (pseudocode or flowchart)
Question 16
It is possible that the machine can be out of stock on certain items, in this case, when that item is chosen
by customer, the machine outputs “Out of stock” and offers user to get their money back or make
another selection. Design a top-down solution that would model the operation of this vending machine
(pseudocode or flowchart). Your solution will contain the following subprograms:
Question 18
Make the procedure even more abstract by letting the number of sides to be another parameter, the
procedure will draw any Polygon. Hint: all angles in a closed polygon add up to 365 degrees.
Question 19
Using the information from Question E2A.5A, design a flowchart that represents the most logical
sequence of these subprograms.
Question 2
What happens when a programmer is using the IF/ELSE IF/ELSE structure and the IF condition and the
ELSE IF condition are both true? Illustrate with an example.
Question 3
Consider the following code:
A:=5
B:=4
AA:=11
A:=9
A:=12
Question 4
Consider the following code:
A:=5
B:=4
AA:=11
IF B<=A THEN
A:=9
ELSE
A:=12
END IF
BEGIN Report
INPUT num
INPUT event
OUTPUT STR(num)+ “ persons signed up for “ + event
HALT
This looks less than professional in the case of a single person signing up to an event – it should really
say “1 person signed up for Choir”. Modify the program accordingly.
Question 6
Given the following code, rewrite this with IF/ELSE IF/ELSE instead of SWITCH.
INPUT Entry
SWITCH Entry
CASE >100
Entry:=Entry*0.75-10
CASE <10
Entry:=0
DEFAULT
Entry:=Entry-10
END SWITCH
Result:=Entry*2
IF Result> 35 THEN
OUTPUT STR(Result) + “Pass”
ELSE
OUTPUT STR(Result) + “Fail”
END IF
Question 7
Entry is 120
Question 9
Entry 52
Question 10
A programmer is coding a menu interface which displays 3 options to the user. The use then presses 1
for the first option, 2 for the second option, 3 for the third option, each of these calls a procedure such as
option1(), option2(), option(3). Code a solution that will validate user input to be only 1, 2 or 3 and then
call the corresponding procedure.
You are writing a program for an airline that calculates the price for oversized baggage (if any) that air
travellers have to pay. The rules are given as follows:
Any baggage that is under 10 kg and is no larger than 40 by 30 cm, ignoring depth, can go free of
charge.
Any baggage that doesn’t satisfy the first criteria, up to 20 kg and 60 by 40 cm, costs £50.
Any baggage that doesn’t satisfy the first and second criteria, is charged £10 per kg.
Baggage over 100 kg and 150 by 150 cm is not allowed at all and should be sent separately by freight.
In this case, the cost variable gets assigned an rogue value of -99.
Question 11
What is the purpose of using a “rogue value”?
Question 12
Design an algorithm for this problem.
1 120 90 60
2 90 100 60
3 13 60 40
4 22 60 40
5 9 30 20
6 50 150 100
Question 14
Add your own test data, trying to test every condition.
Question 16
A drive-through roadside cafe is located on a vantage lookout point with picnic tables and a parking lot.
There is a 10% surcharge for stay-in customers, with take-away customers being charged less as they
tend to leave less of a mess that costs money to clean up. The café sells:
Coffee, in 3 sizes: small (£1), medium(£1.25) and large (£1.40). Additionally, coffee can be offered as
decaffeinated, with or without milk, with or without sugar.
Muffins, all £2
There is a numeric pad positioned by the driveway next to the café, where customers see their service
options on the screen and then they use the pad to indicate their choices. Then they drive up to a
window to receive their purchase and pay. A computer connected to the numeric pad, collects this
information and works out the price, then sends this information to the terminal located in the café’s
kitchen, so that everything is ready by the time a customer drives up to the service window.
order:=""
price:=0
SM_COFFEE:=1
MD_COFFEE:=1.25
LG_COFFEE:=1.4
MUFFIN:=2
ONE_L_WATER:=1.1
ONE_HALF_L_WATER:=1.3
SURCHARGE=1.1
Question 17
Complete the program that will present the customer with the choice of products that the café sells,
quantities of each item purchases and their choice for staying in or taking their purchase with them.
For testing of your program, the café supplied the following sample orders:
1 Medium white and sugar coffees, 2 Large White No Sugar coffee and 1.5L water bottle, stay-in.
1 Medium Decaf black with sugar coffee, 1 Small White With Sugar coffee, 2 Muffins, 1L water, take-
away.
Question 1
Name the two constructs used in the program:
Question 2
State the value that will be output:
1515
Question 3
The value of j depends on the value of i. Complete the table below:
When i =… j is… How many lines of code have been executed?
NULL 0 1
1 0 2
1 1 3
2 3 4
3 6 5
4 10 6
5 15 7
Question 4
For each of the variables i and j, complete the table below:
Iteration i j
0 1 0
1 1 1
1 1 3
2 3 4
3 6 5
4 10 6
5 15 7
Question 6
Write a program that counts from 0 to 1o and then back down.
FOR i=0 TO 10
OUTPUT i
NEXT i
FOR i=10 TO 0 STEP -1
OUTPUT i
NEXT i
Question 7
Modify the previous solution, so that instead of displaying numbers one by one to the screen, the
program joins them into a string that will look like this: "012345678910"
string:=""
FOR i=0 TO 10
string:=string+str(i)
NEXT i
FOR i=10 TO 0 STEP -1
string:=string+str(i)
NEXT i
OUTPUT string
Question 8
Modify the solution now to count down skipping every other number
Question 9
The ASCII code for "A" is 65. Use a condition-controlled loop and then the counter-controlled loop to
display the alphabet.
Question 10
This was all capital letters. Research where lowercase "a" is in the ASCII table and repeat the exercise
with lowercase letters.
a:=""
FOR i=97 TO 122
a:=a+CHAR(i)
NEXT i
OUTPUT a
Question 12
Modify your solution not to change punctuation or whitespace characters.
Question 13
Generate a sequence where every item in a sequence is 2.5 larger than the previous one.
You are given the code for a program that loops adding numbers.
a:=12
b:=2
total:=0
FOR i=1 TO 7
total:=total+a+b-i
a:=a+1
b:=b+2
NEXT FOR
Question 14
What is the sum after 5 iterations?
Question 15
After 6 iterations?
Question 17
Write a program that needs to compute averages of 3 sets of floats
We are given a phrase “The UK has announced that the amphibious landing ship RFA Mounts Bay will
join naval vessels from Germany, Canada, Turkey and Greece in the area.”
Question 19
Write a program that will make every other letter uppercase, lowercase e.g. ThE Uk HaS, etc.
Question 20
Now let’s make all vowels upper case, all consonants - lower case, where vowels are: i,o,a,e,u
Question 21
Now reverse the condition and vowels are now lower case, consonants – upper
Array Numbers[78,1,45,23,98,57]
Question 2
Numbers[0]
Question 3
Numbers[3]
Question 4
Numbers[5]
Question 5
Write an algorithm to output the value of the last array element of any array
Question 7
Write an algorithm to generate an array of sums of individual items from Nums1 and Nums2, e.g.
Nums3[44,79,18]
Question 8
Write an algorithm to generate an array that includes both of these arrays' items in one longer array, e.g.
Nums4[34,67,23,10,12,15]
Question 9
Write an algorithm to generate a 2D array from these two 1D arrays.
Question 10
Given a comma-separated list of numbers, write an algorithm to add them up and output the total.
Question 11
Modify your solution for Question M2D.3A to only add up even numbers
Question 13
Modify your solution so that rather than adding up the array elements, the program will find out the sum
of the changes from item to item, e.g. instead of adding up 24, 26, 45, .... just add 2 (26-24), 19 (45-
26),...
Test[”Peter”,”Amir”,”Jack”, “Bob”,”Nora”]. Your solution should work for an array of any odd size, not
just size 5.
Question 15
However, what about arrays of even size, e.g. 4, 6, 8, etc elements? Our Python code which is based on
the algorithm - crashed!
Question 16
Create a universal solution that works for both odd and even array sizes.
Array Boundaries[["A*","90"],["A","80"],["B","70"],["C","60"],["D","50"]]
Question 18
Extend the program to input a 1D array of scores to convert to grades.
Question 19
Modify the program to get the score information from a 2D array of data which contains pupils’ names
and scores.
0 1 2 3 4
Bob Nora Rezaq Peter Jon
56 78 92 85 67
Question 2
Modify the algorithm to count all instances of “the”.
Question 3
Modify the algorithm to count all instances of all words starting with “a”
Question 4
Create an algorithm to read two text files, and then write their contents to the third file.
Question 5
Now modify your solution to read another input file and add its contents to the output file from the
previous task.
Question 6
Create an algorithm to load a text out of a file and write to another file backwards.
Question 8
The mail merge. You are given two text files: one file is a letter template, which, instead of actual names,
contains a word “<name>”; the other file is a list of names. Create an algorithm to generate individually
addressed letters or wedding invites.
Question 2
Assuming that a machine’s cost can’t exceed 9,999, what is the maximum length of one record?
Estimate the maximum size of a file containing 200 records, assuming 10% overhead (additional data
stored in the file that is in addition to the record data itself).
Question 3
Create an array of 3 machines. Assume these machines have just been purchased and we need to know
how much we must pay. Code the solution to arrive at that amount.
TYPE RECORD Machine(STRING VARCHAR=10 Name, STRING CHAR=4 Type, FLOAT Cost)
SQL
A school has sent a few teams to an Athletics competition. You are given a table of athletes who won
Gold, Silver, Bronze. Multiple age categories were involved, so it is possible to have more than one
medal in the same category, as the multiple medals were awarded to different age groups.
Question 4
Write an SQL SELECT query to return all complete records.
Question 5
Write an SQL SELECT query to return all complete records in alphabetic order.
Question 6
Write an SQL SELECT query to return all complete records in reverse alphabetic order.
Question 7
Write an SQL SELECT query to return complete records of all those who won Silver medals in 100m.
Question 8
Write an SQL SELECT query to return complete records of all those who won medals in 100m.
Question 10
Write an SQL SELECT query to return complete records of all those who won Gold medals and are not
injured.
Question 11
Write an SQL SELECT query to count how many athletes got Bronze in 100m
Question 12
Write an SQL SELECT query to return complete records of all those who won any medals.
Question 13
Write an SQL SELECT query to list the names of all those who won medals.
Question 14
Write an SQL SELECT query to list all those with medals not injured.
Question 16
Write an SQL SELECT query to return Name and the Injured status, with those Injured
(Injured=”FALSE”) listed first.
Question 17
Write an SQL SELECT query to find all those who got no medals.
Question 18
Write an SQL SELECT query to find all athletes who have letter “o” in their name.
Question 19
Write an SQL SELECT query to find all athletes who have names shorter than 5 characters.
Jobs(JobID CHAR=4, CustomerID CHAR=3, Estimate FLOAT, Completed BOOLEAN, Paid BOOLEAN)
Question 20
Write an SQL SELECT query to return complete records from jobs for all unfinished jobs.
Question 22
Write an SQL SELECT query to get names of customers whose jobs haven’t been completed.
Question 23
Write an SQL SELECT query to get names of customers who have unpaid jobs.
Question 24
Write an SQL SELECT query to get the names of industrial customers
Question 25
Write an SQL SELECT query to get all jobs ordered by non-industrial customers.
Question 27
Write an SQL SELECT query to get all jobs ordered by industrial customers, except Nora.
Question 28
Write an SQL SELECT query to get all jobs with estimate less than 900.
Question 29
Write an SQL SELECT query to get all customers that made orders under 900.
Question 30
Write an SQL SELECT query to get all customers that ordered more than 1000 worth of roofing.
Question 32
Write an SQL SELECT query to count the number of jobs that are for industrial customers
Question 33
Write an SQL SELECT query to count the number of unfinished jobs that are for industrial customers
A school’s VLE system uses record structure to store account information. It has a field for a subject
name taken by a pupil which is set up to be CHAR(5). Unfortunately, many subjects have names longer
than that. The solution is to store them in abbreviated form, with a first few characters of the subject
name followed by a number of characters that didn’t “fit”.
E.g. “Algebra” has 7 characters, so it will be shortened to “ALGE3”, and “Critical Thinking” (17
characters) to “CRI12”.
Question 34
Explain how “Critical Thinking” is shortened to “CRI12”.
Question 36
Task A: Find the range of values given 2 numbers.
Question 37
Task B: Find the range of values given a 1D array
Question 39
Task D: Find the range of values given a record array.
Question 41
Design a solution that takes 4 numbers from a user and outputs their sum, max and min.
Question 43
A teacher wants to set up random pairs out of pupils to participate in a task, where Group A pupils are
advanced and Group B pupils need assistance. Design the solution that will do that.
A teacher repeats the same operation: if a supply teacher needs to register a form, he/she would ask
which form, assuming we have at least two files with form names where files names are in the format
<form_name.txt>.
A teacher would find the first name in the student list, read it out, mark as either present or not present,
then find the second name in the list, read it out, mark as either present or not present, etc.
Write a program that reads a list of students from a file, then displays them on a screen one at a time,
with the prompt for the user to either mark them as “p” for present or “n” for not present.
Once every name has been processed, the program will display the list, with the names in one column
and the “p” or “n” in another. This gets saved to a new file which name is a concatenation of the form
name and today's date + ‘CSV’ extension.
Question 45
How would you code a solution to displaying all the names of files in a folder?
Question 47
Modify the solution to also show the count of how many files have the ‘TXT’ extension.
Question 49
Revisit our earlier question on converting binary number in string format to decimal values. Modify the
solution to use iteration.
//Method 1
B:=”1110”
Decimal:=0
FOR i=0 TO 4
Decimal:=Decimal+INT(B[4-i-1])*2**i
NEXT i
OUTPUT Decimal
Python:
b="1110"
result=0
print("start iteration method 2")
for i in range(0,4):
print(int(b[4-i-1])*2**(i+1))
result=result+int(b[4-i-1])*2**i
print(result)
A 2D array got corrupted when it was saved to a text file. Its contents are given in a variable raw_data...
“Bob,123,Serge,Jenny,34,67
0,Peter,Nora,90,120,Noah
56.4,False,Chuck,Don,78,98”
Question 51
Write an algorithm that would convert this into a string array (1D) and search it for the name ‘Chuck’. If
successful, it will return the index of ‘Chuck’ in the array.
Question 53
Given a 2D array, swap its columns around.
Given the following data file, create a program that calculates Break Even quantity for each product.
Fixed Cost is £2000. For extensions, make it write the result to another file, and as an additional
extension, style this file in HTML, including the use of table tags and images.
(http://www.w3schools.com/tags/tag_table.asp)
Looking for a resource? There is now a quick and easy search tool to help find free resources for your qualification:
www.ocr.org.uk/i-want-to/find-resources/
Our documents are updated over time. Whilst every effort is made to check all documents, there may be contradictions between published support and the specification, therefore
please use the information on the latest specification at all times. Where changes are made to specifications these will be indicated within the document, there will be a new version
number indicated, and a summary of the changes. If you do notice a discrepancy between the specification and a resource please contact us at:
[email protected].
© OCR 2020 - This resource may be freely copied and distributed, as long as the OCR logo and this message remain intact and OCR is acknowledged as the originator of this
work. OCR acknowledges the use of the following content: n/a
Please get in touch if you want to discuss the accessibility of resources we offer to support delivery of our qualifications: [email protected]