8.1 Programming concepts

← Topic 7.9 Writing and amending algorithmsComputer Science contentsTopic 8.2 Arrays →
Chapter 8 · Programming

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.

Variables & constantsData typesSelection & iterationString handlingProcedures & functionsMaintainability

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.

FeatureVariableConstant
Can its value change?YesNo
Typical exampleScore, Radius, CounterPI, MAXSIZE
Good namingUse a meaningful identifierUse 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:

PseudocodePythonVisual BasicJava
DECLARE FirstVar : INTEGERFirstVar = 20Dim FirstVar As Integerint FirstVar;
CONSTANT FirstConst ← 500FIRSTCONST = 500
Convention rather than enforcement
Const FirstConst As Integer = 500final int FIRSTCONST = 500;
Remember: Python does not enforce a special constant type. The programmer must treat a value intended as constant as fixed.
Check variables, constants and declarations.

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 typeMeaningExample
INTEGERPositive or negative whole number25, -8
REALNumber that may contain a fractional part25.0, -3.75
CHAROne character'F'
STRINGZero or more characters; text, digits and printable symbols can be stored"Emma", "123"
BOOLEANOnly TRUE or FALSETRUE

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 typePython exampleVisual BasicJava
INTEGERFirstInteger = 25Dim FirstInt As Integerint FirstInt;
REALFirstReal = 25.0Dim FirstReal As Decimaldouble FirstReal;
CHARFemale = "F"Dim Female As Charchar Female;
STRINGFirstName = "Emma"Dim FirstName As StringString FirstName;
BOOLEANFlag = TrueDim Flag As Booleanboolean Flag;
Can you choose the right type?

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.

LanguageExample: input a real-valued radius
PythonRadius = float(input("Please enter the radius: "))
Visual BasicConsole.Write("Please enter the radius: ")
Radius = Decimal.Parse(Console.ReadLine())
JavaScanner input = new Scanner(System.in);
double Radius = input.nextDouble();

Output with a message

LanguageExample
Pythonprint("Volume of the cylinder is ", Volume)
Visual BasicConsole.WriteLine("Volume of the cylinder is " & Volume)
JavaSystem.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 ", Volume

Python, Visual Basic and Java use different syntax, but the sequence of operations remains the same.

Check input, output and casting.

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 ", Counter

With 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.

PurposePseudocodePythonVisual BasicJava
Single-choice IFIF Age > 17 THEN ... ENDIFif Age > 17:If Age > 17 Then ... End Ifif (Age > 17) { ... }
Alternative pathELSEelse:Elseelse
Multiple choiceCASE OFUsually if / elif / elseSelect Caseswitch / case / default

8.1.4(c) Iteration

Iteration repeats statements. The three loop categories are:

Loop typeWhen usedKey point
Count-controlledNumber of repetitions is knownTypically a FOR loop
Pre-conditionRepeat while a condition is trueMay run zero times
Post-conditionRepeat until/while a condition becomes appropriateBody 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 + 1

In 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:

OperationWhat it doesExample idea
LengthReturns the number of characters, including spacesLENGTH("Computer Science") = 16
SubstringExtracts part of a stringExtract "Science" from "Computer Science"
UpperConverts letters to uppercaseCOMPUTER SCIENCE
LowerConverts letters to lowercasecomputer science
OperationPseudocodePythonVisual BasicJava
LengthLENGTH(MyString)len(MyString)MyString.Length()MyString.length()
SubstringSUBSTRING(MyString, 10, 7)MyString[9:16]MyString.Substring(9, 7)MyString.substring(9, 17)
UpperUCASE(MyString)MyString.upper()UCase(MyString)MyString.toUpperCase()
LowerLCASE(MyString)MyString.lower()LCase(MyString)MyString.toLowerCase()
Indexing difference: the textbook pseudocode example starts strings at position 1, while Python, Visual Basic and Java examples use position 0.

8.1.4(f) Arithmetic, logical and Boolean operators

Arithmetic operators perform calculations; logical comparison operators compare values; Boolean operators combine or reverse conditions.

ArithmeticMeaning
+Add
-Subtract
*Multiply
/Divide
^Raise to a power (language syntax varies)
MODRemainder division
DIVInteger division
ComparisonMeaningTypical programming differences
>, <, >=, <=Greater/less comparisonsSimilar in all three languages
=EqualPython/Java use == for comparison
<>Not equalPython/Java use !=
Boolean ideaPythonVisual BasicJava
ANDandAnd&&
ORorOr||
NOTnotNot!
Practice sequence, selection, loops, strings and operators.

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:

LoopRepresentsValues calculated
Inner loopTests within one subjectSubject total, highest, lowest and average
Middle loopSubjects for one studentStudent total, highest, lowest and average
Outer loopStudents in the classClass 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 average
Testing nested code: use smaller constant values first. Testing 2 students, 2 subjects and 2 tests is much easier than manually tracing the full problem.
Check nested structures.

8.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.

FeatureProcedureFunction
Main purposePerforms a named taskPerforms a named task and returns a value
CallCan be a standalone statementNormally used on the right-hand side of an expression or assignment
ParametersMay have none or may accept parametersMay have none or may accept parameters
Return valueNo required return valueUses 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.

Scope matters: trying to use a variable outside its scope causes an error. In the textbook example, a variable declared only inside a procedure cannot be accessed later by the main program.
Practice procedures, functions, parameters and scope.

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:

RoutinePurposePseudocode exampleResult
MODRemainder after integer divisionMOD(10, 3)1
DIVWhole-number quotientDIV(10, 3)3
ROUNDRound to a stated number of decimal placesROUND(6.97354, 2)6.97
RANDOMProduce a random valueRANDOM()A random value in the routine's range
OperationPythonVisual BasicJava
MOD10 % 310 Mod 310 % 3
DIV10 // 310 \ 310 / 3 when both operands are integers
ROUNDround(6.97354, 2)Math.Round(6.97354, 2)Math.round(...) with scaling when decimals are required
RANDOMUse the random libraryRnd()Use java.util.Random
Check MOD, DIV, ROUND and 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:

LanguageComment style
Python# comment
Visual Basic' comment
Java// single-line comment and /* multi-line comment */
Good comments explain purpose, not the obvious. A comment such as “calculate the subject average after all marks are totalled” is more useful than merely restating a line of code.
Can you recognise maintainable code?

Topic 8.1 revision checklist

Distinguish variables from constants and understand declarations.
Use INTEGER, REAL, CHAR, STRING and BOOLEAN appropriately.
Use prompts, input, casting and labelled output.
Explain why statement sequence matters.
Use selection with IF and multiple-choice constructs.
Choose count-controlled, pre-condition and post-condition loops.
Use running totals and counters.
Use length, substring, upper and lower string operations.
Use arithmetic, comparison and Boolean operators.
Explain and trace nested selection/iteration.
Distinguish procedures and functions, arguments and parameters.
Explain local and global scope.
Use MOD, DIV, ROUND and RANDOM library routines.
Recognise features of a maintainable program.
Ready for a mixed Topic 8.1 check?
← Topic 7.9 Writing and amending algorithmsComputer Science contentsTopic 8.2 Arrays →