8.1 Programming concepts
This topic turns algorithm ideas into programming concepts. You need to understand how data is stored, how input and output are handled, how sequence, selection and iteration control a program, and how procedures, functions and library routines help build clear, maintainable solutions.
8.1.1 Variables and constants
A variable is a named data store whose value may change while a program is running. A constant is a named data store whose value should stay fixed during execution. Both should have meaningful names so another programmer can understand their purpose.
| Feature | Variable | Constant |
|---|---|---|
| Can its value change? | Yes | No |
| Typical example | Score, Radius, Counter | PI, MAXSIZE |
| Good naming | Use a meaningful identifier | Use a meaningful identifier; capital letters are often used to make constants obvious |
Declaring data stores
Some languages require an explicit declaration, where a data type is stated. Other languages infer the type from the value assigned. The source compares pseudocode, Python, Visual Basic and Java:
| Pseudocode | Python | Visual Basic | Java |
|---|---|---|---|
DECLARE FirstVar : INTEGER | FirstVar = 20 | Dim FirstVar As Integer | int FirstVar; |
CONSTANT FirstConst ← 500 | FIRSTCONST = 500Convention rather than enforcement | Const FirstConst As Integer = 500 | final int FIRSTCONST = 500; |
8.1.2 Basic data types
Data types tell the computer what kind of value is being stored and what operations are sensible for that value. The five basic types required here are:
| Data type | Meaning | Example |
|---|---|---|
| INTEGER | Positive or negative whole number | 25, -8 |
| REAL | Number that may contain a fractional part | 25.0, -3.75 |
| CHAR | One character | 'F' |
| STRING | Zero or more characters; text, digits and printable symbols can be stored | "Emma", "123" |
| BOOLEAN | Only TRUE or FALSE | TRUE |
A number stored as a string is text, so it cannot be used directly in arithmetic until it is converted to a numeric type.
| Pseudocode type | Python example | Visual Basic | Java |
|---|---|---|---|
| INTEGER | FirstInteger = 25 | Dim FirstInt As Integer | int FirstInt; |
| REAL | FirstReal = 25.0 | Dim FirstReal As Decimal | double FirstReal; |
| CHAR | Female = "F" | Dim Female As Char | char Female; |
| STRING | FirstName = "Emma" | Dim FirstName As String | String FirstName; |
| BOOLEAN | Flag = True | Dim Flag As Boolean | boolean Flag; |
8.1.3 Input and output
Programs need input statements to receive data and output statements to display results. A useful program should tell the user what to enter and should label its output clearly.
Input and prompts
Keyboard input often arrives as text, so numeric input may need to be converted to an integer or real value. This conversion is often called casting.
| Language | Example: input a real-valued radius |
|---|---|
| Python | Radius = float(input("Please enter the radius: ")) |
| Visual Basic | Console.Write("Please enter the radius: ")Radius = Decimal.Parse(Console.ReadLine()) |
| Java | Scanner input = new Scanner(System.in);double Radius = input.nextDouble(); |
Output with a message
| Language | Example |
|---|---|
| Python | print("Volume of the cylinder is ", Volume) |
| Visual Basic | Console.WriteLine("Volume of the cylinder is " & Volume) |
| Java | System.out.println("Volume of the cylinder is " + Volume); |
Complete idea: volume of a cylinder
The source uses a cylinder program to bring constants, input, arithmetic and output together. The logic is the same in any language:
CONSTANT PI ← 3.142
INPUT Radius
INPUT Length
Volume ← Radius * Radius * Length * PI
OUTPUT "Volume of the cylinder is ", VolumePython, Visual Basic and Java use different syntax, but the sequence of operations remains the same.
8.1.4 Basic concepts
This large subtopic brings together six ideas: sequence, selection, iteration, totalling and counting, string handling, and operators.
8.1.4(a) Sequence
Sequence means carrying out statements in the correct order. Changing the order can change the answer or cause extra values to be processed.
The textbook demonstrates this with a marks algorithm using 999 as a sentinel. In the incorrect sequence, the sentinel is added to the total and counted, so the total, average and count are all wrong. The corrected structure adds the previous valid mark before taking the next input and calculates the average after the loop:
Total ← 0
Mark ← 0
Counter ← -1
OUTPUT "Enter marks, 999 to finish"
REPEAT
Total ← Total + Mark
INPUT Mark
Counter ← Counter + 1
UNTIL Mark = 999
OUTPUT "The total mark is ", Total
Average ← Total / Counter
OUTPUT "The average mark is ", Average
OUTPUT "The number of marks is ", CounterWith test data 25, 27, 23, 999, the corrected algorithm gives a total of 75, average 25 and count 3.
8.1.4(b) Selection
Selection chooses different paths depending on a condition. The main structures are IF and a multiple-choice structure such as CASE.
| Purpose | Pseudocode | Python | Visual Basic | Java |
|---|---|---|---|---|
| Single-choice IF | IF Age > 17 THEN ... ENDIF | if Age > 17: | If Age > 17 Then ... End If | if (Age > 17) { ... } |
| Alternative path | ELSE | else: | Else | else |
| Multiple choice | CASE OF | Usually if / elif / else | Select Case | switch / case / default |
8.1.4(c) Iteration
Iteration repeats statements. The three loop categories are:
| Loop type | When used | Key point |
|---|---|---|
| Count-controlled | Number of repetitions is known | Typically a FOR loop |
| Pre-condition | Repeat while a condition is true | May run zero times |
| Post-condition | Repeat until/while a condition becomes appropriate | Body runs at least once |
Python provides for and while; Visual Basic provides For...Next, While...End While and Do...Loop Until; Java provides for, while and do...while.
8.1.4(d) Totalling and counting
A running total adds each new value to an accumulated total. A counter increases (or decreases) to record how many times something occurs.
TotalWeight ← TotalWeight + Weight
NumberOfItems ← NumberOfItems + 1In Java, NumberOfItems++; is a shorter way to add one to a counter.
8.1.4(e) String handling
A string stores text. The first character position may be numbered from zero or one depending on the language. You need to know four string operations:
| Operation | What it does | Example idea |
|---|---|---|
| Length | Returns the number of characters, including spaces | LENGTH("Computer Science") = 16 |
| Substring | Extracts part of a string | Extract "Science" from "Computer Science" |
| Upper | Converts letters to uppercase | COMPUTER SCIENCE |
| Lower | Converts letters to lowercase | computer science |
| Operation | Pseudocode | Python | Visual Basic | Java |
|---|---|---|---|---|
| Length | LENGTH(MyString) | len(MyString) | MyString.Length() | MyString.length() |
| Substring | SUBSTRING(MyString, 10, 7) | MyString[9:16] | MyString.Substring(9, 7) | MyString.substring(9, 17) |
| Upper | UCASE(MyString) | MyString.upper() | UCase(MyString) | MyString.toUpperCase() |
| Lower | LCASE(MyString) | MyString.lower() | LCase(MyString) | MyString.toLowerCase() |
8.1.4(f) Arithmetic, logical and Boolean operators
Arithmetic operators perform calculations; logical comparison operators compare values; Boolean operators combine or reverse conditions.
| Arithmetic | Meaning |
|---|---|
+ | Add |
- | Subtract |
* | Multiply |
/ | Divide |
^ | Raise to a power (language syntax varies) |
MOD | Remainder division |
DIV | Integer division |
| Comparison | Meaning | Typical programming differences |
|---|---|---|
>, <, >=, <= | Greater/less comparisons | Similar in all three languages |
= | Equal | Python/Java use == for comparison |
<> | Not equal | Python/Java use != |
| Boolean idea | Python | Visual Basic | Java |
|---|---|---|---|
| AND | and | And | && |
| OR | or | Or | || |
| NOT | not | Not | ! |
8.1.5 Use of nested statements
Nesting means placing one selection or iteration structure inside another. For example, an IF can be placed inside a loop, or one loop can be placed inside another.
The textbook worked example uses three nested loops to process marks:
| Loop | Represents | Values calculated |
|---|---|---|
| Inner loop | Tests within one subject | Subject total, highest, lowest and average |
| Middle loop | Subjects for one student | Student total, highest, lowest and average |
| Outer loop | Students in the class | Class total, highest, lowest and average |
The source uses constants for the number of tests, subjects and students so the values can be reduced during testing. Each level has its own totals and maximum/minimum values, and results from an inner level are passed outward to build the next level.
FOR Student ← 1 TO ClassSize
// reset student values
FOR Subject ← 1 TO NumberOfSubjects
// reset subject values
FOR Test ← 1 TO NumberOfTests
INPUT Mark
// update subject high, low and total
NEXT Test
// calculate subject average and update student values
NEXT Subject
// calculate student average and update class values
NEXT Student
// calculate class average8.1.6 Procedures and functions
A repeated group of statements can be placed in a subroutine, defined once and called whenever needed. The two types required here are procedures and functions.
| Feature | Procedure | Function |
|---|---|---|
| Main purpose | Performs a named task | Performs a named task and returns a value |
| Call | Can be a standalone statement | Normally used on the right-hand side of an expression or assignment |
| Parameters | May have none or may accept parameters | May have none or may accept parameters |
| Return value | No required return value | Uses RETURN |
Procedures without and with parameters
PROCEDURE Stars
OUTPUT "************"
ENDPROCEDURE
CALL Stars
PROCEDURE Stars(Number : INTEGER)
FOR Counter ← 1 TO Number
OUTPUT "*"
NEXT Counter
ENDPROCEDURE
CALL Stars(7)An argument is the value supplied in the call; a parameter is the variable in the definition that receives that value. For this course, procedure/function examples use no more than two parameters.
Functions
FUNCTION Celsius(Temperature : REAL) RETURNS REAL
RETURN (Temperature - 32) / 1.8
ENDFUNCTION
MyTemp ← Celsius(MyTemp)Different languages use different terminology: Python often describes procedures as void functions and value-returning routines as functions; Visual Basic uses Sub and Function; Java uses methods, with or without a return value.
Local and global variables
A global variable has scope across the whole program. A local variable can only be used inside the procedure/function or block where it was declared. A local variable can even have the same name as a global variable without referring to the same storage location.
8.1.7 Library routines
Programming environments provide library routines: pre-written, tested functions and procedures for common tasks. Some languages require a library to be imported before its routines can be used.
The four routines highlighted for this course are:
| Routine | Purpose | Pseudocode example | Result |
|---|---|---|---|
| MOD | Remainder after integer division | MOD(10, 3) | 1 |
| DIV | Whole-number quotient | DIV(10, 3) | 3 |
| ROUND | Round to a stated number of decimal places | ROUND(6.97354, 2) | 6.97 |
| RANDOM | Produce a random value | RANDOM() | A random value in the routine's range |
| Operation | Python | Visual Basic | Java |
|---|---|---|---|
| MOD | 10 % 3 | 10 Mod 3 | 10 % 3 |
| DIV | 10 // 3 | 10 \ 3 | 10 / 3 when both operands are integers |
| ROUND | round(6.97354, 2) | Math.Round(6.97354, 2) | Math.round(...) with scaling when decimals are required |
| RANDOM | Use the random library | Rnd() | Use java.util.Random |
8.1.8 Creating a maintainable program
A program may be changed years after it is first written, possibly by a different programmer. Good code should therefore be understandable without relying on the original programmer's memory.
A maintainable program should:
- use meaningful names for variables, constants, arrays, procedures and functions;
- divide the solution into modules for separate tasks, using procedures and functions;
- include useful comments that explain the purpose of sections of code.
| Language | Comment style |
|---|---|
| Python | # comment |
| Visual Basic | ' comment |
| Java | // single-line comment and /* multi-line comment */ |