logo

Cambridge IGCSE Computer Science revision notes

P rogramming concepts Revision Notes

Cambridge IGCSE revision notes for P rogramming concepts.

At a glance

revision notes

Resource type

Topic

P rogramming concepts

CambridgeIGCSEComputer ScienceProgramming

Complete revision guide 1 of 8

Declare and Utilize Variables and Constants in Programming

This note explains how to declare and use variables and constants in programming, highlighting their differences, purposes, and practical examples to support effective program design and execution.

Syllabus source

Section 3, Topic 8.1, page 27, objective 8.1.1

Open source document ↗

What you should be able to do

  • ✓Understand what variables and constants are in programming.
  • ✓Learn how to declare variables and constants correctly.
  • ✓Recognize the difference between variables and constants in terms of mutability.
  • ✓Apply variables and constants appropriately in simple programming tasks.
  • ✓Use meaningful identifiers when declaring variables and constants.
1

Understanding Variables and Constants

In programming, a variable is a named storage location that can hold data which may change during the execution of a program. For example, a variable named score might store a player's current points and update as the game progresses.

A constant is similar in that it is a named storage location, but its value is fixed once set and cannot be altered during program execution. For instance, a constant named MAX_PLAYERS might hold the value 4 to represent the maximum number of players allowed in a game.

  • Variables store data that can change.
  • Constants store data that remains fixed throughout the program.
2

Declaring Variables and Constants

Before using variables or constants, they must be declared. Declaration involves specifying a name (identifier) and often a data type that defines what kind of data the storage location can hold, such as integer, real number, or string.

For example, in pseudocode: `DECLARE age AS INTEGER` creates a variable named age that can hold whole numbers. To declare a constant, the syntax might be: `DECLARE CONSTANT PI AS REAL = 3.14159` which sets PI as a fixed real number value.

Proper declaration helps the program manage memory and prevents errors by ensuring data is used consistently.

  • Declaration includes naming and typing the storage location.
  • Constants are declared with a fixed initial value.
  • Variables can be declared without an initial value but must be assigned before use.
3

Using Variables and Constants in Programs

Variables are used when data needs to be stored and updated, such as counters, user inputs, or calculations. Constants are used for values that should not change, like configuration settings or fixed limits.

For example, a program calculating the area of a circle might use a constant for PI and a variable for the radius entered by the user:

`DECLARE CONSTANT PI AS REAL = 3.14159` `DECLARE radius AS REAL` `INPUT radius` `area = PI * radius * radius` `OUTPUT area`

  • Use variables for data that changes.
  • Use constants for fixed values to avoid accidental modification.
  • Using constants improves program readability and maintainability.
4

Choosing Meaningful Identifiers

Names given to variables and constants should be descriptive to make the program easier to understand and maintain. For example, `totalScore` is clearer than `ts` or `x`.

Good naming conventions help prevent confusion and errors, especially in larger programs or when working in teams.

  • Use clear, descriptive names for variables and constants.
  • Avoid single-letter or ambiguous names unless used in very limited contexts.
  • Follow consistent naming conventions throughout the program.
5

Common Practices and Tips

Always initialise variables before use to avoid unpredictable behaviour. Constants must be assigned a value at declaration since they cannot be changed later.

Be aware of the scope of variables and constants—where in the program they can be accessed. This affects how and where you declare them.

Use constants to represent values that might need to be changed in one place only, such as tax rates or maximum limits, making programs easier to update.

  • Initialise variables before use.
  • Assign constants at declaration.
  • Consider scope when declaring variables and constants.
  • Use constants to simplify program updates.

At-a-glance summary

Comparison table

AspectVariableConstantExample
MutabilityValue can change during program executionValue remains fixed after declarationVariable: `score` changes as player earns points; Constant: `MAX_LEVEL` set to 10
DeclarationDeclared with a name and type; may be assigned laterDeclared with a name, type, and assigned immediately`DECLARE age AS INTEGER` vs `DECLARE CONSTANT PI AS REAL = 3.14159`
PurposeStore data that varies, such as user input or countersStore fixed values that should not change, like configurationVariable: `temperature` changes; Constant: `FREEZING_POINT` = 0
Usage in CodeCan be assigned new values multiple timesCannot be assigned new values after initialisation`score = score + 1` valid; `PI = 3.14` invalid if PI is constant

Active recall

Quick check

1. What is the main difference between a variable and a constant?

A variable can have its value changed during program execution, while a constant's value remains fixed once set.

2. How do you declare a constant named MAX_SPEED with a value of 100?

Declare it by specifying it as a constant with a name, type, and assigned value, for example: `DECLARE CONSTANT MAX_SPEED AS INTEGER = 100`.

3. Why is it important to use meaningful names for variables and constants?

Meaningful names make the program easier to understand, maintain, and reduce errors by clearly indicating the purpose of each identifier.

4. Can a variable be used to store user input that changes during the program?

Yes, variables are designed to store data that can change, such as user input.

Complete revision guide 2 of 8

Fundamental Data Types in Programming

This note explains the essential data types used in programming: integer, real, char, string, and Boolean. It covers their characteristics, typical uses, and how understanding these types supports effective coding and data manipulation.

Syllabus source

Section 3, Topic 8.1, page 27, objective 8.1.2

Open source document ↗

What you should be able to do

  • ✓Understand the characteristics of fundamental data types.
  • ✓Identify appropriate data types for different programming scenarios.
  • ✓Apply knowledge of data types to declare variables correctly.
  • ✓Distinguish between similar data types such as char and string.
  • ✓Recognize the role of Boolean values in control flow and logic.
1

Introduction to Data Types

In programming, data types define the kind of data a variable can store. Choosing the correct data type is crucial because it affects how data is stored, processed, and interpreted by the computer. The fundamental data types form the building blocks for all programming tasks and include integer, real, char, string, and Boolean.

  • Data types specify the nature and size of data.
  • Correct data type selection ensures efficient memory use and accurate operations.
  • Fundamental data types are universal across programming languages.
2

Integer Data Type

An integer represents whole numbers without any fractional or decimal part. Integers can be positive, negative, or zero. They are commonly used for counting, indexing, and performing arithmetic operations where decimals are not needed.

For example, the number of students in a class (25) or the number of pages in a book (300) are integers.

When declaring an integer variable, it can only hold whole numbers; attempting to assign a decimal value will cause an error or truncation depending on the language.

  • Stores whole numbers only, e.g., -3, 0, 42.
  • Used for counting and discrete quantities.
  • Operations include addition, subtraction, multiplication, and division (result may be truncated).
3

Real (Floating-Point) Data Type

The real data type represents numbers that can have fractional parts, including decimals. These are also called floating-point numbers because the decimal point can 'float' to any position within the number.

Real numbers are essential when precision is required, such as measurements, financial calculations, or scientific data.

For example, 3.14 (approximate value of pi) or -0.001 are real numbers.

  • Stores numbers with decimals, e.g., 2.5, -0.75.
  • Used for measurements, averages, and precise calculations.
  • Operations include arithmetic with decimal results.
4

Char (Character) Data Type

A char data type holds a single character, which can be a letter, digit, symbol, or whitespace. It is typically stored as a numeric code internally (such as ASCII or Unicode).

For example, 'A', '7', or '?' are valid char values.

Char is different from string because it can only store one character at a time.

  • Stores exactly one character.
  • Represents letters, digits, punctuation, or control characters.
  • Useful for processing individual characters in text.
5

String Data Type

A string is a sequence of characters grouped together to form text. Strings can include letters, digits, spaces, and symbols.

Examples include names like "Alice", sentences like "Hello, world!", or numeric strings like "12345".

Strings are used for storing and manipulating text data such as user input, messages, or file contents.

  • Stores sequences of characters, e.g., "Hello".
  • Used for text processing and display.
  • Operations include concatenation, slicing, and searching.
6

Boolean Data Type

Boolean data types represent logical values and can only be one of two states: true or false.

Booleans are fundamental in decision-making, controlling program flow with conditions and loops.

For example, a Boolean variable might indicate whether a user is logged in (true) or not (false).

  • Stores true or false values only.
  • Used in conditional statements and logic operations.
  • Enables control flow such as if-else and loops.

At-a-glance summary

Comparison table

Data TypeDescriptionExample ValueCommon Use
IntegerWhole numbers without decimals42Counting items, indexing arrays
RealNumbers with decimal points3.14Measurements, precise calculations
CharSingle character'A'Storing individual letters or symbols
StringSequence of characters"Hello"Text data, user input
BooleanTrue or false valuetrueDecision making, control flow

Active recall

Quick check

1. What data type would you use to store the number of students in a class?

Integer, because the number of students is a whole number without decimals.

2. Which data type can hold the value '3.1415'?

Real, because it includes decimal points.

3. How is a char different from a string?

A char holds a single character, while a string holds a sequence of characters.

4. What values can a Boolean variable hold?

Only true or false.

5. Why should you not use an integer to store 2.5?

Because integers cannot store decimal values; using an integer would truncate or cause an error.

Complete revision guide 3 of 8

Input and Output Operations in Programming

This note explains how programs receive data from users or external sources (input) and how they present data to users or other systems (output). It covers common methods, implementation techniques, and practical examples to develop effective interactive programs.

Syllabus source

Section 3, Topic 8.1, page 27, objective 8.1.3

Open source document ↗

What you should be able to do

  • ✓Understand the purpose and types of input operations in programming.
  • ✓Understand the purpose and types of output operations in programming.
  • ✓Be able to implement basic input and output statements in pseudocode or programming languages.
  • ✓Recognise common input and output devices and methods.
  • ✓Apply input and output operations to create interactive programs.
1

Introduction to Input and Output in Programming

Programs need to interact with users or other systems to be useful. This interaction happens through input and output operations. Input operations allow a program to receive data, such as numbers or text, from a user or an external source. Output operations allow the program to display or send results, messages, or data to the user or another system.

Without input and output, a program would simply run without any interaction, limiting its usefulness. For example, a calculator program needs input numbers and must output the result of calculations.

  • Input: Receiving data from users or external sources.
  • Output: Sending or displaying data to users or other systems.
2

Common Input Methods and Implementation

The most common input method is through the keyboard, where users type data that the program reads. Another input method is reading data from files stored on a disk. In some cases, input can come from sensors or other devices, but these are beyond this scope.

In programming, input is often implemented using specific commands or functions. For example, in pseudocode, the statement 'INPUT age' prompts the user to enter a value that is stored in the variable 'age'. In Python, the equivalent is 'age = input()'.

Input data must often be converted to the correct type. For example, input from the keyboard is usually read as text (string) and may need conversion to an integer or real number before calculations.

  • Keyboard input is the most common method.
  • File input allows reading stored data.
  • Input commands store user data in variables.
  • Data type conversion may be necessary after input.
3

Common Output Methods and Implementation

Output usually involves displaying information on the screen, such as results, messages, or prompts. Another output method is writing data to files for storage or further processing.

In pseudocode, output is often done with the 'OUTPUT' or 'PRINT' statement, for example, 'OUTPUT "Result is", total'. In Python, 'print("Result is", total)' displays the message and value.

Output can be formatted to improve readability, such as including labels, line breaks, or formatting numbers to a certain decimal place.

  • Screen display is the primary output method.
  • File output saves data externally.
  • Output commands display or send data.
  • Formatting output improves clarity.
4

Example: Simple Input and Output Program

Consider a program that asks the user for two numbers, adds them, and displays the result.

Pseudocode example: INPUT number1 INPUT number2 SET sum TO number1 + number2 OUTPUT "The sum is", sum

This program uses input statements to get two numbers, stores them in variables, calculates their sum, and outputs the result with a descriptive message.

  • Input two numbers from the user.
  • Calculate the sum of the numbers.
  • Output the sum with a message.
5

Best Practices and Common Considerations

When implementing input and output, it is important to validate input data to ensure it is sensible and prevent errors. For example, if a program expects a number, it should check that the input is numeric.

Clear prompts and messages improve user experience. For example, 'Enter your age:' is clearer than just 'Input:'.

Programs should handle unexpected input gracefully, such as prompting again or showing an error message rather than crashing.

  • Validate input data to avoid errors.
  • Use clear prompts and messages.
  • Handle invalid input gracefully.

At-a-glance summary

Comparison table

StepDetailExampleExam Use
Input operationReceiving data from user or fileINPUT nameDescribe how input stores user data in variables
Output operationDisplaying or sending dataOUTPUT "Hello, " + nameExplain how output shows results or messages
Input methodKeyboard or file inputKeyboard input via INPUT statementIdentify input devices and methods
Output methodScreen display or file outputPrint result on screenDemonstrate output commands in pseudocode

Active recall

Quick check

1. What is the purpose of an input operation in a program?

To receive data from the user or an external source and store it for processing.

2. Give an example of an output operation.

Displaying a message or result on the screen using an OUTPUT or PRINT statement.

3. Why might input data need to be converted after being received?

Because input is often read as text and may need conversion to a number or other data type for calculations.

4. Name two common input methods.

Keyboard input and file input.

5. How can output be made clearer to the user?

By formatting output with labels, messages, and appropriate spacing or line breaks.

Complete revision guide 4 of 8

Understanding and Applying Key Programming Concepts: Sequence, Selection, Iteration, Totalling, Counting, and String Handling

This note explains fundamental programming concepts essential for algorithm development and problem-solving in IGCSE Computer Science. It covers the logical flow of instructions (sequence), decision-making (selection), repetition of actions (iteration), accumulating totals (totalling), tracking occurrences (counting), and manipulating text data (string handling). Each concept is illustrated with clear examples and practical insights to support exam success.

Syllabus source

Section 3, Topic 8.1, page 27, objective 8.1.4

Open source document ↗

What you should be able to do

  • ✓Understand the role of sequence in controlling program flow.
  • ✓Explain how selection enables decision-making based on conditions.
  • ✓Describe iteration as a method for repeating instructions.
  • ✓Apply totalling to accumulate sums within programs.
  • ✓Use counting to track occurrences or events during execution cycles or loops.“Understand basic string handling operations such as concatenation and length measurement.
1

Sequence: The Backbone of Program Flow

Sequence refers to the order in which instructions are executed in a program. Each statement runs one after another unless the flow is changed by selection or iteration.

Maintaining correct sequence is vital because computers follow instructions literally and sequentially. For example, if you input a number and then print it, reversing these steps would cause an error or unexpected output.

Example: To calculate the area of a rectangle, first input length and width, then multiply, then output the result. Changing this order breaks the logic.

  • Sequence ensures predictable and logical execution.
  • Errors often arise from incorrect ordering of statements.
  • Every program starts with sequence before selection or iteration modifies flow.
2

Selection: Making Decisions in Code

Selection allows a program to choose between different actions based on conditions. It uses Boolean expressions to decide which path to follow.

Common selection structures include IF, IF-ELSE, and CASE statements.

Example: If a student's mark is 50 or above, print 'Pass'; otherwise, print 'Fail'. This decision-making controls program behaviour dynamically.

  • Selection introduces branching in programs.
  • Conditions must be carefully constructed to avoid logic errors.
  • Nested selections allow multiple layers of decision-making.
3

Iteration: Repeating Actions Efficiently

Iteration repeats a block of instructions while a condition remains true or for a set number of times.

Loops such as FOR, WHILE, and REPEAT-UNTIL implement iteration.

Example: To print numbers 1 to 5, a FOR loop runs from 1 to 5, printing each number in turn, avoiding code duplication.

  • Iteration reduces code repetition and increases efficiency.
  • Loop conditions must be correctly defined to prevent infinite loops.
  • Loops can be nested for complex repetition patterns.
4

Totalling and Counting: Accumulating and Tracking

Totalling involves adding values together, often within loops, to compute sums such as totals or averages.

Counting tracks how many times an event occurs, such as counting valid inputs or occurrences of a character.

Example totalling: Summing exam scores entered by a user to find the total marks obtained. Example counting: Counting how many times the letter 'a' appears in a string.

  • Totalling uses an accumulator variable updated each iteration.
  • Counting uses a counter variable incremented when conditions are met.
  • Both require initialisation before loops and careful updates inside loops.
5

String Handling: Managing Text Data

Strings are sequences of characters used to represent text. Handling strings involves operations like concatenation (joining), measuring length, extracting substrings, and searching.

Example: Concatenating first name and last name to form a full name, or counting vowels in a word.

String handling is essential for user input processing, formatting output, and data validation.

  • Strings are manipulated differently from numbers.
  • Common operations include concatenation, length measurement, and character access.
  • Understanding string functions helps solve text-based problems efficiently.

At-a-glance summary

Comparison table

ConceptPurposeExampleExam Use
SequenceControls exact order of executionInput number → Calculate square → Output resultExplain why order matters in program flow
SelectionChooses between actions based on conditionIf temperature > 30 then print 'Hot' else print 'Cool'Outline how decisions affect program paths
IterationRepeats instructions until condition metFor i = 1 to 5 print iExplain loop function and termination
TotallingAdds values cumulativelySum = Sum + score inside a loopDescribe how totals are calculated in loops
CountingTracks occurrences or eventsCount vowels in a string by incrementing counterExplain counting logic in algorithms
String HandlingManipulates text dataConcatenate 'Hello' + ' World' = 'Hello World'Outline basic string operations

Active recall

Quick check

1. What is the difference between sequence and iteration?

Sequence is executing instructions one after another in order; iteration repeats instructions multiple times based on a condition.

2. How does selection affect program flow?

Selection allows the program to choose different paths or actions depending on whether a condition is true or false.

3. Why must accumulator variables be initialised before a loop?

Because they store running totals or counts, initialising ensures correct starting values and accurate results.

4. Give an example of string handling in a program.

Concatenating a user's first and last name to display the full name.

Complete revision guide 5 of 8

Understanding and Implementing Nested Statements in Programming

Nested statements involve placing one control structure inside another, enabling complex decision-making and repeated actions within programs. Mastery of nested selection and iteration is essential for writing effective algorithms that respond to multiple conditions and perform layered repetitions.

Syllabus source

Section 3, Topic 8.1, page 28, objective 8.1.5

Open source document ↗

What you should be able to do

  • ✓Explain the concept of nested statements in programming.
  • ✓Implement nested selection statements to evaluate multiple conditions.
  • ✓Implement nested iteration statements to perform repeated actions within loops.
  • ✓Recognise the importance of proper indentation and structure in nested code for readability and correctness.
1

What Are Nested Statements?

In programming, a nested statement occurs when one control structure is placed inside another. This can be a selection statement (like an if statement) inside another selection, or a loop inside another loop. Nesting allows programs to handle complex logic by combining multiple conditions or repeated actions.

For example, an if statement inside another if statement lets a program check a condition only if a previous condition is true, enabling multi-level decision-making.

  • Nested statements increase the complexity and capability of programs.
  • They are commonly used in decision-making and repetition.
  • Proper nesting requires careful attention to syntax and logic.
2

Nested Selection Statements

Nested selection means placing one selection statement inside another. This allows checking multiple conditions in a structured way.

For instance, consider a program that checks a student's grade and then checks attendance:

If the grade is above 70, then check if attendance is above 80%. If both are true, print 'Pass with good attendance'. Otherwise, print 'Pass but poor attendance'. If the grade is 70 or below, print 'Fail'.

  • Nested if statements enable multi-level condition checks.
  • They help handle complex decision trees.
  • Each inner condition is only evaluated if the outer condition is true.
3

Nested Iteration Statements

Nested iteration involves placing one loop inside another. This is useful when dealing with multi-dimensional data or repeated processes within repeated processes.

For example, to print a 3x3 grid of stars, an outer loop can iterate over rows, and an inner loop can iterate over columns, printing a star each time.

Example pseudocode: For each row from 1 to 3: For each column from 1 to 3: print '*' without newline; after inner loop ends, print newline.

  • Nested loops allow handling of multi-level repetition.
  • They are essential for working with arrays, matrices, or grids.
  • Care must be taken to avoid infinite loops by ensuring correct loop bounds.
4

Importance of Indentation and Structure

When nesting statements, proper indentation is crucial for readability and to avoid logical errors. Indentation visually separates blocks of code, showing which statements belong inside others.

Most programming languages require consistent indentation or use braces to define blocks. Poor indentation can lead to confusion and bugs, especially in nested code where multiple levels exist.

Example: In Python, indentation defines blocks, so nested statements must be indented further than their parent statements.

  • Indentation improves code clarity and maintainability.
  • It helps identify the start and end of nested blocks.
  • Consistent style reduces errors and aids debugging.
5

Practical Tips for Implementing Nested Statements

Start by clearly understanding the logic you want to implement. Break down complex conditions into smaller parts.

Use comments to explain each nested block's purpose.

Test nested statements carefully, as errors can be harder to spot than in simple statements. Use trace tables or print statements to follow the flow of execution during debugging.

  • Plan nested logic before coding.
  • Comment nested blocks for clarity.
  • Test thoroughly to ensure correct behaviour.

At-a-glance summary

Comparison table

StepDetailExampleExam Use
Nested SelectionEvaluate multiple conditions inside if statementsIf score > 50 then if attendance > 75% then print 'Pass'Show understanding of multi-level conditions
Nested IterationLoops inside loops to repeat actions multiple timesFor each row 1 to 3, for each column 1 to 3, print '*'Demonstrate ability to handle multi-dimensional repetition
IndentationUse indentation to show nested blocksIndent inner if or loop further than outerMarks awarded for clear, readable code structure
TestingCheck nested logic with sample inputsUse trace tables to follow variable changesExplain testing approach to validate nested code

Active recall

Quick check

1. What is a nested selection statement?

A selection statement placed inside another selection statement, allowing multiple conditions to be checked in sequence.

2. Why are nested loops useful?

They allow repeated actions to be performed within other repeated actions, useful for multi-dimensional data or complex repetition.

3. How does proper indentation help with nested statements?

It visually separates code blocks, making the structure and flow of nested statements clear and reducing errors.

4. Give a simple example of nested iteration.

A loop that prints rows, with an inner loop that prints columns, such as printing a 3x3 grid of stars.

Complete revision guide 6 of 8

Understanding Procedures, Functions, Parameters, and Variable Scope

This note explains the concepts of procedures and functions, how parameters enable data passing, and the distinction between local and global variables in programming. It includes practical examples and clarifies their roles in structuring code effectively.

Syllabus source

Section 3, Topic 8.1, page 28, objective 8.1.6

Open source document ↗

What you should be able to do

  • ✓Define procedures and functions and understand their differences.
  • ✓Explain the purpose and use of parameters in procedures and functions.
  • ✓Distinguish between local and global variables and understand their scope and lifetime.
  • ✓Apply procedures and functions with parameters and variables in programming examples.
1

Procedures and Functions: Building Blocks of Structured Code

Procedures and functions are reusable blocks of code designed to perform specific tasks within a program. Using them helps avoid repetition and makes programs easier to read and maintain.

A procedure is a set of instructions executed when called but does not return a value to the calling code. For example, a procedure might display a message or update a variable.

A function is similar but always returns a value after execution. For instance, a function could calculate the area of a rectangle and return the result for further use.

  • Procedures perform tasks without returning values.
  • Functions perform tasks and return a value to the caller.
2

Parameters: Passing Information into Procedures and Functions

Parameters are variables listed in the procedure or function definition that receive values when the procedure or function is called. They allow the same procedure or function to operate on different data each time it is used.

For example, a function to calculate the area of a rectangle might have two parameters: length and width. When called, specific values are passed in, and the function returns the calculated area.

Parameters enable modular and flexible code by avoiding hard-coded values inside procedures or functions.

  • Parameters act as inputs to procedures/functions.
  • They allow dynamic data to be processed within reusable code blocks.
3

Local Variables: Temporary and Scoped to Procedures or Functions

Local variables are declared inside a procedure or function and exist only during its execution. They cannot be accessed outside that procedure or function.

This limits their scope and prevents unintended interference with other parts of the program. For example, a variable used to store a temporary calculation inside a function is local to that function.

Once the procedure or function finishes, local variables are destroyed and their memory freed.

  • Local variables exist only within their procedure/function.
  • They help avoid conflicts by limiting variable scope.
4

Global Variables: Accessible Throughout the Program

Global variables are declared outside any procedure or function, usually at the start of a program. They can be accessed and modified by any part of the program, including all procedures and functions.

While useful for sharing data, overusing global variables can make programs harder to debug and maintain because changes in one place affect others.

For example, a global variable might store a program-wide setting or counter that multiple procedures update.

  • Global variables are accessible everywhere in the program.
  • They persist for the program’s entire runtime.
5

Example: Using a Function with Parameters and Variable Scope

Consider a function that calculates the area of a rectangle:

It takes two parameters: length and width (both local to the function).

Inside the function, a local variable area stores the product of length and width. This variable is not accessible outside the function. The function returns area to the caller.

  • Function definition: function area(length, width)
  • Local variable: area = length × width
  • Return value: area
  • Caller can use the returned value without accessing local variables directly.

At-a-glance summary

Comparison table

AspectProcedureFunctionExample
Return valueDoes not return a valueReturns a valueProcedure to display a message; function to calculate sum
PurposePerform tasks or actionsPerform tasks and produce a resultProcedure to update a score; function to compute area
ParametersCan have parameters to receive inputsCan have parameters to receive inputsBoth can take length and width as inputs
Variable scopeLocal variables exist within procedureLocal variables exist within functionTemporary variables inside procedure/function only accessible there

Active recall

Quick check

1. What is the main difference between a procedure and a function?

A procedure performs a task but does not return a value, while a function performs a task and returns a value to the caller.

2. Why are parameters used in procedures and functions?

Parameters allow data to be passed into procedures and functions so they can operate on different inputs each time they are called.

3. Where can local variables be accessed in a program?

Local variables can only be accessed within the procedure or function where they are declared.

4. What is a global variable and how does its scope differ from a local variable?

A global variable is declared outside all procedures/functions and can be accessed anywhere in the program, unlike a local variable which is limited to its own procedure/function.

Complete revision guide 7 of 8

Using Library Routines: MOD, DIV, ROUND, and RANDOM

This note explains key library routines commonly used in programming to perform mathematical operations efficiently. It covers the MOD and DIV operations for division-related calculations, the ROUND function for approximating numbers, and the RANDOM function for generating random values within a specified range. Understanding these routines helps write clearer, shorter, and more reliable code.

Syllabus source

Section 3, Topic 8.1, page 28, objective 8.1.7

Open source document ↗

What you should be able to do

  • ✓Explain the purpose and use of the MOD routine to find remainders.
  • ✓Describe how DIV returns the integer quotient of division.
  • ✓Use ROUND to approximate real numbers to the nearest integer.
  • ✓Generate random numbers within a specified range using RANDOM.
  • ✓Apply these routines correctly in programming examples.
1

Division-Related Library Routines: MOD and DIV

In programming, division can produce both a quotient and a remainder. The MOD routine returns the remainder after division, while DIV returns the integer quotient, discarding any fractional part.

For example, consider dividing 17 by 5: 17 DIV 5 equals 3 because 5 fits into 17 three whole times, and 17 MOD 5 equals 2 because 2 is left over after subtracting 3×5=15 from 17.

Using MOD is useful for tasks like determining if a number is even or odd (a number MOD 2 equals 0 means it is even). DIV is helpful when you need to know how many times one number fits completely into another without fractions.

  • MOD returns the remainder of integer division.
  • DIV returns the integer quotient, ignoring the remainder.
2

Rounding Numbers with ROUND

The ROUND routine approximates a real (decimal) number to the nearest whole number. If the fractional part is 0.5 or greater, ROUND increases the integer part by one; otherwise, it leaves it unchanged.

For example, ROUND(4.3) results in 4, while ROUND(4.7) results in 5. This is useful when you need to convert floating-point results to integers for indexing or display.

ROUND helps avoid errors from truncation and makes results easier to interpret when decimals are not needed.

  • ROUND approximates a real number to the nearest integer.
  • It rounds up if the decimal part is 0.5 or more, otherwise rounds down.
3

Generating Random Numbers with RANDOM

The RANDOM routine produces a pseudo-random number, often within a specified range. For example, RANDOM(1, 10) generates an integer between 1 and 10 inclusive.

Random numbers are essential in simulations, games, and testing programs where unpredictability is required.

Programmers must understand that RANDOM generates pseudo-random numbers based on algorithms, which appear random but are deterministic if the seed is known.

  • RANDOM generates a number within a given range.
  • Useful for simulations, games, and randomized testing.
4

Practical Examples of Using These Routines

Example 1: To check if a number N is divisible by 4, use: if N MOD 4 = 0 then it is divisible.

Example 2: To find how many full weeks are in D days, use: weeks = D DIV 7.

Example 3: To round a calculated average score avg to the nearest whole number: rounded_avg = ROUND(avg). If avg = 78.6, rounded_avg = 79; if avg = 78.3, rounded_avg = 78.

  • Use MOD to test divisibility or cycle through repeating patterns.
  • Use DIV to count whole units from totals.
  • Use ROUND to convert decimals to integers appropriately.
5

Common Usage Tips and Considerations

Always ensure that the arguments passed to these routines are of the correct data type (usually integers for MOD and DIV, real numbers for ROUND).

Be aware that DIV discards the fractional part without rounding, which differs from ROUND.

When using RANDOM, specify the range clearly and understand that repeated calls produce different values, but the sequence can be repeated if the seed is fixed.

  • Check data types before using routines.
  • Understand differences between truncation (DIV) and rounding (ROUND).
  • Use RANDOM carefully to avoid predictable patterns.

At-a-glance summary

Comparison table

RoutinePurposeExampleExam Use
MODReturns remainder after division17 MOD 5 = 2Check divisibility or cycle through values
DIVReturns integer quotient of division17 DIV 5 = 3Calculate whole units from totals
ROUNDRounds a real number to nearest integerROUND(4.7) = 5Convert decimals to integers accurately
RANDOMGenerates random number in rangeRANDOM(1,10) might return 7Create unpredictable values for simulations

Active recall

Quick check

1. What does 29 MOD 6 return and why?

29 MOD 6 returns 5 because 6 fits into 29 four times (6×4=24) with a remainder of 5.

2. Calculate 29 DIV 6 and explain the result.

29 DIV 6 equals 4 because it counts how many whole times 6 fits into 29, ignoring the remainder.

3. What is ROUND(3.5) and ROUND(3.4)?

ROUND(3.5) is 4 because decimals of 0.5 or more round up; ROUND(3.4) is 3 because decimals less than 0.5 round down.

4. How would you generate a random integer between 1 and 100?

Use RANDOM(1, 100) to generate a pseudo-random integer from 1 to 100 inclusive.

Complete revision guide 8 of 8

Developing Maintainable Programs Using Meaningful Identifiers, Comments, and Structured Procedures and Functions

Creating maintainable programs is essential for efficient software development and future-proofing code. This involves using clear and descriptive identifiers, adding informative comments, and structuring code with procedures and functions to improve readability, debugging, and modification.

Syllabus source

Section 3, Topic 8.1, page 29, objective 8.1.8

Open source document ↗

What you should be able to do

  • ✓Understand the importance of meaningful identifiers in programming.
  • ✓Learn how to write effective comments to clarify code purpose and logic.
  • ✓Recognize the role of procedures and functions in structuring programs.
  • ✓Apply these concepts to write maintainable and readable code.
1

Meaningful Identifiers

Identifiers are names given to variables, constants, procedures, and functions in a program. Using meaningful identifiers means choosing names that clearly describe the purpose or content of the item. For example, naming a variable 'totalScore' is more informative than 'x' or 'a'. This practice helps anyone reading the code to understand what each element represents without guessing.

Meaningful identifiers reduce confusion and errors during development and maintenance. They also make it easier to locate and update parts of the program when requirements change.

  • Choose descriptive names that reflect the role or data stored.
  • Avoid vague or single-letter names except for simple counters (e.g., i, j).
  • Use consistent naming conventions, such as camelCase or underscores, to improve readability.
2

Effective Commenting

Comments are notes written within the code that explain what the code does or why certain decisions were made. They do not affect program execution but are vital for human understanding.

Good comments clarify complex logic, describe the purpose of variables or functions, and outline the overall program flow. For example, before a loop that calculates the average score, a comment might say: 'Calculate the average score from all test results'.

Comments should be concise and relevant, avoiding obvious statements that restate the code. They are especially helpful when the logic is not immediately clear or when using non-trivial algorithms.

  • Use comments to explain the purpose of code blocks or complex statements.
  • Avoid redundant comments that simply repeat the code.
  • Update comments when code changes to keep them accurate.
3

Structured Procedures and Functions

Procedures and functions are blocks of code designed to perform specific tasks. Using them helps break down a program into manageable parts, making it easier to understand, test, and maintain.

A procedure performs actions but does not return a value, while a function returns a value after processing. For example, a function 'calculateArea' might take length and width as inputs and return the area of a rectangle.

Structuring code with procedures and functions avoids repetition, promotes code reuse, and isolates changes to specific parts without affecting the whole program.

  • Define procedures for tasks that perform actions without returning values.
  • Define functions for computations that return results.
  • Use parameters to pass data into procedures and functions, and return values where appropriate.
  • Keep procedures and functions focused on a single task for clarity.
4

Benefits of Maintainable Programs

Programs developed with meaningful identifiers, clear comments, and structured procedures/functions are easier to debug, update, and extend. This reduces development time and errors when modifying code.

Maintainable code also facilitates collaboration among programmers, as others can quickly understand the program's logic and structure.

For example, if a program calculates student grades, using descriptive variable names like 'studentName' and functions like 'calculateFinalGrade' makes it straightforward to add new grading criteria later.

  • Improves readability and understanding for current and future developers.
  • Simplifies debugging and testing processes.
  • Enables easier updates and feature additions.
  • Supports teamwork and code sharing.

At-a-glance summary

Comparison table

StepDetailExampleExam Use
Choosing IdentifiersSelect clear, descriptive namesUse 'totalMarks' instead of 'x'Explain why names aid understanding
Writing CommentsAdd notes explaining code logic// Calculate average score from test resultsDescribe purpose of comments
Using ProceduresCreate reusable code blocks without return valuesProcedure to display student detailsIdentify when to use procedures
Using FunctionsCreate code blocks that return valuesFunction to compute area of rectangleExplain function benefits

Active recall

Quick check

1. Why should variable names be meaningful?

Meaningful variable names make the code easier to understand and maintain by clearly indicating the data they hold.

2. What is the purpose of comments in a program?

Comments explain the purpose or logic of code sections to help readers understand and maintain the program.

3. How do procedures and functions improve program structure?

They divide code into manageable, reusable blocks that simplify debugging and updates.

4. What is the difference between a procedure and a function?

A procedure performs actions without returning a value, while a function returns a value after processing.

Related topics

Study nearby topics next

Revision hubs

Keep studying from the right hub