Understand and use input and output

Programming – Input and Output (IGCSE 0478)

Learning Objectives

  • Explain why input and output (I/O) are essential in a program.
  • Identify the hardware and software sources and destinations of I/O.
  • Describe basic data‑transmission concepts and simple error‑detection techniques.
  • Write correct I/O statements in pseudocode, Python and Java.
  • Use file handling (and, where required, simple network I/O) safely.
  • Apply selection, iteration and arrays when processing multiple inputs.
  • Design, trace and debug I/O‑heavy programs, including validation and error handling.

1. What Is Input and Output?

Input – any data a program receives from the outside world.
Output – any data a program sends out to the user or another system.

1.1 Typical I/O Sources & Destinations

Device / Channel Direction Typical Use in Programs
KeyboardInputEnter numbers, text, menu choices
Mouse / TouchscreenInputSelect items, click buttons, draw
Screen (monitor)OutputDisplay results, prompts, graphics
PrinterOutputHard‑copy reports, receipts
File (disk, SSD)BothRead data, write results, store records
Network (NIC, Internet)BothDownload data, send API requests, chat
Sensor (temperature, light, etc.)InputCollect real‑world measurements
Actuator (motor, speaker)OutputControl hardware, produce sound

2. Where Does I/O Live?

  • Hardware layer – physical devices (keyboard, mouse, display, printer, network card, sensors, actuators).
  • Operating System (OS) – provides drivers that translate generic I/O requests into hardware actions and manages files, buffers and security.
  • IDE / Runtime environment – supplies the console window, standard input/output streams, and debugging tools.
  • Language libraries – functions such as input(), print() (Python) or Scanner, System.out (Java) are wrappers around OS services.

3. Hardware I/O Devices (Syllabus 3.1‑3.4)

The Cambridge syllabus expects you to recognise the following categories:

  • Input devices: keyboard, mouse, touchpad, scanner, digital camera, microphone, sensors (temperature, pressure, motion).
  • Output devices: monitor, printer, speaker, LED display, actuator (robotic arm, motor).
  • Combined I/O: touch screen, network interface card (NIC), USB ports.
  • Data‑storage devices: magnetic hard‑disk, solid‑state drive, optical disc, flash drive.

4. Data Transmission & Simple Network Basics (Syllabus 2.2‑2.3)

4.1 Basic Concepts

  • Packet – a unit of data sent over a network; contains a header (source/destination address, length) and a payload (the actual data).
  • MAC address – hardware address of a NIC; used on the local network segment.
  • IP address – logical address that identifies a device on an IP network.
  • Switching – routers/switches forward packets based on MAC/IP information.
  • USB – serial bus that carries power and data between a computer and peripheral devices.

4.2 Simple Pseudocode for Network I/O (conceptual only)

OPEN url "http://example.com/data" FOR INPUT
READ line FROM url
CLOSE url
WRITE "Data received: ", line

4.3 Error‑Detection & Encryption (Syllabus 2.2‑2.3)

  • Parity bit – adds a single bit to a byte to make the number of 1‑bits even (even parity) or odd (odd parity). Detects single‑bit errors.
  • Checksum – sum of all data bytes (often modulo 256); transmitted with the data and recomputed on receipt.
  • Simple encryption example – Caesar cipher (shift each character by a fixed number). Illustrates symmetric encryption.

5. I/O in Pseudocode

5.1 Keyboard I/O

READ variable          // read a value from the user
WRITE expression       // display a value or message

5.2 File Handling (required for syllabus 3.3)

OPEN fileName FOR INPUT      // open an existing file for reading
OPEN fileName FOR OUTPUT     // create (or overwrite) a file for writing
READ fileVariable FROM file  // read a record from the file
WRITE expression TO file    // write a record to the file
CLOSE file                   // release the file

5.3 Network I/O (conceptual)

OPEN url "https://api.example.com/quote" FOR INPUT
READ line FROM url
CLOSE url
WRITE "Quote received: ", line

6. I/O in Python

6.1 Keyboard I/O

# read a line of text
name = input("Enter your name: ")

# read an integer, with basic validation
while True:
    try:
        age = int(input("Enter your age: "))
        break
    except ValueError:
        print("Please enter a valid integer.")
print("Hello", name, "- you are", age, "years old.")

6.2 File I/O

# Write to a file (creates/overwrites)
with open("scores.txt", "w") as f:
    f.write("Alice 85")
    f.write("Bob 78")

# Read from a file
with open("scores.txt", "r") as f:
    for line in f:
        print("Record:", line.strip())

6.3 Simple Network I/O (standard library)

import urllib.request

url = "https://api.example.com/quote"
with urllib.request.urlopen(url) as response:
    data = response.read().decode('utf-8')
    print("Quote received:", data)

6.4 Arrays (lists) and Loops

# read 5 test scores into a list and compute the average
scores = []
for i in range(5):
    s = int(input(f"Enter score {i+1}: "))
    scores.append(s)

total = sum(scores)
average = total / len(scores)
print("Average score =", average)

6.5 Re‑usable Procedure for Validated Input

def get_positive_int(prompt):
    while True:
        try:
            value = int(input(prompt))
            if value > 0:
                return value
            print("Value must be positive.")
        except ValueError:
            print("Please enter a valid integer.")

7. I/O in Java

7.1 Keyboard I/O

import java.util.Scanner;

Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();

System.out.print("Enter your age: ");
int age = sc.nextInt();

System.out.println("Hello " + name + " - you are " + age + " years old.");
sc.close();

7.2 File I/O (required for syllabus 3.3)

import java.io.*;

try (PrintWriter out = new PrintWriter(new FileWriter("scores.txt"));
     BufferedReader in = new BufferedReader(new FileReader("scores.txt"))) {

    // write records
    out.println("Alice 85");
    out.println("Bob 78");

    // read records
    String line;
    while ((line = in.readLine()) != null) {
        System.out.println("Record: " + line);
    }
} catch (IOException e) {
    System.err.println("File error: " + e.getMessage());
}

7.3 Simple Network I/O (conceptual example)

import java.net.*;
import java.io.*;

URL url = new URL("https://api.example.com/quote");
try (BufferedReader br = new BufferedReader(
        new InputStreamReader(url.openStream()))) {
    String line = br.readLine();
    System.out.println("Quote received: " + line);
}

7.4 Arrays, Selection and Iteration

// read 5 scores into an array and compute the average
int[] scores = new int[5];
int total = 0;

for (int i = 0; i < scores.length; i++) {
    System.out.print("Enter score " + (i+1) + ": ");
    scores[i] = sc.nextInt();
    total += scores[i];
}
double average = total / (double) scores.length;
System.out.println("Average = " + average);

7.5 Menu‑driven Program (selection + loop)

int choice;
do {
    System.out.println("Menu");
    System.out.println("1 – Add two numbers");
    System.out.println("2 – Find largest of three");
    System.out.println("0 – Quit");
    System.out.print("Enter choice: ");
    choice = sc.nextInt();

    switch (choice) {
        case 1:
            System.out.print("a: "); int a = sc.nextInt();
            System.out.print("b: "); int b = sc.nextInt();
            System.out.println("Sum = " + (a + b));
            break;
        case 2:
            System.out.print("x: "); int x = sc.nextInt();
            System.out.print("y: "); int y = sc.nextInt();
            System.out.print("z: "); int z = sc.nextInt();
            int max = Math.max(x, Math.max(y, z));
            System.out.println("Largest = " + max);
            break;
        case 0:
            System.out.println("Good‑bye!");
            break;
        default:
            System.out.println("Invalid choice – try again.");
    }
} while (choice != 0);

8. Validation, Common Errors & Good Practices

  • Never trust the user – always convert and check the type of input.
  • Provide clear, unambiguous prompts (e.g., “Enter a whole number between 1 and 100”).
  • When reading files or network streams, always handle possible IOException (Java) or try/except (Python).
  • Close files, sockets or scanners when finished to free system resources.
  • If you write to a file and need the data immediately, call flush() (Java) or use the with statement (Python) which flushes automatically.
  • Use loops for repeated input until valid data is received.
  • When working with arrays, check that the index is within bounds.

9. Tracing an I/O Program

Example pseudocode that reads five scores, stores them in an array, and calculates the average:

DECLARE scores[5] : INTEGER
total ← 0
FOR i ← 1 TO 5 DO
    READ scores[i]               // input
    total ← total + scores[i]    // accumulate
END FOR
average ← total / 5
WRITE "Average = ", average

Trace table (sample input: 12, 15, 9, 20, 14)

Step i scores[i] total Output
1 (read 1)11212
2 (read 2)21527
3 (read 3)3936
4 (read 4)42056
5 (read 5)51470
6 (calculate)70
7 (output)70Average = 14

10. Emerging Technologies (Syllabus 5.2‑6.3 – brief overview)

  • Digital currency & blockchain – data stored in distributed ledgers; transactions are verified by cryptographic hashes.
  • Artificial intelligence & machine learning – programs that learn patterns from data; often require large I/O streams (datasets, sensors).
  • Robotics & IoT (Internet of Things) – sensors provide input, actuators provide output; communication often via wireless networks.
  • Cyber‑security – encryption, authentication, and integrity checks protect I/O against tampering.

11. Summary

Input and output connect a program with the real world. For the IGCSE you must be able to:

  • Identify hardware devices and software channels used for I/O.
  • Explain basic network concepts (packets, MAC/IP, error‑detection).
  • Write correct I/O statements in pseudocode, Python and Java, including file handling.
  • Use arrays, selection and iteration to process multiple inputs.
  • Validate data, handle exceptions, and close resources properly.
  • Trace programs using tables and understand where the OS and language libraries intervene.

12. Practice Questions

  1. Write a Python program that asks the user for three numbers and prints the largest of the three.
  2. In Java, extend the rectangle‑area program so that it also asks for the unit of measurement (e.g., “m”, “cm”) and displays the result with the appropriate unit squared.
  3. Complete the following pseudocode to read five test scores into an array, compute the total and the average, then display the result.
    DECLARE scores[5] : INTEGER
    total ← 0
    FOR i ← 1 TO 5 DO
        _______               // read each score
        total ← total + ______
    END FOR
    average ← total / 5
    WRITE "Average score = ", average
            
  4. Explain why input validation is essential. Give an example of a calculation that would give an incorrect result if a non‑numeric string were accepted as input.
  5. Write a menu‑driven Java program (using switch and a do‑while loop) that offers the user:
    • 1 – Convert Celsius to Fahrenheit
    • 2 – Convert Fahrenheit to Celsius
    • 0 – Exit
    Include input validation for the temperature value.
  6. Provide a short Python script that reads a text file called data.txt, counts how many lines contain the word “error”, and writes the count to a new file called report.txt.
Suggested flowchart pattern for most I/O programs: Prompt → Input → Validate → Process → Output. Use a decision diamond for validation and a loop block for repeated input.

Create an account or Login to take a Quiz

39 views
0 improvement suggestions

Log in to suggest improvements to this note.