← GCSE Computer Science · OCR · GCSE Computer Science revision
⭐ 0
OCR GCSE Computer Science (J277) · 2.2 Programming fundamentals
Mini-Lesson

Programming fundamentals

6 missions. Guess, learn, then check. Your place is saved.

  1. Mission 1How does a game turn 135 seconds into 2:15 on its timer?
  2. Mission 2How can a few lines of code print all 100 times-table answers?
  3. Mission 3How can one name hold all 9 squares of a noughts and crosses board?
  4. Mission 4Two subroutines both use a variable called total. Why no clash?
  5. Mission 5How does an app show only the last 4 digits of your card number?
  6. Mission 6How can one line of SQL find every overdue book in a library?
Mission 1

How does a game turn 135 seconds into 2:15 on its timer?

Make a guess: How does a game turn 135 seconds into 2:15 on its timer?

Programming · data and operators

Variables, constants, input and output

Variables and constantslives32assignmentvariableMAX_LIVES3constantvariable: value can changeconstant: value fixed while running
  • A variable is a named memory location whose value can change while the program runs.
  • A constant is a named value that cannot change while the program runs. Naming it means one place to update it, and clearer code.
  • Assignment puts a value into a variable; the first assignment is initialisation. Use meaningful identifiers like lives, not x.
OCR Exam Reference Language
const maxLives = 3
lives = maxLives
name = input("Enter your name")
print("Good luck, " + name)
lives = lives - 1
print(lives)
Programming · data and operators

Data types

  • A data type tells the computer what kind of data a variable holds and which operations make sense.
Data typeHoldsExamples
Integera whole number42, -7, 0
Reala number that can have a fractional part3.5, -0.25, 12.0
Booleanone of two valuesTrue, False
Characterone single character'A', '7', '@'
Stringa sequence of characters'Hello', '07700 900123'
Quick check
?A program stores a customer's phone number, such as 07700 900123. Which data type is most suitable?
Programming · data and operators

Arithmetic operators

Integer division and remainder200 seconds60606020integer division = 3200 DIV 60remainder = 20200 MOD 60
  • +, - and * work as in maths. Real division / can give a fractional answer.
  • Integer division gives only the whole-number part. The remainder (modulus) is what is left over.
Operation200 seconds ÷ 60Result
Real division200 / 603.333…
Integer division200 DIV 603
Remainder200 MOD 6020
  • OCR calls DIV the quotient and MOD modulo.
OCR Exam Reference Language
total = 200
minutes = total DIV 60    // 3
seconds = total MOD 60    // 20
Calculate
?A shop packs eggs in boxes of 6. It has 47 eggs. What value does the program store in spare?
OCR Exam Reference Language
boxes = 47 DIV 6
spare = 47 MOD 6
Calculate
?What value is stored in result?
OCR Exam Reference Language
result = 2 ^ 5
Programming · data and operators

Casting

Casting'15'stringint()15integer+ 1 → 16
  • Casting converts a value from one data type to another, e.g. the string '15' to the integer 15.
  • Keyboard input usually arrives as a string, so cast it before doing arithmetic.
  • Cast numbers to strings to join them into a message.
  • OCR: int(), float() or real(), str(), bool(). The change is temporary: the original variable keeps its type.
OCR Exam Reference Language
age = int(input("Enter your age"))
print(age + 1)
print("Next year: " + str(age + 1))
Quick check
?A user types 15 for their age. The program reads it as a string and needs to output the age next year. What must happen first?
Mission check

?How does a game turn 135 seconds into 2:15 on its timer?
Mission 2

How can a few lines of code print all 100 times-table answers?

Make a guess: How can a few lines of code print all 100 times-table answers?

Programming · control flow

Sequence and selection

Selection flowchartYesNoYesNoStartmark = 72mark >= 70?Output"Distinction"mark >= 40?Output "Pass"Output "Fail"Stop
  • Sequence: statements run one after another, in order.
  • Selection: a condition that is true or false decides which block of code runs.
  • Compare with <, >, <=, >=, equal to == and not equal to !=.
  • Join conditions with AND, OR, NOT.
OCR Exam Reference Language
mark = 72
if mark >= 70 then
    print("Distinction")
elseif mark >= 40 then
    print("Pass")
else
    print("Fail")
endif
Quick check
?What is output when this code runs?
OCR Exam Reference Language
temp = 18
wind = 35
if temp > 15 AND NOT (wind > 30) then
    print("Picnic")
else
    print("Stay in")
endif
Programming · control flow

CASE statements

  • A switch (CASE SELECT) statement picks one branch by comparing one variable with a list of values.
  • Cases are checked in order; the first match runs, then the statement ends.
  • default runs if no case matches.
  • It is neater than a long chain of IFs when you test one variable for exact values.
OCR Exam Reference Language
day = input("Enter a day")
switch day:
    case "Sat":
        print("Weekend")
    case "Sun":
        print("Weekend")
    default:
        print("Weekday")
endswitch
Programming · control flow

Count-controlled loops

  • Iteration repeats a block of code.
  • A count-controlled loop repeats a fixed number of times. A counter variable goes up by 1 each time unless a step is given.
OCR Exam Reference Language
for count = 1 to 5
    print(count * 3)
next count

All output 3, 6, 9, 12, 15.

Programming · control flow

Condition-controlled loops

  • A condition-controlled loop repeats until a condition changes, so you need not know the number of passes.
  • A WHILE loop tests the condition at the start: it may run zero times.
  • do … until tests at the end, so it always runs at least once.
OCR Exam Reference Language
total = 1
while total < 50
    total = total * 2
endwhile
print(total)

All output 64.

Your answer
?What is output when this code runs?
OCR Exam Reference Language
n = 3
while n < 40
    n = n * 2
endwhile
print(n)
Programming · control flow

Nesting

Nested loopsrowcoloutput111122133212224236313326339inner loop:3 passesinner loop:3 passesinner loop:3 passesouter loop:3 passes
  • Nesting puts one construct inside another: an IF inside a loop, a loop inside an IF, or a loop inside a loop.
  • With nested loops, the inner loop runs in full for every pass of the outer loop.
  • Total passes of the inner block = outer passes × inner passes.
OCR Exam Reference Language
for row = 1 to 3
    for col = 1 to 3
        print(row * col)
    next col
next row

Output: 1, 2, 3, 2, 4, 6, 3, 6, 9 (9 values).

Calculate
?How many values does this code output?
OCR Exam Reference Language
for i = 1 to 4
    for j = 1 to 6
        print(i + j)
    next j
next i
Mission check

?How can a few lines of code print all 100 times-table answers?
Mission 3

How can one name hold all 9 squares of a noughts and crosses board?

Make a guess: How can one name hold all 9 squares of a noughts and crosses board?

Programming · data structures

Arrays

An arrayscores12071923441520indexOUTPUT scores[1]
  • An array is a data structure: it stores many values under one identifier. Each value is an element.
  • All elements have the same data type, and the array has a fixed length (static).
  • An index picks out one element. The first element has index 0.
OCR Exam Reference Language
array scores = [12, 7, 9, 15, 4]
print(scores[1])      // 7
scores[3] = 20        // 15 becomes 20
Programming · data structures

Looping through an array

  • Use a variable as the index in a count-controlled loop to visit every element in turn.
  • The counter runs from 0 to length − 1.
OCR Exam Reference Language
array temps = [18, 21, 17, 22, 19]
total = 0
for i = 0 to 4
    total = total + temps[i]
next i
print(total)

All output 97.

Your answer
?What is output when this code runs?
OCR Exam Reference Language
array nums[5]
for i = 0 to 4
    nums[i] = i * 3
next i
print(nums[2] + nums[4])
Programming · data structures

2D arrays

A 2D arraycolumnrow00121X2Oboard[1,1]
  • A two-dimensional (2D) array is like a table: one identifier, with rows and columns.
  • Each element needs two indexes: board[row, col] (row first here).
  • A noughts and crosses board is a 3 × 3 2D array of characters.
  • A 2D array can emulate a database table: each row is a record and each column a field.
OCR Exam Reference Language
array board[3,3]
board[1,1] = "X"     // centre square
board[2,0] = "O"     // bottom-left square
Quick check
?This table shows a 2D array marks with 3 rows and 4 columns (row first). What is marks[1, 2]?
5829
7163
410110
Programming · data structures

Records

A recordPetname'Biscuit'species'dog'age4weight12.5vaccinatedTrueStringIntegerRealBooleanarray: onedata type
  • A record groups related data about one item under one name.
  • Each item of data in a record is a field. Fields can have different data types.
  • Compare: an array's elements all share one data type, but a record mixes types.
FieldData typeExample
nameString'Biscuit'
speciesString'dog'
ageInteger4
weightReal12.5
vaccinatedBooleanTrue
Quick check
?A club stores each member's name, age and whether they have paid. Which structure best holds one member's details?
Mission check

?How can one name hold all 9 squares of a noughts and crosses board?
Mission 4

Two subroutines both use a variable called total. Why no clash?

Make a guess: Two subroutines both use a variable called total. Why no clash?

Programming · subroutines

Subroutines

Calling a proceduremain programwelcome()welcome()end of programprocedurewelcomeshows thewelcome message1234
  • A subroutine is a named, out-of-line block of code. It runs when you call it by its name, then control returns to the line after the call.
  • A procedure carries out a task. A function carries out a task and returns a value.
  • Your board calls subroutines sub programs.
OCR Exam Reference Language
procedure welcome()
    print("Welcome to the quiz")
endprocedure

welcome()
welcome()
Programming · subroutines

Parameters and return values

  • A parameter passes data into a subroutine when it is called. Values are matched to parameters in order.
  • A function sends its result back with return. The returned value replaces the call, so store it or use it straight away.
OCR Exam Reference Language
function area(width, height)
    result = width * height
    return result
endfunction

roomArea = area(4, 5)
print(roomArea)    // 20
Your answer
?What is output when this code runs?
OCR Exam Reference Language
function change(paid, price)
    return paid - price
endfunction

print(change(20, 13) * 2)
Programming · subroutines

Local and global variables

Local and globalmain programaddBonusnewScore15localbonus5globalreadable insideaddBonusnewScore?local: exists only while addBonus runs
  • A local variable is declared inside a subroutine: it only exists while that subroutine runs and is only usable inside it.
  • A global variable is declared in the main program and can be used anywhere.
  • Good practice: nothing outside can change a local variable, and its name can be reused elsewhere.
  • Declare a global with the global keyword. Constants can also be local or global.
OCR Exam Reference Language
global bonus = 5
function addBonus(score)
    newScore = score + bonus    // newScore is local
    return newScore
endfunction

print(addBonus(10))    // 15
print(newScore)        // error: newScore does not exist here
Quick check
?A subroutine calcTax declares a local variable tax and returns its value. After calling calcTax, the main program tries to output tax. What happens?
Programming · subroutines

Why use subroutines?

  • Reuse: write code once and call it many times, so there is less to write and check.
  • Decomposition: each subroutine solves one part and can be written and tested on its own.
  • Maintenance: fix or improve the code in one place.
  • Arrays can be passed into, and returned from, sub programs.
Quick check
?Which task should be written as a function rather than a procedure?
Mission check

?Two subroutines both use a variable called total. Why no clash?
Mission 5

How does an app show only the last 4 digits of your card number?

Make a guess: How does an app show only the last 4 digits of your card number?

Programming · strings, files and random numbers

Strings have positions

String positionscard40912293142536475869710811912013114215length = 16
  • A string is a sequence of characters. Each character has a position, its index.
  • The first character is at index 0, so the last is at length − 1.
  • The length of a string is how many characters it holds, spaces included.
  • A card number is stored as a string, not an integer: it is never used in arithmetic.
OCR Exam Reference Language
card = "4929123456789012"
print(card.length)
// prints 16
Programming · strings, files and random numbers

Taking a substring

Taking a substringcard40912293142536475869710811912013114215****9012start index = 16 − 4 = 12result
  • A substring is part of a string, picked out by position.
  • string.substring(x, i) starts at index x and takes i characters; .left(i) and .right(i) take characters from either end.
  • Using the length makes the code work for any card length.
OCR Exam Reference Language
card = "4929123456789012"
last4 = card.substring(card.length - 4, 4)
print("****" + last4)
Your answer
?Trace this code. What is output?
OCR Exam Reference Language
word = "computer"
print(word.substring(3, 3))
Programming · strings, files and random numbers

More string tools

  • Concatenation joins strings with +.
  • .upper and .lower change case: "Hi".upper gives "HI".
  • ASC("A") gives 65; CHR(97) gives "a".
Programming · strings, files and random numbers

Random numbers

  • Games, quizzes and simulations need unpredictable values, such as a dice roll.
  • The range you give includes both ends: (1, 6) can give 1, 2, 3, 4, 5 or 6.
OCR Exam Reference Language
dice = random(1, 6)
print(dice)
Calculate
?How many different values can this code output?
OCR Exam Reference Language
print(random(5, 9))
Programming · strings, files and random numbers

Reading and writing files

Filesprogramscores.txtAnn,35Ben,28Zara,42openwritereadcloseWhen the program endsRAMline–variable emptiedscores.txt3 lines keptfile keeps its contents
  • Variables are lost when a program ends. A file in secondary storage keeps data, such as high scores, for next time.
  • Open the file, read or write it, then close it so the data is saved and the file is freed.
  • open() opens a file; .readLine() reads the next line; .writeLine() adds a line to the end; .endOfFile() is True after the last line; newFile() creates a file.
OCR Exam Reference Language
scores = open("scores.txt")
scores.writeLine("Zara,42")
scores.close()
scores = open("scores.txt")
while NOT scores.endOfFile()
  print(scores.readLine())
endwhile
scores.close()
Quick check
?A game keeps its high-score table in a variable. Every time the game closes, the scores vanish. What fixes this?
Mission check

?How does an app show only the last 4 digits of your card number?
Mission 6

How can one line of SQL find every overdue book in a library?

Make a guess: How can one line of SQL find every overdue book in a library?

Databases · SQL

SELECT and FROM

SELECT and FROMLoanFROM chooses the tableLoanIDTitleGenreDaysLateMemberIDL01HolesAdventure0M01L02WonderDrama3M02L03CoralineFantasy0M03L04SkelligFantasy7M04L05HolesAdventure2M05L06MatildaFantasy5M02SELECT chooses columnsResultTitleDaysLateHoles0Wonder3Coraline0Skellig7Holes2Matilda5
  • SQL (Structured Query Language) is used to search for data in a database.
  • SELECT lists the fields you want to see, separated by commas.
  • FROM names the table to search.
  • This query shows the Title and DaysLate of every record in Loan:
SQL
SELECT Title, DaysLate
FROM Loan
LoanIDTitleGenreDaysLateMemberID
L01HolesAdventure0M01
L02WonderDrama3M02
L03CoralineFantasy0M03
L04SkelligFantasy7M04
L05HolesAdventure2M05
L06MatildaFantasy5M02
Databases · SQL

WHERE picks the records

WHERE keeps matching rowsLoanWHERE Genre = 'Fantasy'LoanIDTitleGenreDaysLateMemberIDL01HolesAdventure0M01L02WonderDrama3M02L03CoralineFantasy0M03L04SkelligFantasy7M04L05HolesAdventure2M05L06MatildaFantasy5M02WHERE keeps matching rowsResultTitleDaysLateCoraline0Skellig7Matilda5
  • WHERE gives a condition. Only records that meet it are returned.
  • Compare with = < > <= >= and <> (not equal).
  • Put text values in quotes: Genre = 'Fantasy'. Numbers need no quotes.
SQL
SELECT Title, DaysLate
FROM Loan
WHERE Genre = 'Fantasy'

Result: Coraline 0, Skellig 7, Matilda 5.

Your answer
?Use the Loan table. What does this query return? Give the values in order, separated by commas.
SQL
SELECT LoanID
FROM Loan
WHERE DaysLate >= 5
Databases · SQL

Writing a query

  • Read the question for the fields to show (SELECT), the table (FROM) and the rule (WHERE).
  • Fields in WHERE do not have to appear in SELECT.
SQL
SELECT Title, Genre
FROM Loan
WHERE DaysLate > 4

Returns Skellig Fantasy and Matilda Fantasy.

Quick check
?Which query lists the titles of the books more than 4 days late?
Mission check

?How can one line of SQL find every overdue book in a library?
Recap

Big ideas

  • A variable is a named memory location whose value can change; a constant keeps one value while the program runs.
  • Choose the data type that fits the data: integer, real, Boolean, character or string, and cast between types when needed (input text to an integer).
  • Integer division gives the whole-number part; the remainder (modulus) gives what is left over.
  • Sequence runs statements in order; selection uses a true/false condition to choose a branch (if or switch).
  • Count-controlled loops repeat a fixed number of times; condition-controlled loops repeat until a condition changes, tested at the start or the end.
  • In nested loops the inner loop runs fully for every pass of the outer loop.
  • An array holds many values of one data type under one identifier; an index picks out an element (the first is index 0).
  • A 2D array is a table of rows and columns, so each element needs two indexes.
  • A record groups fields of different data types about one item.
  • A subroutine is a named block of code called by its name; a function returns a value and a procedure does not.
  • Parameters pass data in, in order; return passes a result back to the call.
  • Local variables exist only inside their subroutine while it runs, so the same name can be reused safely; global variables can be used anywhere.
  • A string is a sequence of characters, each with an index; the length is how many characters it has. Indexes start at 0.
  • A substring picks out part of a string by position.
  • Concatenation joins strings with +.
  • Files keep data after a program ends: open, read or write, close.
  • Random number functions give a value in a range, including both ends.
  • SELECT fields FROM table WHERE condition: the fields to show, the table to search and the records to keep.
🏆

Mini-lesson complete!

⭐⭐⭐

You've worked through Programming fundamentals for OCR GCSE Computer Science (J277). 🎉

  1. Mission 1How does a game turn 135 seconds into 2:15 on its timer?
  2. Mission 2How can a few lines of code print all 100 times-table answers?
  3. Mission 3How can one name hold all 9 squares of a noughts and crosses board?
  4. Mission 4Two subroutines both use a variable called total. Why no clash?
  5. Mission 5How does an app show only the last 4 digits of your card number?
  6. Mission 6How can one line of SQL find every overdue book in a library?

Your stars: 0 / 0

Next: test yourself in the Verify stage.

📣 Smashed it? Share your score

Challenge a mate to beat your stars, or show a parent how you got on.

→ Back to GCSE Computer Science · OCR

Specification points and sources for this lesson are listed at the bottom of the page.

Sources (6)

The specification points and sources behind this lesson.

  1. 1 OCR J277 spec v3.1, 2.2.1, 2.2.2; section 3c Exam Reference Language
  2. 2 OCR J277 spec v3.1, 2.2.1; section 3c Exam Reference Language
  3. 3 OCR J277 spec v3.1, 2.2.3 and guidance; section 3c ERL Arrays
  4. 4 OCR J277 spec v3.1, 2.2.3 and guidance; section 3c ERL (global, procedure, function)
  5. 5 OCR J277 spec v3.1, 2.2.3; section 3c Exam Reference Language (string handling, file handling, random numbers)
  6. 6 OCR J277 spec v3.1, 2.2.3 (SQL commands SELECT, FROM, WHERE)