Programming

Programming is the heart of computer science. This section covers the fundamental concepts you need to write, understand, and debug code effectively. From basic data types to complex procedures, you'll master the building blocks of computational thinking required for your IGCSE exam.

Data Types & Variables

Every program needs to store and manipulate data. Understanding data types and how to declare variables and constants is the foundation of programming.

Data Types

Data types classify the kind of values a variable can hold. Choosing the correct data type is crucial for efficient memory usage and preventing errors. INTEGER: Whole numbers (e.g., 5, -10, 1000). CHAR: A single character (e.g., 'a', 'Z', '7', '$'). STRING: A sequence of characters (e.g., "Hello World", "IGCSE"). REAL: Numbers with decimal points (e.g., 3.14, -0.5, 99.99). BOOLEAN: Represents truth values, either TRUE or FALSE. Pseudocode DECLARE age : INTEGER DECLARE price : REAL DECLARE initial : CHAR DECLARE name : STRING DECLARE isAdmin : BOOLEAN Visual Basic Dim age As Integer Dim price As Single Dim initial As Char Dim name As String Dim isAdmin As Boolean

Variables

Variables are named storage locations in memory used to hold data that can change during the program's execution. They allow programs to be dynamic and respond to different inputs or states. Pseudocode DECLARE score : INTEGER score ← 0 score ← score + 10 OUTPUT score // Outputs 10 Visual Basic Dim score As Integer score = 0 score = score + 10 Console.WriteLine(score) ' Outputs 10

Constants

Constants are named storage locations whose values cannot be changed once they have been defined. They are used for values that remain fixed throughout the program, improving readability and maintainability. Pseudocode CONSTANT PI = 3.14159 CONSTANT MAX_USERS = 100 Visual Basic Const PI As Double = 3.14159 Const MAX_USERS As Integer = 100

Declaration Syntax

Declaring a variable or constant involves giving it a name and specifying its data type. This reserves the necessary memory space and helps the compiler or interpreter understand how to handle the stored value. Pseudocode // Variable Declaration DECLARE variableName : DataType // Constant Declaration CONSTANT CONSTANT_NAME = value Visual Basic ' Variable Declaration Dim variableName As DataType ' Constant Declaration Const CONSTANT_NAME As DataType = value

Input/Output Operations

Input operations allow programs to receive data from users or external sources, while output operations display results or information. These operations are fundamental for user interaction and conveying program status. Pseudocode DECLARE userName : STRING OUTPUT "Enter your name: " INPUT userName OUTPUT "Hello, " & userName Visual Basic Dim userName As String Console.Write("Enter your name: ") userName = Console.ReadLine() Console.WriteLine("Hello, " & userName)

Operators & Expressions

Operators allow you to perform calculations, make comparisons, and combine conditions. Mastering these is essential for writing effective algorithms.

Operators are fundamental building blocks in programming. Click on each section below to explore different types of operators with detailed examples.

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numerical values. Common Operators + → Addition - → Subtraction * → Multiplication / → Division (real number result) DIV → Integer division (drops decimals) MOD → Remainder after division Pseudocode result ← 5 + 3 result ← 10 - 4 result ← 6 * 2 result ← 20 / 4 result ← 17 DIV 5 // result = 3 result ← 17 MOD 5 // result = 2 Visual Basic result = 5 + 3 result = 10 - 4 result = 6 * 2 result = 20 / 4 result = 17 \ 5 'integer division result = 17 Mod 5 'remainder

Relational Operators

Relational operators compare two values. Operators > → greater than < → less than >= → greater than or equal to <= → less than or equal to = → equal to <> → not equal to Pseudocode isGreater ← (age > 18) isEqual ← (score = 100) isDifferent ← (name <> "Alice") Visual Basic isGreater = (age > 18) isEqual = (score = 100) isDifferent = (name <> "Alice")

Logical Operators

Logical operators join or modify Boolean expressions. Operators AND → both conditions must be TRUE OR → at least one condition is TRUE NOT → reverses TRUE/FALSE Pseudocode canVote ← (age >= 18) AND (isCitizen = TRUE) needsRetake ← (mark < 50) OR (attendance < 80) isNotAdmin ← NOT isAdmin Visual Basic canVote = (age >= 18) And (isCitizen = True) needsRetake = (mark < 50) Or (attendance < 80) isNotAdmin = Not isAdmin

Library Routines (from syllabus)

Only the routines used in the 0478 syllabus: ROUND(x) RANDOM (returns a random number) DIV and MOD already shown above Pseudocode value ← ROUND(3.67) // value = 4 number ← RANDOM // returns a random number Visual Basic value = Math.Round(3.67) number = Rnd() 'returns random value

Selection Structures

Programs need to make decisions. Selection structures allow your code to choose different paths based on conditions, making programs intelligent and responsive.

IF (Single Condition)

A single condition IF statement executes a block of code only if the specified condition is true. If the condition is false, the code block is skipped, and the program continues after the END IF. Pseudocode IF age > 18 THEN OUTPUT "Adult" END IF Visual Basic If age > 18 Then Console.WriteLine("Adult") End If

IF / ELSE (Two-Way Selection)

IF / ELSE statements provide two possible paths of execution. If the condition is true, one block of code is executed; otherwise, the code in the ELSE block is executed. Pseudocode IF score >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" END IF Visual Basic If score >= 50 Then Console.WriteLine("Pass") Else Console.WriteLine("Fail") End If

IF / ELSE IF / ELSE (Multi-Way Selection)

For scenarios requiring more than two outcomes, IF / ELSE IF / ELSE structures allow for multiple conditions to be checked sequentially, leading to different execution paths. Pseudocode IF mark >= 75 THEN OUTPUT "Distinction" ELSE IF mark >= 60 THEN OUTPUT "Merit" ELSE OUTPUT "Pass" END IF Visual Basic If mark >= 75 Then Console.WriteLine("Distinction") ElseIf mark >= 60 Then Console.WriteLine("Merit") Else Console.WriteLine("Pass") End If

CASE Statements

CASE statements, also known as SELECT CASE or SWITCH, provide a structured way to handle multiple possible outcomes based on the value of a single variable or expression, offering a cleaner alternative to complex IF / ELSE IF chains. Pseudocode CASE OF day WHEN "Mon": OUTPUT "Start of week" WHEN "Fri": OUTPUT "End of week" OTHERWISE: OUTPUT "Mid-week" END CASE Visual Basic Select Case day Case "Mon" Console.WriteLine("Start of week") Case "Fri" Console.WriteLine("End of week") Case Else Console.WriteLine("Mid-week") End Select

Boolean Conditions

Boolean conditions are expressions that evaluate to either TRUE or FALSE. They are essential for controlling the flow of selection structures, allowing programs to make decisions based on logical evaluations. Pseudocode isRaining ← TRUE isCold ← FALSE IF isRaining AND isCold THEN OUTPUT "Stay inside" ELSE IF isRaining OR isCold THEN OUTPUT "Wear a jacket" ELSE OUTPUT "Enjoy outside" END IF Visual Basic Dim isRaining As Boolean = True Dim isCold As Boolean = False If isRaining And isCold Then Console.WriteLine("Stay inside") ElseIf isRaining Or isCold Then Console.WriteLine("Wear a jacket") Else Console.WriteLine("Enjoy outside") End If

Iteration Structures (Loops)

Loops allow code to repeat, making programs efficient and powerful. Understanding when to use each type of loop is crucial for algorithm design.

FOR Loops (Count-Controlled)

Repeats a fixed number of times. Can also use STEP for custom increments (e.g., FOR i ← 1 TO 10 STEP 2)

WHILE Loops (Pre-Condition)

Checks condition BEFORE executing. May not execute at all. Use when you don't know how many iterations needed.

REPEAT...UNTIL Loops (Post-Condition)

Checks condition AFTER executing. Always runs at least once. Useful for input validation.

Nested Loops

Loops inside loops. Common for 2D arrays. Inner loop completes fully for each iteration of outer loop.

Infinite Loops

Occur when loop condition never becomes false. Always ensure your loop will eventually terminate!

Choosing the Right Loop

Known iterations? Use FOR Unknown iterations, may not run? Use WHILE Unknown iterations, must run once? Use REPEAT...UNTIL

Pseudocode
// FOR Loop Example
FOR i ← 1 TO 5
    OUTPUT "Hello, iteration " & i
NEXT i

// WHILE Loop Example
DECLARE count : INTEGER
count ← 1
WHILE count <= 3
    OUTPUT "Counting: " & count
    count ← count + 1
END WHILE

// REPEAT...UNTIL Loop Example
DECLARE userInput : INTEGER
REPEAT
    OUTPUT "Enter a number greater than 0: "
    INPUT userInput
UNTIL userInput > 0
OUTPUT "Valid number entered: " & userInput
VB Code
' FOR Loop Example
For i As Integer = 1 To 5
    Console.WriteLine("Hello, iteration " & i.ToString())
Next

' WHILE Loop Example
Dim count As Integer = 1
While count <= 3
    Console.WriteLine("Counting: " & count.ToString())
    count += 1
End While

' DO WHILE Loop Example (pre-condition)
Dim num As Integer = 1
Do While num <= 3
    Console.WriteLine("Counting (Do While): " & num.ToString())
    num += 1
Loop

' DO...LOOP UNTIL Example (post-condition)
Dim userInput As Integer
Do
    Console.Write("Enter a number greater than 0: ")
    userInput = CInt(Console.ReadLine())
Loop Until userInput > 0
Console.WriteLine("Valid number entered: " & userInput.ToString())

Arrays

Arrays are fixed-length structures that store multiple values of the same data type. They're essential for handling collections of related data efficiently.

1D Arrays

Linear collection of same data type, accessed by single index Index typically starts at 0 or 1 Example: scores[1], scores[5]

2D Arrays

Grid structure with rows and columns, accessed by two indices Perfect for tables, game boards, matrices Example: grid[2,3]

Array Declaration

Must declare size before use Syntax: DECLARE arrayName : ARRAY[lower:upper] OF datatype Example: DECLARE scores : ARRAY[1:10] OF INTEGER

Array Operations

Access elements using index in square brackets Use loops to process all elements Can store in variables: value ← scores[3]

Using Arrays with Loops

FOR loops are ideal for processing arrays Can iterate through all elements Useful for totalling, counting, searching

Pseudocode


VB Code


String Handling

String operations allow you to manipulate text data. Understanding these operations is essential for processing user input and formatting output.

LENGTH Function

Returns the number of characters in a string Syntax: LENGTH(string) Example: LENGTH("Hello") returns 5

SUBSTRING Function

Extracts a portion of a string Syntax: SUBSTRING(string, start, length) Example: SUBSTRING("Hello", 1, 3) returns "Hel"

UCASE Function

Converts all characters to uppercase Syntax: UCASE(string) Example: UCASE("hello") returns "HELLO"

LCASE Function

Converts all characters to lowercase Syntax: LCASE(string) Example: LCASE("HELLO") returns "hello"

String Indexing

First character can be position 0 or 1 (check your exam board) Position matters for SUBSTRING operations Cambridge IGCSE typically uses 1 as first position

Exam Tips

String operations return NEW values, don't modify original Remember to check if indexing starts at 0 or 1 Can combine string operations together

Pseudocode


VB Code


Procedures & Functions

Breaking code into reusable blocks makes programs easier to write, test, and maintain. Understanding scope and parameters is key to modular programming.

There was an error generating this image

Procedures

Named blocks of code that perform a task. Don't return a value:

Called using: CALL printMessage()

Functions

Named blocks that perform a task AND return a value:

Called in expressions: result ← square(5)

Parameters

Values passed into procedures/functions. Can have up to 2 parameters in IGCSE:

Local Variables

Declared inside a procedure/function. Only accessible within that block. Destroyed when block ends.

Global Variables

Declared outside all procedures/functions. Accessible throughout entire program. Use sparingly!

Benefits of Modular Code

  • Reusability: Write once, use many times
  • Testing: Test each module independently
  • Readability: Clear structure and purpose
  • Maintenance: Fix bugs in one place
Pseudocode
// Procedure with parameters and a function that returns a value

PROCEDURE Greet(name : STRING, age : INTEGER)
    OUTPUT "Hello ", name, ", you are ", age, " years old."
ENDPROCEDURE

FUNCTION Square(x : INTEGER) RETURNS INTEGER
    RETURN x * x
ENDFUNCTION

// Main program
DECLARE username : STRING
DECLARE userAge  : INTEGER
DECLARE result   : INTEGER

INPUT username
INPUT userAge

CALL Greet(username, userAge)

result ← Square(5)
OUTPUT "5 squared is ", result
VB Code
' Procedure with parameters and a function that returns a value

Module Program
    Sub Main()
        Dim username As String
        Dim userAge As Integer
        Dim result As Integer
        
        Console.Write("Enter your name: ")
        username = Console.ReadLine()
        
        Console.Write("Enter your age: ")
        userAge = CInt(Console.ReadLine())
        
        Greet(username, userAge)
        
        result = Square(5)
        Console.WriteLine("5 squared is {0}", result)
    End Sub
    
    Sub Greet(name As String, age As Integer)
        Console.WriteLine("Hello {0}, you are {1} years old.", name, age)
    Zend Sub
    
    Function Square(x As Integer) As Integer
        Return x * x
    End Function
End Module

File Handling & Pseudocode

Efficiently managing files and writing clear algorithms are fundamental skills in computer science. This section outlines key file operations and the pseudocode conventions you'll use in exams.

File Operations & Modes

  • OPENFILE: Opens a file for reading or writing.
  • READFILE: Reads data from an open file.
  • WRITEFILE: Writes data to an open file.
  • CLOSEFILE: Closes an open file, saving changes.

File Modes:

  • READ: Opens a file to read its contents.
  • WRITE: Opens a file to write to it (overwriting existing content or creating a new file).

Pseudocode Conventions

Pseudocode is used to describe algorithms in a structured, language-agnostic way, focusing on logic rather than specific syntax. In exams, adhere to the conventions provided in your syllabus to ensure clarity and consistency.

Key Pseudocode Commands

  • DECLARE: Declares a variable and its data type.
  • INPUT: Obtains input from the user.
  • OUTPUT: Displays output to the user.
  • IF...THEN...ELSE...ENDIF: Conditional execution.
  • FOR...NEXT: Loops a fixed number of times.
  • WHILE...DO...ENDWHILE: Loops as long as a condition is true, condition checked at start.
  • REPEAT...UNTIL: Loops until a condition is true, condition checked at end.
  • CASE OF...ENDCASE: Multi-way selection based on a variable's value.

Important Exam Note (Paper 2)

In Paper 2, you are generally expected to write solutions in pseudocode. The only exception is the 15-mark scenario question, for which you may use Python, Visual Basic, or Java to demonstrate your programming skills.

Pseudocode
// Read all names from a file and display them

DECLARE fileName : STRING
DECLARE name : STRING

fileName ← "students.txt"

OPENFILE fileName FOR READ

WHILE NOT EOF(fileName) DO
    READFILE fileName, name
    OUTPUT name
ENDWHILE

CLOSEFILE fileName
VB Code
' Read all names from a file and display them

Imports System.IO

Module Program
    Sub Main()
        Dim fileName As String = "students.txt"
        Dim line As String
        
        If File.Exists(fileName) Then
            Dim reader As New StreamReader(fileName)
            
            line = reader.ReadLine()
            While line IsNot Nothing
                Console.WriteLine(line)
                line = reader.ReadLine()
            End While
            
            reader.Close()
        Else
            Console.WriteLine("File not found.")
        End If
    End Sub
End Module

Powered by Bytonix — Digital Learning for Computer Science