Entity-Relationship Diagrams and User-Interface Design

UNIT 2 • MODULE 2 • LESSON 06

The library’s data has to live somewhere. In Lesson 04 the DFD showed data stores called Members, Books and Loans, and the data dictionary listed their fields. Before anyone builds a database or writes C structures, the designer must decide exactly which things the system stores data about and how those things are related. The tool for that is the entity-relationship diagram (ERD), a semantic data model. The second half of this lesson turns to the part of the design that people actually see: screens and reports.

What you will learn

  • Entities, attributes, primary keys and foreign keys.
  • Relationships and their cardinality: one-to-one, one-to-many and many-to-many.
  • How to read and draw an ERD in crow’s foot notation.
  • How to resolve a many-to-many relationship with a link entity.
  • How an entity becomes a C struct.
  • Guidelines for good screens, reports and user interfaces, and how to critique a poor design.

Part 1: Entities, attributes and keys

TermMeaningLibrary example
EntityA thing (person, object, event or idea) about which the system stores data. Written as a singular noun, often in capitals.MEMBER, BOOK, LOAN
AttributeA property of an entity; one data item.Name, Phone, Title, DueDay
Primary key (PK)An attribute (or set of attributes) whose value is unique for every occurrence of the entity.MemberID, BookID, LoanID
Foreign key (FK)An attribute in one entity that is the primary key of another entity, used to link them.MemberID inside LOAN

Primary keys are usually shown underlined. Names are poor primary keys because two members can share a name; that is why systems invent ID numbers. A foreign key is how a relationship is actually stored: each LOAN record holds the MemberID of the member who made it.

Part 2: Relationships and cardinality

A relationship is a link between entities, described with a verb (a member makes a loan). Its cardinality (or degree) says how many occurrences of one entity can be linked to one occurrence of the other.

CardinalityMeaningExample
One-to-one (1:1)Each A is linked to at most one B, and each B to at most one A.Each school has one principal; each principal leads one school.
One-to-many (1:M)Each A can be linked to many B, but each B to only one A.One member makes many loans; each loan is made by one member.
Many-to-many (M:N)Each A can be linked to many B, and each B to many A.A member borrows many books over time; a book is borrowed by many members.

Crow’s foot notation

In crow’s foot notation, the relationship is a line between entity boxes. A short bar (or two bars) at an end means “one”; a three-pronged crow’s foot means “many”. Read each end separately: stand at one entity, look along the line, and read the symbol at the far end.

MEMBERMemberIDNamePhoneLOANLoanIDMemberID (FK)BookID (FK)LoanDayDueDayBOOKBookIDTitleAuthormakesis in
ER diagram for the library, in crow’s foot notation. Two bars mean exactly one; the crow’s foot means many.

Reading the ERD: from MEMBER, look towards LOAN and you see a crow’s foot, so one member makes many loans. From LOAN, look back towards MEMBER and you see bars, so each loan is made by exactly one member. The same pattern links BOOK and LOAN. Some textbooks use a different notation (Chen notation with diamonds and 1 and M labels). Either is acceptable if used consistently and clearly.

Resolving a many-to-many relationship

MEMBERBOOKborrows (many-to-many)
Before resolving: a member borrows many books, and a book is borrowed by many members over time.

Many-to-many relationships cannot be stored directly in a simple table or array, because there is nowhere to put “many” foreign keys on either side. The fix is to introduce a link entity (also called an associative or junction entity) between them. Here, MEMBER borrows BOOK (M:N) becomes MEMBER 1:M LOAN M:1 BOOK, which is the first ERD above. LOAN also turns out to be a natural place for the attributes that belong to the borrowing itself, such as LoanDay and DueDay.

Try it 1Name the cardinality

Choose the cardinality for each relationship.

Worked example: an ERD from a scenario

Scenario. An inter-island ferry company runs several vessels. Each vessel makes many sailings, and each sailing uses one vessel. Passengers make bookings; a passenger may make many bookings, and each booking is for one passenger on one sailing. A sailing can carry many bookings. The company records each vessel’s name and capacity, each sailing’s date and departure time, each passenger’s name and phone number, and each booking’s seat class.

StepWorking
1. Entities (nouns that need data stored)VESSEL, SAILING, PASSENGER, BOOKING. “Company” is the owner of the system, not an entity here.
2. AttributesVESSEL: name, capacity. SAILING: date, departure time. PASSENGER: name, phone. BOOKING: seat class.
3. Primary keysInvent unique IDs: VesselID, SailingID, PassengerID, BookingID.
4. Relationships (verbs)VESSEL makes SAILING; PASSENGER makes BOOKING; SAILING carries BOOKING.
5. CardinalityVESSEL 1 to M SAILING; PASSENGER 1 to M BOOKING; SAILING 1 to M BOOKING.
6. Foreign keysSAILING holds VesselID; BOOKING holds PassengerID and SailingID.
7. Check for M:NPASSENGER and SAILING are many-to-many (a passenger takes many sailings; a sailing carries many passengers), but BOOKING already resolves it as a link entity.

The finished ERD has four boxes in a row or a T-shape, three labelled relationship lines with bars at the “one” end and crow’s feet at the “many” end, primary keys underlined, and foreign keys marked. Notice that BOOKING plays the same role as LOAN in the library: it is the event that links two other entities and carries its own attributes.

Part 3: From ERD to C

The ERD is a design for the data, and in C each entity becomes a struct type, each attribute a field, and each foreign key an ordinary field holding another entity’s key. A collection of entity occurrences becomes an array of structs.

Worked example: the LOAN entity in C

#include <stdio.h>

/* One LOAN entity becomes one struct. */
struct Loan {
    int loanId;    /* primary key */
    int memberId;  /* foreign key */
    int bookId;    /* foreign key */
    int loanDay;
    int dueDay;
};

int main(void)
{
    struct Loan loans[3] = {
        {1, 1001, 52001, 10, 24},
        {2, 1002, 52007, 11, 25},
        {3, 1001, 52003, 15, 29}
    };
    int m = 1001;  /* member to look up */

    printf("Loans for member %d:\n", m);
    for (int i = 0; i < 3; i++) {
        struct Loan L = loans[i];
        if (L.memberId == m)
            printf("  loan %d: book %d, "
                   "due %d\n", L.loanId,
                   L.bookId, L.dueDay);
    }
    return 0;
}

Output:

Loans for member 1001:
  loan 1: book 52001, due 24
  loan 3: book 52003, due 29

Notice how the one-to-many relationship appears in code: to find all loans for one member, the program searches the loans array for records whose foreign key memberId matches. Loan 2 belongs to a different member, so it is skipped. In Lesson 07 this same struct is used in the full library program.

Part 4: Designing screens, reports and user interfaces

Interface design (Lesson 05) includes the user interface: the screens people use to enter and view data, and the reports the system prints or displays. A technically correct system with a confusing interface will cause errors and frustration, so usability (Lesson 01) depends heavily on this part of the design.

Guidelines for screens and forms

GuidelineWhat it means
Clear labelsEvery field has a short, plain-language label next to it. Avoid codes and abbreviations users may not know.
Readable textUse a clear font at a comfortable size; avoid all capitals for long text.
Colour and contrastUse strong contrast between text and background; never use colour alone to carry meaning; use few colours.
Layout and spacingGroup related fields; align fields; leave white space; order fields in the order users think (name, then contact, then address).
ConsistencySame button names, positions and colours on every screen; same date format everywhere.
Suitable field sizes and formatsSize boxes to fit the data; show the expected format (DD/MM/YYYY); offer drop-down lists or calendars where possible to reduce typing.
Prevent and handle errorsValidate input; keep dangerous actions (delete) away from common ones and ask for confirmation.
Helpful messagesError messages say what went wrong and how to fix it, in plain words.
FeedbackConfirm actions (“Member saved”) and show progress for slow tasks.

Guidelines for reports

  • A clear title, plus the date and time the report was produced.
  • Column headings, with units where needed.
  • Data sorted in a useful order (for example by surname or by days overdue).
  • Numbers right-aligned, with totals or counts where useful.
  • Page numbers (“Page 2 of 5”) on printed reports.
  • Only the data the reader needs; summary first, detail after.

Critiquing a poor design

MEMBER REG FORM V2 FINAL1nm2Ph#3D.O.B (YYYYDDMM)4AddressGO!!Del5ERROR 0x3F: INVALID INPUT6All fields required. Press GO!! to save or Del to delete everything.
A deliberately poor screen design. Each numbered flaw breaks a guideline from Part 4.

Try it 2Which guideline is broken?

Match each numbered flaw on the poor screen to the guideline it breaks most clearly.

A redesigned screen would have a calm, high-contrast colour scheme; a title such as “Register a new member”; labelled fields for First name, Surname, Phone (7 digits) and Date of birth (DD/MM/YYYY, with a calendar); a clear “Save member” button; a separate “Cancel” button; no delete button on a registration form; and error messages next to the field they refer to.

Try it 3ERD and interface drill

“ERD” checks data modelling. “Interface” checks screen and report guidelines.

Common mistakes

  • Drawing an attribute (such as Phone) as an entity.
  • Choosing a name as a primary key. Names are not unique.
  • Reading crow’s foot notation from the wrong end. Stand at one entity and read the symbol at the other end.
  • Leaving a many-to-many relationship unresolved when the question asks for a design that could be implemented.
  • Critiquing a screen with vague comments such as "it looks bad". Name the guideline and the specific flaw.
  • Reusing a textbook or specimen scenario word for word. Practise on your own scenarios so that you understand the method.

Summary

IdeaKey point
Entity, attributeA thing stored about; one of its properties.
KeysPrimary key unique; foreign key links to another entity’s primary key.
Cardinality1:1, 1:M, M:N; crow’s foot means many.
M:NResolve with a link entity holding both foreign keys.
CEntity becomes a struct; occurrences become an array of structs.
ScreensLabels, readability, contrast, layout, consistency, formats, error prevention, helpful messages, feedback.
ReportsTitle, date, headings, sorted, aligned, totals, page numbers.

Review questions

1. Define entity, attribute and primary key.

Show answer

An entity is a thing about which data is stored. An attribute is a property of an entity. A primary key is an attribute whose value uniquely identifies each occurrence of the entity.

2. What is a foreign key? Give an example from the library ERD.

Show answer

An attribute in one entity that is the primary key of another, used to link them. MemberID in LOAN is a foreign key referring to MEMBER.

3. Explain the three types of relationship cardinality with an example of each.

Show answer

One-to-one: each country has one capital city. One-to-many: one customer places many orders. Many-to-many: students and clubs.

4. A sports academy has COACHes and ATHLETEs. Each athlete has one coach; a coach trains many athletes. Describe the ERD.

Show answer

Two entities, COACH (CoachID PK, Name) and ATHLETE (AthleteID PK, Name, CoachID FK), joined by a one-to-many relationship "trains", with bars at COACH and a crow’s foot at ATHLETE.

5. Why must a many-to-many relationship be resolved, and how?

Show answer

It cannot be stored directly because neither side can hold many foreign keys. Add a link entity whose primary key includes both foreign keys, giving two one-to-many relationships.

6. State FOUR guidelines for designing a data entry screen.

Show answer

Any four: clear labels; readable font; good colour contrast; logical grouping and spacing; consistency; field sizes and formats that match the data; validation and confirmation for dangerous actions; helpful error messages; feedback.

7. State THREE features of a well-designed printed report.

Show answer

Any three: title; date and time; column headings; sorted data; right-aligned numbers; totals; page numbers.

Homework

  1. A music school has TEACHERs, STUDENTs and INSTRUMENTs. A teacher teaches many students; a student studies one or more instruments; an instrument is studied by many students. Draw the ERD, resolving any many-to-many relationship, and list a primary key for each entity.
  2. Write a C struct for one of your entities and a short program that prints all records matching a foreign key.
  3. Find a real form (paper or online) and critique it against at least five guidelines from Part 4.
  4. Design a printed "Overdue loans" report for the library, showing headings and two sample rows.

Mastery quiz: ER diagrams and interface design

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: Entity-Relationship Diagrams and User-Interface Design

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. In an ERD, a thing about which data is stored is a
    2. Which is the best primary key for STUDENT?
    3. A field in one table that refers to the primary key of another is a
    4. One customer, many orders, each order one customer. Cardinality?
    5. In crow’s foot notation, the three-pronged symbol means
    6. A many-to-many relationship is resolved by
    7. In C, an entity is most naturally represented as
    8. Which is a helpful error message?
    9. Putting a Delete button right beside Save breaks which guideline?
    10. Which feature belongs on a printed report?

    Exam tips

    Specimen Unit 2 Paper 01 (2021), Item 16. You are shown an ER diagram and asked to read a relationship from it. Read each end of the line separately, as in Part 2, and say the sentence aloud: "one A has many B".

    Specimen Unit 2 Paper 02 (2021), Question 4(b). You must produce an ER model from a written scenario. Method: underline nouns that need data stored (entities); note their properties (attributes); pick a unique key for each; underline verbs that link entities (relationships); decide the cardinality of each from the scenario wording; resolve any many-to-many with a link entity if the question asks for an implementable model. Label every relationship and show keys. Practise with your own scenarios, such as the music school in the homework.

    Previous: Unit 2 • Module 2 • Lesson 05 – Software Design: Architecture, Structure Charts and Design Strategies. Next: Unit 2 • Module 2 • Lesson 07 – From Design to Code: The Implementation Phase in C.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Software Engineering (Unit 2, Module 2). Specific Objective 5 (second part): semantic data models (entity-relationship diagrams); guidelines for the design of screens, reports and user interfaces.

    Video search terms

    Search YouTube for: "entity relationship diagram crow’s foot tutorial", "resolve many to many relationship link entity", "primary key foreign key explained", "user interface design principles for beginners".

    Try it 4Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/12/01

    - First version of the lesson.

    © 2026 islandclass.org

    Software Design: Architecture, Structure Charts and Design Strategies

    UNIT 2 • MODULE 2 • LESSON 05

    The analysis phase produced a requirements specification for the library: what the system must do. Design answers a different question: how will the system be organised so that it does those things well? A good design is like an architect’s plan for a house. Before anyone lays a block, the plan shows the rooms, how they connect, where the pipes run and what each room is for. In software, the “rooms” are sub-systems and modules, and the “pipes” are the data passed between them.

    You already met top-down design and hierarchy charts in Unit 1 • Module 2 • Lesson 02 – Top-Down, Bottom-Up, Stepwise Refinement and Hierarchy Charts, where they helped you design a single algorithm. This lesson places the same thinking inside system design and adds the tools professionals use: structure charts, design strategies and design deliverables.

    What you will learn

    • The four design activities: architectural, interface, data structure and algorithm design.
    • System structuring into sub-systems, modules and programs.
    • Top-down and bottom-up design methods.
    • How to read and draw a structure chart, including data couples and control flags.
    • Functional versus object-oriented design strategies.
    • Coupling and cohesion as measures of a good modular design.
    • The deliverables of design: the system architecture and the design specification.

    Part 1: The four design activities

    ActivityDecidesLibrary example
    Architectural designThe overall structure: the sub-systems, the modules within them, and how they relate and communicate.Split into Loans, Catalogue and Membership sub-systems that share one database.
    Interface designHow each component communicates: with users (screens, reports) and with other components (parameters, data formats).The loan screen layout; recordLoan takes a member ID, a book ID and a day number.
    Data structure designHow data is organised and stored: records, files, tables, arrays.A Loan record with MemberID, BookID, LoanDay, DueDay, ReturnDay; loans held in a table.
    Algorithm designThe step-by-step logic of each module.Pseudocode for finding all loans more than 14 days old.

    These activities overlap and feed each other. Architectural design usually comes first, because it decides what modules exist. Interface, data and algorithm design then fill in the detail for each one.

    System structuring: sub-systems, modules and programs

    Large systems are divided into layers of smaller parts:

    • A sub-system is a major part of the system that could almost stand alone, with its own purpose (for example the Loans sub-system).
    • A module is a smaller, named unit within a sub-system that does one job (for example Record loan). In C a module is usually a function, or a source file of related functions.
    • A program is an executable unit built from modules (for example the front-desk loans program that staff run).

    Structuring is what makes large systems manageable. Different programmers can build different modules at the same time; each module can be tested alone; and a later change usually affects only one module.

    Try it 1Which design activity?

    Choose the design activity each decision belongs to.

    Part 2: Top-down and bottom-up design

    Top-downBottom-up
    Starts withThe whole system as one problemSmall, well-understood components
    ThenBreaks it into sub-problems, then breaks those down again (stepwise refinement) until each piece is simpleCombines components into larger units until the whole system is built
    StrengthsKeeps the overall goal in view; clear structure; easy to divide workReuses existing tested parts; useful low-level pieces are built and tested early
    WeaknessesLow-level problems may be found late; can produce duplicate modulesOverall structure may be unclear until late; parts may not fit together

    In practice designers mix both. They sketch the system top-down to get the structure, but reuse existing library functions and components bottom-up. Reuse-oriented development from Lesson 02 is largely a bottom-up approach.

    Part 3: Structure charts

    A structure chart shows the modules of a program and how they call each other, together with the data passed between them. It looks like the hierarchy charts from Unit 1, with extra symbols for data.

    Library loansmainRecord loanrecordLoanFind bookfindBookRecord returnrecordReturnFind loanfindLoanPrint overdueprintOverdueDays latedaysLatemember, book, dayokbook, daydaybookindexbookindexloan, daydays
    Structure chart for the library loans program. Boxes are modules; lines show which module calls which; small arrows are data couples (open circle) and control flags (filled circle).
    SymbolMeaning
    RectangleA module (in C, usually a function). The top module controls the others.
    Line from a higher to a lower moduleThe higher module calls (uses) the lower one.
    Arrow with an open circleA data couple: data passed between modules, in the direction of the arrow.
    Arrow with a filled circleA control flag: a signal (such as found, ok, end of file) that affects what the receiving module does.
    Curved arrow around lines (optional)The calls are repeated (a loop).
    Small diamond at a module (optional)The call is made only if a condition is true (selection).

    Reading the chart above. The top module main calls three modules. It passes a member, a book and a day number down to Record loan and receives an ok flag back, which tells main whether to print a confirmation or an error. Record loan calls Find book, passing a book ID and getting back an index (its position in the list of books). Print overdue receives today’s day number and, for each loan, calls Days late. You will turn this exact chart into C in Lesson 07.

    Structure chart vs DFD

    Do not confuse the two. A DFD (Lesson 04) is an analysis model of how data flows through the whole system, including people and stores. A structure chart is a design model of how a program’s modules are arranged and call each other. A common design step is to turn each DFD process into one or more modules on a structure chart: process 1 Record loan becomes the Record loan module, and so on.

    Try it 2Read the structure chart

    Use the structure chart above to answer each question.

    Worked example: from DFD to structure chart

    Here is how the designer produced the chart above from the level 1 DFD in Lesson 04. Follow the same steps for your own systems.

    StepWhat the designer didResult
    1. One controllerCreate a top module that runs the program and decides which task to do.Library loans (main)
    2. One module per DFD processEach numbered process becomes a second-level module, named with the same verb phrase.Record loan, Record return, Print overdue
    3. Find repeated or separable jobsLook inside each process for a sub-task that is clearly separate or could be reused.Searching for a book, searching for a loan, working out days late
    4. Add data couplesFor each call, ask: what data must go down, and what result must come back?book down, index up; loan and day down, days up
    5. Add control flagsWhere a module must report success or failure, add a flag.ok returned from Record loan
    6. Check qualityDoes each module do one job? Are couples few and clear?Yes: six small, cohesive modules

    Notice what disappeared: the external entities and data stores of the DFD are not boxes on the structure chart. Entities become input and output inside modules (for example, printing the overdue list for the librarian), and data stores become data structures (arrays of records in Lesson 07, or files and database tables in a larger system).

    CASE tools in design

    The CASE tools from Lesson 04 are just as useful here. Design tools can draw structure charts and class diagrams, keep every module description in the shared repository alongside the data dictionary, check that each data couple on a chart is defined, and in some cases generate function headers or class skeletons directly from the design. As in analysis, the tool records and checks the design; the designer still makes the decisions.

    Part 4: Good modular design: coupling and cohesion

    Two ideas help judge whether a structure chart is a good design.

    • Cohesion is how closely the parts inside one module belong together. Aim for high cohesion: each module does one clear job. “Find book” is highly cohesive. A module called “Do loan stuff and print report and check password” is not.
    • Coupling is how much modules depend on each other. Aim for low coupling: modules communicate only through a few clearly defined parameters, not through shared global variables. Low coupling means a change inside one module rarely breaks another.

    High cohesion and low coupling directly support maintainability (Lesson 01) and make modules easier to test separately (Lesson 08). When a structure chart has a module with many data couples going in and out, or a module that seems to do several unrelated things, that is a sign the design should be improved.

    Part 5: Design strategies: functional vs object-oriented

    Functional (function-oriented) designObject-oriented design
    FocusThe functions (actions) the system performsThe objects (things) in the system and their behaviour
    System is built fromFunctions that transform data; data is often shared between themClasses that bundle data (attributes) with the operations (methods) on it
    Typical toolsDFDs, structure chartsClass diagrams and other UML diagrams
    Library exampleFunctions recordLoan, recordReturn, printOverdue working on loan recordsClasses Member, Book and Loan; a Loan object knows its own due day and can calculate its days late
    SuitsSystems with clear processing steps; languages such as CLarge systems with many interacting things; languages such as Java, Python, C++

    Because this course uses C, our designs are functional: structure charts of functions. You should still be able to describe the object-oriented alternative and compare the two. A key advantage of object-oriented design is encapsulation: an object’s data can be changed only through its own methods, which protects it from accidental change. A key advantage of functional design is simplicity for smaller, process-driven systems.

    Part 6: Deliverables of the design phase

    DeliverableContents
    System architectureThe sub-systems and modules and how they connect, usually shown as block diagrams and structure charts; hardware and network layout if relevant.
    Design specificationThe detailed design: structure charts, module descriptions (inputs, outputs, purpose), data structures and file or database designs, screen and report layouts, and algorithms in pseudocode.

    The design specification is what programmers work from in the implementation phase. A good one is detailed enough that two different programmers would produce code that fits together. It also becomes system documentation for later maintainers.

    Worked example: a module description

    Module: findBook
    Purpose: locate a book
      by its ID
    In:  book ID (int)
    Out: index in books
      array, or -1
    Called by: recordLoan
    Algorithm: linear search

    Every module on the structure chart gets a short description like this. Notice how it links to your Unit 2 Module 1 work: the algorithm is the linear search from Unit 2 • Module 1 • Lesson 07 – Searching in C: Linear Search and Binary Search.

    Try it 3Design drill

    “Concepts” checks design vocabulary. “Charts” checks structure chart symbols and quality.

    Common mistakes

    • Mixing up structure charts and DFDs. Structure charts show calls between program modules; DFDs show data movement through a system.
    • Drawing a structure chart with no data couples. The data passed between modules is a key part of the design.
    • Using a control flag where a data couple is meant, or the reverse.
    • Describing top-down design as "starting with the code". It starts with the whole problem.
    • Forgetting interface design includes interfaces between modules, not just screens.

    Summary

    IdeaKey point
    Four design activitiesArchitectural, interface, data structure, algorithm.
    StructuringSystem, sub-systems, modules, programs.
    MethodsTop-down (decompose) and bottom-up (compose), often mixed.
    Structure chartModules, calls, data couples (open circle), control flags (filled circle).
    QualityHigh cohesion, low coupling.
    StrategiesFunctional (functions and data flows) vs object-oriented (classes and objects).
    DeliverablesSystem architecture and design specification.

    Review questions

    1. Name and describe the FOUR design activities.

    Show answer

    Architectural design (overall structure of sub-systems and modules and their relationships); interface design (how components communicate with users and each other); data structure design (how data is organised and stored); algorithm design (the step-by-step logic of each module).

    2. What is architectural design?

    Show answer

    Deciding the overall structure of the system: identifying the sub-systems and modules and the relationships and communication between them.

    3. Compare top-down and bottom-up design.

    Show answer

    Top-down starts with the whole system and breaks it into smaller parts; it keeps the goal in view but may find low-level problems late. Bottom-up builds and combines small components; it reuses tested parts but the overall structure may be unclear until late.

    4. Distinguish between a data couple and a control flag.

    Show answer

    A data couple (open circle) carries data that the receiving module processes, such as a book ID. A control flag (filled circle) carries a signal that affects what the receiving module does, such as found or ok.

    5. Explain why low coupling and high cohesion are desirable.

    Show answer

    High cohesion means each module does one job, so it is easier to understand and test. Low coupling means modules depend on each other little, so a change in one module is unlikely to break others. Both improve maintainability.

    6. Compare functional and object-oriented design strategies.

    Show answer

    Functional design decomposes the system into functions that transform data, using tools such as structure charts. Object-oriented design identifies objects that combine data and operations, using class diagrams; it supports encapsulation and reuse.

    7. List THREE items in a design specification.

    Show answer

    Any three: structure charts; module descriptions; data structures or file and database designs; screen and report layouts; algorithms in pseudocode.

    Homework

    1. Draw a structure chart for the sports club system from Lesson 04, with at least five modules, data couples and one control flag.
    2. Write module descriptions (purpose, in, out, called by) for two of your modules.
    3. List the classes you would use for the sports club in an object-oriented design, with two attributes and one method each.
    4. Find a module in one of your own Unit 1 C programs that has low cohesion, and explain how you would split it.

    Mastery quiz: Software design

    This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

    Mastery quiz: Software Design: Architecture, Structure Charts and Design Strategies

    Your course badges: loading saved progress…

    View badges

      No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

      Saved in this browser on this device. Clearing browser data may remove your badges.

      Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

      1. Identifying sub-systems and the relationships between them is
      2. Designing a screen layout is part of
      3. Choosing to store loans in an array of records is
      4. Breaking a whole problem into smaller and smaller parts is
      5. On a structure chart, an arrow with a filled circle shows
      6. A line from module A down to module B shows that
      7. A module that does one well-defined job has
      8. Low coupling means
      9. A design built from classes that bundle data with methods is
      10. The detailed design that programmers code from is the

      Exam tips

      Specimen Unit 2 Paper 01 (2021), Item 28. This item describes the activity of identifying sub-systems and their relationships and asks which design activity it is. Learn a one-line definition of each of the four design activities so that you can match a description to its name quickly.

      For structured questions, a structure chart earns marks for correct hierarchy (who calls whom), sensible module names, and labelled data couples and flags. Use a ruler-straight, top-to-bottom layout and keep labels short.

      When asked to compare strategies or methods, use a two-column comparison: focus, tools, strengths, and a short example.

      Previous: Unit 2 • Module 2 • Lesson 04 – Data Flow Diagrams, Data Dictionaries and CASE Tools. Next: Unit 2 • Module 2 • Lesson 06 – Entity-Relationship Diagrams and User-Interface Design.

      Syllabus link: CAPE Computer Science (CXC A19/U2/21), Software Engineering (Unit 2, Module 2). Specific Objective 5 (first part): design activities (architectural, interface, data structure, algorithm); structure charts and CASE tools; top-down, bottom-up and system structuring (sub-systems, modules, programs); functional versus object-oriented design strategies; deliverables (system architecture, design specification).

      Video search terms

      Search YouTube for: "structure chart data couple control flag", "top down vs bottom up design", "coupling and cohesion explained", "function oriented vs object oriented design".

      Try it 4Quick quiz

      Tap an answer. All eight questions are self-checks on this lesson.

      Updates

      2026/12/01

      - First version of the lesson.

      © 2026 islandclass.org

      Data Flow Diagrams, Data Dictionaries and CASE Tools

      UNIT 2 • MODULE 2 • LESSON 04

      In Lesson 03 the analyst gathered facts about the Chaguanas Community Library and wrote requirements in words. Words are useful, but long paragraphs make it hard to see how data moves around a system: who supplies it, what happens to it, and where it is kept. Analysts therefore draw models. This lesson covers the most important analysis model in the syllabus, the data flow diagram (DFD), together with the data dictionary that defines every data item in it, and the CASE tools that help analysts produce both.

      What you will learn

      • The four DFD symbols: external entity, process, data store and data flow.
      • The rules that make a DFD valid.
      • Context diagrams (level 0) and level 1 DFDs, and how they must balance.
      • How to build a level 1 DFD from a written scenario, step by step.
      • What a data dictionary is and how to write entries for it.
      • What CASE tools are, what they can produce, and what they cannot do for you.

      Part 1: What a DFD shows

      A data flow diagram shows how data moves through a system and how it is transformed by processes. It does not show the order in which things happen, loops or decisions: that is the job of flowcharts and pseudocode. A DFD answers: where does data come from, what is done to it, where is it stored, and where does it go?

      EntitynProcessD1Storedata flow
      The four DFD symbols used in this course (Gane and Sarson style).
      SymbolMeaningNaming ruleLibrary example
      External entityA person, organisation or other system outside the system boundary that sends or receives data.A nounMember, Head librarian
      ProcessAn activity that transforms incoming data into outgoing data.A number plus a verb phrase1 Record loan
      Data storeData held for later use: a file, a database table, even a card index.An ID (D1, D2) plus a plural nounD3 Loans
      Data flowData moving between the other symbols, in the direction of the arrow.A noun phrase naming the dataloan details

      Different textbooks use slightly different shapes. In the Yourdon style, processes are circles; in the Gane and Sarson style used here, processes are rounded rectangles. Either is acceptable in an exam if you use it consistently and label everything.

      Part 2: The rules of a valid DFD

      A DFD that breaks these rules is marked as incorrect even if the drawing is neat. Learn them as a checklist:

      • Every data flow must start or end at a process. Data cannot flow directly from an external entity to a data store, from one data store to another, or between two external entities.
      • Every process must have at least one input flow and at least one output flow. A process with only inputs is a “black hole”; one with only outputs is a “miracle”.
      • Every data store must have at least one flow in (something writes to it) and at least one flow out (something reads it), somewhere in the full set of diagrams.
      • Every flow is labelled with the data it carries. Flows into and out of data stores may be left unlabelled only if the whole record is moved, but labelling is safer.
      • Processes are named with verbs (“Record loan”), not nouns (“Loans”).
      • A process transforms data: the data going out must be different from, or derived from, the data coming in.

      Try it 1Valid or invalid?

      Each statement describes part of a DFD. Decide whether it is allowed.

      Part 3: Levels of DFD

      Level 0: the context diagram

      The context diagram (level 0) shows the whole system as a single process, numbered 0, surrounded by its external entities. It has no data stores. Its purpose is to fix the system boundary: what is inside the system and who it exchanges data with.

      MemberHeadlibrarian0Library loanssystemrequestreceiptreturnoverdue list
      Level 0 (context diagram) for the library loans system: the whole system is one process, with only the external entities around it.

      Level 1: opening up the system

      A level 1 DFD breaks process 0 into its main sub-processes (usually three to seven), numbered 1, 2, 3 and so on, and shows the data stores they use.

      MemberHeadlibrarian1Record loan2Recordreturn3Produceoverdue listD2BooksD3LoansD1Membersrequestreceiptreturnbook statusloan detailsreturn dateloan recordscontactoverdue list
      Level 1 DFD for the same system. The single process is broken into three numbered processes, and the data stores appear.

      Read the level 1 diagram as a story. A member asks to borrow a book. Process 1 checks the book’s status in D2 Books, records the loan in D3 Loans and gives the member a receipt. When the book comes back, process 2 records the return date in D3 Loans. Each week, process 3 reads the loan records and members’ contact details and produces an overdue list for the head librarian.

      Balancing

      The levels must balance: every flow into or out of an external entity on the context diagram must appear on the level 1 diagram, and no new external flows may appear. Check the pair above: request, receipt and return connect Member to the system on both diagrams, and overdue list goes to Head librarian on both. They balance. A level 1 process can be broken down again into a level 2 diagram (processes 1.1, 1.2 and so on) if it is still complex.

      Part 4: Building a level 1 DFD from a scenario

      Exam questions often give a paragraph and ask for a level 1 DFD. Use this method every time.

      Scenario. A school sports club rents out equipment. A student fills in a rental form. The club secretary checks the student’s details in the student file and the item in the equipment file, then records the rental in the rentals file and gives the student a rental slip. When equipment is returned, the secretary updates the rentals file. At the end of each month, the secretary prepares a usage report from the rentals file for the sports teacher.

      StepWhat to doResult for the scenario
      1. External entitiesUnderline people or organisations outside the system that give or receive data.Student, Sports teacher (the secretary operates the system, so is not an entity here)
      2. Data storesUnderline files, records or lists that are kept.D1 Students, D2 Equipment, D3 Rentals
      3. ProcessesUnderline actions that change data. Name each with a verb.1 Record rental, 2 Record return, 3 Produce usage report
      4. Data flowsFor each process, list its inputs and outputs and label them.rental form, student details, item details, rental record, rental slip, returned item, return update, rental records, usage report
      5. Check the rulesEvery flow touches a process; every process has input and output; every store is written and read.D1 and D2 are only read here; that is acceptable if other processes (not in this scenario) maintain them, but mention it.
      6. BalanceDraw or imagine the context diagram and check the external flows match.Student: rental form, returned item in; rental slip out. Sports teacher: usage report out.

      Notice that the club secretary is not drawn as an external entity. When a person simply operates the system on behalf of someone else, the data really comes from the student. This is a common source of lost marks.

      Try it 2Name the DFD element

      Each item comes from the sports club scenario above. Choose what it should be on the level 1 DFD.

      Part 5: The data dictionary

      Labels on a DFD such as “loan details” are short. Programmers need to know exactly what each one contains. A data dictionary is a central list that defines every data item, data flow and data store in the system: its name, meaning, type, size, format and validation rules. It is “data about data” (metadata).

      Entries for data elements

      NameDescriptionTypeSize or formatValidation
      MemberIDUnique member numberText6 chars, e.g. M01234Starts with M; 5 digits
      BookIDBarcode on the bookText8 digitsExactly 8 digits
      LoanDateDate the book was borrowedDateDD/MM/YYYYNot in the future
      DueDateDate the book must be backDateDD/MM/YYYYLoanDate plus 14 days
      ReturnDateDate the book came backDateDD/MM/YYYYBlank or not before LoanDate

      Entries for flows and stores

      Composite items are often written with a simple notation: = means “is made up of”, + means “and”, and square or round brackets mark optional parts.

      loan details = MemberID
        + BookID + LoanDate
        + DueDate
      D3 Loans = {loan details
        + (ReturnDate)}
      { } repeats, ( ) optional

      The data dictionary links analysis to design and coding. In Lesson 06 the same items become attributes of entities, and in Lesson 07 they become fields of a C struct. If everyone works from the same dictionary, a BookID cannot be 8 digits in one module and 10 in another.

      Part 6: CASE tools

      CASE stands for Computer-Aided Software Engineering. CASE tools are programs that support software engineering activities. They range from simple diagram editors to large integrated environments that cover the whole life cycle.

      CASE tools can help toExamples of outputs
      Draw and edit diagrams with the correct symbolsDFDs, ER diagrams, structure charts, UML diagrams
      Check diagrams for rule errors and balancingA report listing a process with no output, or unbalanced levels
      Keep a central data dictionary (repository)Data dictionary listings and reports
      Generate code or database definitions from a designCode skeletons, table definitions
      Produce documentationFormatted specification documents and reports
      Support testing and project managementTest reports, schedules, version histories

      Upper CASE tools support early phases (analysis and design); lower CASE tools support later phases (coding, testing, maintenance). An integrated CASE environment covers both.

      CASE tools save time, enforce standards and keep diagrams and documents consistent. But they do not replace thinking. A CASE tool cannot interview users, decide what the requirements are, judge whether a project is feasible, or choose the best design. It can only check and present what the analyst enters. Tools can also be costly and take time to learn.

      Try it 3Could a CASE tool produce it?

      Decide whether each item is a typical CASE tool output or something only people can do.

      Try it 4DFD and data dictionary drill

      “Symbols” checks DFD notation and rules. “Dictionary” checks data dictionary and CASE ideas.

      Common mistakes

      • Drawing a flow from an external entity straight into a data store.
      • Naming processes with nouns ("Loans") instead of verbs ("Record loan").
      • Including the system operator (a clerk or secretary) as an external entity when the real source of data is someone else.
      • Putting data stores on a context diagram. Level 0 has none.
      • Forgetting to balance: adding a new flow to an entity on level 1 that is not on level 0.
      • Writing control logic (if, loop) into a DFD. DFDs show data movement only.
      • Thinking a CASE tool can gather requirements or make decisions.

      Summary

      IdeaKey point
      DFDShows how data moves and is transformed; four symbols.
      RulesEvery flow touches a process; every process has input and output; verb names; labelled flows.
      Context diagramLevel 0: one process, entities, no stores; sets the boundary.
      Level 1Main processes, numbered, with data stores; must balance with level 0.
      Data dictionaryDefines every data item, flow and store: type, size, format, validation.
      CASE toolsSoftware that supports engineering tasks; upper and lower CASE; helps but does not decide.

      Review questions

      1. Name and describe the four symbols used in a DFD.

      Show answer

      External entity: a source or destination of data outside the system. Process: an activity that transforms data, numbered and named with a verb. Data store: data held for later use, labelled with an ID such as D1. Data flow: a labelled arrow showing data moving between symbols.

      2. Which analysis model shows data being transformed as it passes through a system?

      Show answer

      The data flow diagram.

      3. State THREE rules for drawing a correct DFD.

      Show answer

      Any three: every flow must start or end at a process; every process needs at least one input and one output; no flow from store to store or entity to store; label every flow; name processes with verbs; every store must be written and read.

      4. Distinguish between a context diagram and a level 1 DFD.

      Show answer

      A context diagram shows the whole system as one process (0) with external entities and no data stores. A level 1 DFD breaks that process into numbered sub-processes and shows data stores and internal flows.

      5. What is meant by balancing DFDs?

      Show answer

      The external data flows on a lower-level diagram must match those on the higher-level diagram: no flows to or from external entities may be added or lost.

      6. What is a data dictionary, and why is it useful?

      Show answer

      A central record that defines every data item, flow and store, with type, size, format and validation. It keeps definitions consistent between analysts, designers and programmers and supports maintenance.

      7. Write a data dictionary entry for a field holding a student’s form class, such as 5B.

      Show answer

      Name: FormClass; description: student’s form class; type: text; size: 2 characters; format: digit then letter; validation: first character 1 to 6, second character A to F.

      8. Give TWO outputs a CASE tool might produce and ONE thing it cannot do.

      Show answer

      Outputs: DFDs or ER diagrams; data dictionary reports; rule-check reports; generated code. It cannot interview users or decide what the requirements should be.

      Homework

      1. Draw the context diagram and level 1 DFD for the sports club scenario in Part 4.
      2. Add a new process to the library level 1 DFD: "4 Register member", which receives an application from Member and writes to D1 Members. Redraw the context diagram so it still balances.
      3. Write five data dictionary entries for the sports club system.
      4. Process 2 Record return should also update the book’s status in D2 Books. Add the flow and label it.

      Mastery quiz: DFDs, data dictionaries and CASE

      This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

      Mastery quiz: Data Flow Diagrams, Data Dictionaries and CASE Tools

      Your course badges: loading saved progress…

      View badges

        No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

        Saved in this browser on this device. Clearing browser data may remove your badges.

        Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

        1. Which model shows how data is transformed as it moves through a system?
        2. In a DFD, a person outside the system who supplies data is a
        3. Which flow is NOT allowed?
        4. A context diagram contains
        5. Balancing means
        6. Which is the best name for a process?
        7. A data dictionary entry would include
        8. Which is a typical CASE tool output?
        9. Upper CASE tools mainly support
        10. A process with outputs but no inputs is

        Exam tips

        Specimen Unit 2 Paper 01 (2021), Items 26, 27 and 29. Item 26 gives a DFD and asks what one symbol represents; Item 27 asks which model shows data being transformed; Item 29 asks which item could come from a CASE tool. Know the four symbols by sight, remember that the DFD is the transformation model, and remember that CASE tools produce diagrams, dictionaries and reports, not decisions.

        Specimen Unit 2 Paper 02 (2021), Question 3(b). This part asks for a level 1 DFD from a written scenario. Use the six-step method from Part 4: entities, stores, processes, flows, rules, balance. Marks are typically spread across correct symbols, correct processes, labelled flows and correct stores, so a tidy diagram with every flow labelled is worth more than an elaborate one with gaps. Practise on your own scenarios, not on the specimen’s.

        Previous: Unit 2 • Module 2 • Lesson 03 – Feasibility Studies and Requirements Analysis. Next: Unit 2 • Module 2 • Lesson 05 – Software Design: Architecture, Structure Charts and Design Strategies.

        Syllabus link: CAPE Computer Science (CXC A19/U2/21), Software Engineering (Unit 2, Module 2). Specific Objective 4 (second part): tools and techniques of the analysis phase, including data flow models (DFDs) with symbols for data stores, processes, data flows and external entities; data dictionaries; and CASE tools.

        Video search terms

        Search YouTube for: "data flow diagram level 0 level 1 tutorial", "DFD rules black hole miracle", "data dictionary systems analysis", "CASE tools upper lower".

        Try it 5Quick quiz

        Tap an answer. All eight questions are self-checks on this lesson.

        Updates

        2026/12/01

        - First version of the lesson.

        © 2026 islandclass.org

        Feasibility Studies and Requirements Analysis

        UNIT 2 • MODULE 2 • LESSON 03

        The Chaguanas Community Library lends about 600 books a week using index cards and a big ledger. Members complain that they cannot check whether a book is in. Staff spend Friday afternoons chasing overdue loans by phone. The library committee asks a small software company to “build us a system”. Before anyone writes a line of code, two questions must be answered: Should we build it at all? and Exactly what must it do? Those questions belong to the analysis phase, and this lesson shows how professionals answer them.

        In Unit 1 you defined a problem and wrote an algorithm for it (Unit 1 • Module 2 • Lesson 03 – The Stages of the Problem-Solving Process). Here the scale is larger: you are specifying a whole system for an organisation, with many users and many tasks. The ideas are related, but the tools and deliverables are more formal.

        What you will learn

        • The activities of the requirements and specification process.
        • What a feasibility study is, the main types of feasibility, and what goes into a feasibility report.
        • Fact-finding techniques: interviews, questionnaires, observation, review of internal documents and prototyping, with strengths and weaknesses of each.
        • The difference between functional and non-functional requirements.
        • The requirements specification as the main deliverable of analysis.

        Part 1: The requirements and specification process

        The analysis phase is often called requirements engineering. It usually has four activities, which overlap and repeat:

        ActivityQuestion it answersOutput
        Feasibility studyIs the proposed system worth building, and can it be built?Feasibility report with a recommendation
        Requirements elicitation and analysisWhat do the users and the organisation need?Notes, models (such as data flow diagrams), prototypes
        Requirements specificationHow do we write those needs down precisely?Requirements specification document
        Requirements validationAre the written requirements correct, complete and consistent?Reviewed and agreed specification

        The order matters: there is no point spending weeks gathering detailed requirements for a system the organisation cannot afford. So the feasibility study usually comes first, and its recommendation decides whether the rest of the project goes ahead.

        Part 2: The feasibility study

        A feasibility study is a short, focused investigation that decides whether a proposed system is practical and worthwhile. It looks at the current situation, the problems, some possible solutions, and the costs and benefits of each. It should be quick and cheap compared with the full project, because its job is to prevent money being wasted.

        Types of feasibility

        A helpful way to remember the main considerations is the word TELOS:

        TypeKey questionLibrary example
        TechnicalDo the hardware, software and skills exist to build and run it?Can the library’s old computer run the system, and is there internet at the branch?
        Economic (cost-benefit)Do the benefits outweigh the costs? Is it cost-effective?Development and hardware cost about $40,000; staff save 6 hours a week and fewer books go missing.
        LegalDoes it comply with laws, contracts and licences?Members’ names, addresses and phone numbers are personal data and must be protected.
        OperationalWill it work in the organisation? Will people use it?Are staff willing to change from cards, and is training available?
        ScheduleCan it be delivered in the time available?Can it be ready before the new school term, when borrowing peaks?

        Economic feasibility deserves extra care because examiners often ask about cost-effectiveness. Costs include development, hardware, software licences, training, data conversion (typing the old card records into the new system) and running costs such as maintenance and support. Benefits may be tangible (measurable, such as staff hours saved or fewer lost books) or intangible (harder to measure, such as happier members or a better public image). A system is cost-effective when its benefits over its useful life outweigh its total costs.

        The feasibility report

        The deliverable of this stage is a feasibility report for management. A typical report contains:

        • An outline of the current system and its problems.
        • The aims of the proposed system.
        • Two or three alternative solutions (for example: improve the manual system, buy a ready-made package, or build a custom system).
        • Findings on technical, economic, legal, operational and schedule feasibility for each option.
        • A clear recommendation: go ahead with a named option, or stop.

        Try it 1Which feasibility type?

        Each concern comes from the library project. Choose the type of feasibility it belongs to.

        Worked example: critiquing a weak feasibility sketch

        A junior analyst hands the library committee this one-paragraph “feasibility study”:

        Feasibility: YES.
        Computers are cheap now.
        Everyone uses phones.
        We should build an app
        and a website. It will
        be ready soon and save
        lots of money.

        The committee should not accept it. Here is a structured critique, heading by heading:

        HeadingProblem in the sketchWhat a proper study would say
        Technical“Computers are cheap” says nothing about the library’s actual equipment or internet.Lists current hardware, connection speed, and staff skills, and what must be bought.
        Economic“Save lots of money” has no figures.Estimates development, hardware, training and running costs, and values the hours saved and books recovered.
        LegalNot mentioned at all.Notes that member data is personal data and must be protected; checks licence terms.
        Operational“Everyone uses phones” ignores staff attitudes and older members.Reports staff views and training needs; considers members without smartphones.
        Schedule“Ready soon” is not a date.Gives a realistic timeline against the September deadline.
        AlternativesOnly one option (app plus website).Compares at least two or three options, such as a ready-made package.
        Recommendation“YES” with no reasons.Recommends a named option and explains why it is best.

        The lesson here is that feasibility is evidence-based. Every heading needs facts or estimates about this organisation, and the recommendation must follow from them. In an exam, the same habit earns marks: apply each consideration to the scenario you are given rather than writing a general list.

        Part 3: Gathering requirements (fact-finding)

        Once the project is approved, the analyst must find out in detail how the current system works and what the new one must do. No single technique is enough; good analysts combine several.

        TechniqueHow it worksStrengthsWeaknesses
        InterviewsFace-to-face questions with key users or managers.Rich detail; can follow up on answers; builds trust.Time-consuming; few people reached; answers may be biased.
        QuestionnairesWritten questions given to many people.Reach many people cheaply; can be anonymous; easy to total.Low return rate; no follow-up; badly worded questions give poor data.
        ObservationWatch users doing their real work.Shows what really happens, not what people say happens.People may act differently when watched; slow; may miss rare events.
        Review of internal documentsStudy forms, reports, manuals and records already in use.Shows real data items and volumes; cheap; no disruption.Documents may be out of date or incomplete.
        PrototypingBuild quick sample screens for users to try.Users react to something concrete; finds missed requirements early.Users may expect the prototype to be the finished system; takes effort to build.

        Library example. The analyst interviews the head librarian about goals and problems. She gives a short questionnaire to 150 members about what they want online. She spends a Saturday morning observing the front desk to see how loans and returns really happen. She reviews the index cards, the overdue letters and the monthly report to the committee to list every data item. Finally she shows a paper prototype of a “search the catalogue” screen to five members.

        Try it 2Choose a fact-finding technique

        Pick the most suitable technique for each situation.

        Part 4: Functional and non-functional requirements

        Requirements are usually divided into two kinds. Learn the difference carefully; it appears regularly in exam questions.

        Functional requirementsNon-functional requirements
        MeaningWhat the system must do: its services, functions and behaviour.How well the system must perform, or limits it must work within: qualities and constraints.
        Typical wording“The system shall record a loan with member ID, book ID and due date.”“A catalogue search shall return results within 2 seconds.”
        ExamplesSearch the catalogue; record loans and returns; print an overdue list; send an email reminder.Response time; availability (open 7 days); security (staff login); usability (new staff learn it in one hour); must run on existing PCs; must comply with data protection law.

        A quick test: if you can imagine a button, menu option or report for it, it is probably functional. If it describes speed, reliability, security, ease of use, hardware or legal limits, it is non-functional. Non-functional requirements link directly to the attributes of well-engineered software from Lesson 01.

        Good requirements are also measurable and testable. “The system should be fast” cannot be tested. “Search results shall appear within 2 seconds for 95% of searches” can. When you write requirements, add numbers wherever you can.

        Try it 3Requirements drill

        “F or NF” asks you to classify a requirement. “Analysis” checks other ideas from the lesson.

        Part 5: The requirements specification

        The analysis phase ends with a requirements specification (sometimes called a software requirements specification). It is the agreed statement of what the system must do and the constraints on it. Designers, programmers and testers all work from it, and the client signs it as a record of what was agreed. A typical structure is:

        1. Introduction: purpose, scope, and definitions of terms.
        2. Description of the current system and its problems (from the feasibility report).
        3. Functional specification: each function the system shall provide, numbered so it can be referred to later.
        4. Non-functional specification: performance, security, usability, hardware and legal constraints, with measurable targets.
        5. Models of the system, such as data flow diagrams and a data dictionary (Lesson 04).
        6. Any assumptions, priorities and items left for a later version.

        A good specification is complete (nothing important missing), consistent (no requirement contradicts another), unambiguous (each statement has one meaning) and testable. Testers in Lesson 08 will write a test for every numbered requirement, so vague wording now causes problems later.

        Worked example: three library requirements

        IDRequirementType
        F1The system shall let staff record a loan by scanning the member card and the book barcode.Functional
        F2The system shall produce a list of loans more than 7 days overdue, sorted by member surname.Functional
        F3The system shall let members search the catalogue by title, author or subject.Functional
        N1A catalogue search shall return results within 2 seconds.Non-functional (performance)
        N2Member records shall be visible only to logged-in staff.Non-functional (security)
        N3The system shall run on the two existing desktop computers at the front desk.Non-functional (hardware constraint)

        Each requirement is numbered, says "shall", and could be tested. Compare a weak version of N1: "The search should be quick." Nobody could say whether that has been met.

        Common mistakes

        • Treating a feasibility study as a full analysis. It is short and decides whether to continue.
        • Writing "cost" as the only feasibility factor. Cover technical, economic, legal, operational and schedule where relevant.
        • Calling security or speed a functional requirement. They describe how well the system works, so they are non-functional.
        • Naming a technique without matching it to the situation. Explain why it suits: "a questionnaire, because there are 1,200 students".
        • Writing untestable requirements such as "user-friendly". Add a measurable target.

        Summary

        IdeaKey point
        Analysis phaseFeasibility, elicitation and analysis, specification, validation.
        FeasibilityTechnical, economic, legal, operational, schedule; ends in a feasibility report with a recommendation.
        Fact-findingInterviews, questionnaires, observation, document review, prototyping; combine them.
        FunctionalWhat the system does.
        Non-functionalHow well it does it, and constraints.
        DeliverableRequirements specification: functional plus non-functional, numbered and testable.

        Review questions

        1. What is the purpose of a feasibility study?

        Show answer

        To decide, quickly and cheaply, whether a proposed system is practical and worthwhile, so that money is not wasted on a project that should not go ahead.

        2. Name and briefly explain FOUR considerations in a feasibility study.

        Show answer

        Any four: technical (is the technology and expertise available?); economic (do benefits outweigh costs?); legal (does it comply with laws and licences?); operational (will it work in the organisation and will people use it?); schedule (can it be delivered in time?).

        3. How would an analyst judge whether a proposed system is cost-effective?

        Show answer

        List all costs (development, hardware, licences, training, data conversion, running costs) and all benefits (tangible, such as time saved; intangible, such as better service) over the system’s life. It is cost-effective if benefits outweigh costs.

        4. Compare interviews and questionnaires as fact-finding techniques.

        Show answer

        Interviews give rich detail and allow follow-up but are slow and reach few people. Questionnaires reach many people cheaply and can be anonymous, but there is no follow-up and return rates may be low.

        5. Why might an analyst use observation as well as interviews?

        Show answer

        People may describe the official process rather than what really happens. Observation shows actual practice, including shortcuts and problems they did not mention.

        6. Define functional and non-functional requirements and give one example of each for a school canteen ordering app.

        Show answer

        Functional: what the system does, for example "students shall order a meal before 10 a.m.". Non-functional: qualities or constraints, for example "the app shall load the menu within 3 seconds on a phone".

        7. List THREE items found in a requirements specification.

        Show answer

        Any three: introduction and scope; functional specification; non-functional specification; system models such as DFDs; data dictionary; assumptions and priorities.

        8. Rewrite "The system must be secure" as a testable requirement.

        Show answer

        For example: "Only users with a valid staff username and password shall be able to view or edit member records; three failed logins shall lock the account for 15 minutes."

        Homework

        1. Choose an organisation you know (a church group, sports club or family business). Write a half-page feasibility summary for a simple computer system, covering all five TELOS headings.
        2. Design a five-question questionnaire for that system. Make at least two questions closed (tick a box) and one open.
        3. Write five functional and three non-functional requirements for it. Number them and make each one testable.
        4. Explain which two fact-finding techniques you would combine for this organisation, and why.

        Mastery quiz: Feasibility and requirements

        This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

        Mastery quiz: Feasibility Studies and Requirements Analysis

        Your course badges: loading saved progress…

        View badges

          No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

          Saved in this browser on this device. Clearing browser data may remove your badges.

          Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

          1. The main purpose of a feasibility study is to
          2. Whether the organisation has the hardware and skills to run the system is
          3. Weighing development and running costs against benefits checks whether the system is
          4. Which is a non-functional requirement?
          5. Which is a functional requirement?
          6. Which technique best reaches 800 customers cheaply?
          7. A weakness of observation is that
          8. Studying existing forms and reports to list data items is
          9. The main deliverable of the analysis phase is the
          10. A good requirement should be

          Exam tips

          Specimen Unit 2 Paper 01 (2021), Items 23 to 25. Item 23 asks you to recognise a non-functional requirement among options; Items 24 and 25 test the order and purpose of the requirements process and which part judges cost-effectiveness. Use the "button or quality?" test for requirements, and remember that the economic part of the feasibility study is where cost-effectiveness is judged.

          Specimen Unit 2 Paper 02 (2021), Question 4(a). This part asks for important considerations in a feasibility study. Name each consideration (technical, economic, legal, operational, schedule) and add a sentence applying it to the scenario in the question. A named heading with a scenario-specific sentence earns more than a bare list.

          Previous: Unit 2 • Module 2 • Lesson 02 – Software Process Models: Waterfall, Evolutionary, Reuse-Oriented and Agile. Next: Unit 2 • Module 2 • Lesson 04 – Data Flow Diagrams, Data Dictionaries and CASE Tools.

          Syllabus link: CAPE Computer Science (CXC A19/U2/21), Software Engineering (Unit 2, Module 2). Specific Objective 4 (first part): the requirements and specification process, including the feasibility study and requirements analysis; fact-finding tools and techniques (interviews, questionnaires, observation, review of internal documents, prototyping); deliverables (feasibility report; functional and non-functional specification).

          Video search terms

          Search YouTube for: "feasibility study TELOS explained", "functional vs non-functional requirements", "requirements gathering techniques interview questionnaire observation", "software requirements specification example".

          Try it 4Quick quiz

          Tap an answer. All eight questions are self-checks on this lesson.

          Updates

          2026/12/01

          - First version of the lesson.

          © 2026 islandclass.org

          Software Process Models: Waterfall, Evolutionary, Reuse-Oriented and Agile

          UNIT 2 • MODULE 2 • LESSON 02

          Two teams are asked to build an app for a Caribbean ferry company. The first team spends three months writing a detailed specification, gets the company to sign it, then designs, codes and tests in strict order. The second team builds a rough working screen in two weeks, shows it to ticket staff, changes it, shows it again, and keeps going in short cycles. Both teams are doing software engineering. They are simply following different software process models.

          In Lesson 01 you saw why software needs a structured process. This lesson looks at the main ways that process can be organised, and at when each one is the right choice.

          What you will learn

          • The phases of the Software Development Life Cycle (SDLC).
          • What a generic software process model is.
          • The waterfall model, with its strengths and weaknesses.
          • Evolutionary development, including exploratory development and throwaway (rapid) prototyping.
          • Reuse-oriented (component-based) development.
          • Agile development, with short iterations and close customer contact.
          • How to choose and justify a model for a given situation.

          Part 1: The Software Development Life Cycle

          The Software Development Life Cycle (SDLC) is the series of phases a software product passes through, from the first idea until it is finally retired. Almost every model uses the same four core activities, even if the names change:

          PhaseWhat happensMain deliverable
          Analysis (specification)Study whether the system is worth building and find out exactly what it must do.Requirements specification, including a feasibility report
          DesignDecide how the system will be organised: sub-systems, modules, data and interfaces.Design specification and system architecture
          ImplementationWrite the program code from the design and test each unit.Source code and unit test results
          Validation (testing)Check the system meets its specification and satisfies users.Test plans, test reports, signed acceptance
          Evolution (maintenance)Change the system after release to fix faults, adapt to new environments and add features.Updated system, change log, updated documentation

          A software process model is a simplified description of how these activities are arranged in time. Some models do each phase once, in order. Others repeat the phases many times in small loops. A model is a framework, not a recipe: real projects often adapt or combine models.

          Notice what is not a life-cycle phase. Prototyping, interviewing and drawing data flow diagrams are techniques used within phases; they are not phases themselves. Keep that distinction clear, because a common exam trap is to mix a technique in with a list of phases.

          Part 2: The waterfall model

          RequirementsDesignImplementationTestingMaintenance
          The waterfall model. Each phase is finished and signed off before the next begins, so the work flows one way, like water down steps.

          The waterfall model is the classic plan-driven model. Each phase is completed, documented and signed off before the next begins. Work flows downward from requirements to maintenance, like water over a series of steps. In practice teams sometimes go back up a step to fix a problem, but going back is expensive and discouraged.

          StrengthsWeaknesses
          Simple to understand and to manage: each phase has a clear start, end and deliverable.Requirements must be fixed early. If users change their minds, going back is costly.
          Strong documentation at every phase, which helps maintenance and audits.Users see a working system only near the end, so misunderstandings are discovered late.
          Progress is visible: managers can check which phase is complete.Testing comes late, so serious design faults may be found when they are most expensive to fix.
          Works well when requirements are clear and stable, such as safety-critical or contract-based systems.Poor fit for projects where requirements are uncertain or change quickly.

          Example where it fits: a government department replacing a well-understood payroll calculation, where the rules are set by law and change rarely. Contracts, budgets and approvals all depend on a fixed specification signed at the start.

          Part 3: Evolutionary development

          Outline ideaBuild versionUsers try itfeedbackFinal systemwhen users are happy
          Evolutionary development. Versions are built, tried by users, and improved in a loop until the system is good enough.

          In evolutionary development, the team builds an early version quickly, shows it to users, and improves it based on their feedback. Specification, development and validation happen together, in a loop, rather than one after another. There are two main forms.

          Exploratory development

          The team works with the customer, starting with the parts of the system that are best understood. New features are added as users suggest them. The prototype evolves into the final system. This suits small systems where the customer cannot describe everything in advance.

          Throwaway (rapid) prototyping

          A prototype is a quick, partial model of a system, often just screens with little real processing behind them. In throwaway prototyping, the prototype is built only to discover and confirm requirements. Once users agree what they want, the prototype is discarded and the real system is built properly, often using a more structured process. Rapid prototyping stresses speed: the prototype is made in days, not months, so feedback arrives early.

          Strengths of evolutionary developmentWeaknesses of evolutionary development
          Users see something working early and can say what they really want.The process is less visible: it is hard for managers to measure progress when versions change constantly.
          Requirements can change as understanding grows.Frequent change can leave the system poorly structured and harder to maintain.
          Users feel involved, so the final system is more likely to be accepted.Producing full documentation for every version is not cost-effective, so documentation often lags.
          Misunderstandings are caught early, when they are cheap to fix.Users may think the prototype is nearly finished, raising unrealistic expectations about delivery.

          Example where it fits: a small business wants an online ordering page but is unsure what customers will find easiest. A prototype lets the owner and a few customers try different layouts before money is spent on the full build.

          Part 4: Reuse-oriented development

          In reuse-oriented (component-based) development, the team builds as much of the system as possible from existing components: libraries, frameworks, commercial packages or modules from earlier projects. The process looks like this:

          1. Specify requirements.
          2. Analyse which existing components could meet them.
          3. Modify the requirements where a component almost fits, to avoid building from scratch.
          4. Design the system around the chosen components.
          5. Develop any missing parts and integrate everything.
          6. Validate the whole system.
          StrengthsWeaknesses
          Less code to write, so cost and development time fall.Requirements may have to be compromised to fit available components, so the system may not match users’ needs exactly.
          Reused components have often been well tested already, which can improve reliability.The team depends on outside suppliers; if a component is changed or abandoned, the system is affected.
          Faster delivery.Control over how components evolve is lost, and licences may restrict use.

          You already use reuse every time you call printf or strlen from the C standard library instead of writing those functions yourself. Reuse-oriented development applies the same idea to whole sub-systems, such as using an existing payment service in an online shop.

          Part 5: Agile development

          Agile methods grew from frustration with heavy, document-driven processes. They deliver working software in short iterations (often one to four weeks). Each iteration produces a small, tested, usable increment. Agile methods value:

          • Individuals and conversation over heavy process and tools.
          • Working software over long documents.
          • Close collaboration with the customer, who is often part of the team.
          • Responding to change instead of rigidly following a plan.

          A typical agile team keeps a prioritised list of features (often written as short user stories), picks the most valuable ones for the next iteration, builds and tests them, shows them to the customer, and then plans the next iteration. Many agile teams write automated tests alongside the code and meet briefly every day.

          StrengthsWeaknesses
          Copes well with changing requirements.Needs a customer who is available and committed throughout.
          Delivers useful features early and often.Light documentation can make long-term maintenance harder, especially when team members change.
          Constant feedback keeps the product close to what users want.Harder to fix a total price and deadline in a contract at the start.
          Small teams communicate quickly.Scales poorly to very large or safety-critical projects that need detailed specifications.

          Part 6: Comparing and choosing a model

          SituationGood choiceWhy
          Requirements clear, stable and fixed by contractWaterfallPlan-driven phases and sign-offs fit a fixed specification.
          Users unsure what they want; interface matters a lotEvolutionary or prototypingEarly versions draw out the real requirements.
          Suitable components or packages already existReuse-orientedSaves time and cost by building from tested parts.
          Small team, engaged customer, requirements change oftenAgileShort iterations respond quickly to change.
          Safety-critical system needing full documentationWaterfall (plan-driven)Every phase must be documented and checked.

          Real projects often mix models. A team might build a throwaway prototype to settle requirements, then use a plan-driven process for the core system, and reuse an existing login component. In an exam, always justify your choice with a feature of the scenario.

          Side by side: waterfall vs evolutionary development

          FeatureWaterfallEvolutionary
          When requirements are fixedAt the start, before designGradually, as versions are tried
          When users see working softwareNear the endWithin days or weeks
          Visibility to managersHigh: signed-off documents per phaseLower: frequent versions are hard to measure
          Handling changeExpensive; may mean going back several phasesExpected and built into the loop
          DocumentationFull at every phaseOften lighter and later
          Structure of the final codePlanned up front, usually cleanCan decay unless the team refactors
          Typical useLarge, stable or safety-critical systemsSmall or medium systems with unclear needs

          Worked example: justifying a model

          Scenario. A dental clinic in San Fernando wants an appointment system. The receptionist has used paper for twenty years and is not sure what the screens should look like. The clinic owner wants the system working in three months and has a modest budget.

          Step 1: pick out the key facts. The users are unsure what they need (the receptionist cannot describe the screens). The system is small. Time is short.

          Step 2: match facts to a model. Unclear requirements point to evolutionary development or a throwaway prototype. A short deadline and a small system point away from a heavy plan-driven process.

          Step 3: write the justification. “I recommend evolutionary development. The receptionist is unsure what the screens should contain, so building an early version she can try will reveal her real requirements. The system is small, so the risk of poor structure from repeated change is manageable, and early versions can be in use well within three months.”

          Step 4: show balance (for higher marks). “A weakness is that the owner may find progress hard to measure, so the team should agree short review meetings after each version.” Naming a weakness and how to manage it shows you understand the trade-off, not just the label.

          Notice the pattern: scenario fact, then model, then effect. The same pattern works for any “choose and justify” question in this module.

          Try it 1Pick the process model

          For each project, choose the model that fits best.

          Try it 2Whose strength or weakness?

          Each statement is a strength or weakness of one model. Choose the model.

          Try it 3Process models drill

          “Phases” checks the life cycle. “Models” checks which model is described.

          Common mistakes

          • Listing prototyping as a life-cycle phase. It is a technique used during analysis or design.
          • Saying waterfall "has no testing". It does; testing simply comes late, after implementation.
          • Confusing throwaway prototyping with exploratory development. A throwaway prototype is discarded; an exploratory version grows into the final system.
          • Giving an advantage or disadvantage without explaining it. Write the effect, for example: "users see a working version early, so misunderstandings are found while they are cheap to fix."
          • Choosing a model without linking it to the scenario. Quote a detail from the question as your reason.

          Summary

          ModelKey ideaBest when
          WaterfallPhases in strict order, each signed offRequirements are clear and stable
          EvolutionaryBuild, get feedback, improve, repeatRequirements are unclear
          Throwaway prototypingQuick model to learn requirements, then discardUser interface or needs are uncertain
          Reuse-orientedBuild from existing componentsGood components already exist
          AgileShort iterations, close customer, working codeChange is frequent, team small

          Review questions

          1. List the main phases of the software development life cycle in order.

          Show answer

          Analysis (requirements and specification), design, implementation, validation (testing) and evolution (maintenance).

          2. Describe the waterfall model and give one strength and one weakness.

          Show answer

          Each phase is completed and signed off before the next begins. Strength: clear phases and documentation make progress visible and the process easy to manage. Weakness: requirements are fixed early, so later changes are expensive and users see a working system only near the end.

          3. Give an advantage and a disadvantage of evolutionary development, explaining each.

          Show answer

          Advantage: users see an early version and can say what they really need, so the final system fits them better. Disadvantage: constant change makes progress hard to measure and can leave the system poorly structured and documented.

          4. Distinguish between throwaway prototyping and exploratory development.

          Show answer

          In throwaway prototyping the prototype is built only to clarify requirements and is then discarded. In exploratory development an early version is kept and extended into the final system.

          5. Give two reasons a team might choose reuse-oriented development, and one risk.

          Show answer

          Reasons: less code to write, so lower cost and faster delivery; reused components are often already tested. Risk: requirements may need to be compromised, or the team depends on outside suppliers.

          6. Why is agile unsuitable for some safety-critical systems?

          Show answer

          Safety-critical systems need detailed specifications, full documentation and careful checking at each stage. Agile keeps documentation light and expects requirements to change, which conflicts with those needs.

          7. A local credit union wants to replace its loans system. The rules are fixed, and the board wants a fixed price. Which model would you recommend? Justify your answer.

          Show answer

          Waterfall (plan-driven): the requirements are clear and stable, and a fixed price needs a signed specification at the start.

          Homework

          1. Draw the waterfall model and the evolutionary loop from memory and label each part.
          2. Write two scenarios of your own: one where waterfall is clearly best and one where agile is clearly best. Justify each.
          3. Make a paper prototype (sketches of three screens) for a school canteen ordering app. Show it to two people and record what they would change.
          4. List three components that a developer of an online shop could reuse instead of writing from scratch.
          5. Write a short paragraph comparing waterfall and evolutionary development under the headings visibility, user involvement and handling change.

          Mastery quiz: Software process models

          This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

          Mastery quiz: Software Process Models: Waterfall, Evolutionary, Reuse-Oriented and Agile

          Your course badges: loading saved progress…

          View badges

            No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

            Saved in this browser on this device. Clearing browser data may remove your badges.

            Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

            1. Which is NOT a phase of the software development life cycle?
            2. In the waterfall model, each phase
            3. A main weakness of the waterfall model is that
            4. A key advantage of evolutionary development is
            5. A prototype built only to discover requirements and then discarded is
            6. Building an online shop mostly from an existing cart and payment package is
            7. Which model delivers working increments in short iterations with close customer contact?
            8. A risk of reuse-oriented development is that
            9. Which situation best suits waterfall?
            10. Why can evolutionary development produce poorly structured systems?

            Exam tips

            Specimen Unit 2 Paper 01 (2021), Items 21 and 22. Item 21 describes one model by its main feature and asks you to name it; Item 22 gives a list of activities and asks which is not a life-cycle phase. Learn one defining feature per model, and remember that prototyping is a technique, not a phase.

            Specimen Unit 2 Paper 02 (2021), Question 3(a). You are asked for an advantage and a disadvantage of the evolutionary approach. Marks usually go to a point plus its effect. Use the strength and weakness tables in Part 3: one benefit to users (early feedback), one cost (less visibility or weaker structure), each with a "so that" or "because" clause.

            Previous: Unit 2 • Module 2 • Lesson 01 – Why a Structured Software Process, and What Well-Engineered Software Looks Like. Next: Unit 2 • Module 2 • Lesson 03 – Feasibility Studies and Requirements Analysis.

            Syllabus link: CAPE Computer Science (CXC A19/U2/21), Software Engineering (Unit 2, Module 2). Specific Objective 3: examine the strengths and weaknesses of different generic software process models (phases of the life cycle; waterfall; evolutionary development including rapid prototyping; reuse-oriented; agile).

            Video search terms

            Search YouTube for: "waterfall model explained", "evolutionary prototyping vs throwaway prototyping", "agile methodology for beginners", "component based software engineering".

            Try it 4Quick quiz

            Tap an answer. All eight questions are self-checks on this lesson.

            Updates

            2026/12/01

            - First version of the lesson.

            © 2026 islandclass.org

            Why a Structured Software Process, and What Well-Engineered Software Looks Like

            UNIT 2 • MODULE 2 • LESSON 01

            Think about the software you rely on in a single school day. A bank app shows your parent the balance before a payment. The school uses a system to record attendance and print report cards. A taxi or delivery app tracks drivers across town. Hospitals, airports, the electricity company and government offices all run on software. If any of these systems is late, full of faults, or hard to change, real people pay the price.

            In Unit 1 you learned to solve a problem by writing an algorithm and turning it into a C program. That works well for a program one person writes in a week. This module asks a bigger question: how do teams build large software products that many people depend on, for years, without the project collapsing? The answer is software engineering: a disciplined, structured approach to specifying, designing, building, testing and maintaining software.

            What you will learn

            • Why organisations need a structured approach to developing software, and what goes wrong without one.
            • Why standard interfaces, management control, visibility of progress and risk management matter.
            • Why end users and management must be involved throughout a project.
            • A simple Gantt chart for planning and tracking a project.
            • The attributes of well-engineered software: maintainability, dependability, efficiency, usability, portability and appropriate documentation.
            • The difference between system documentation and user documentation.
            • How the same C program can be written in a hard-to-maintain way or in a well-engineered way.

            Part 1: What is software engineering?

            Software engineering is the application of a systematic, disciplined and measurable approach to the development, operation and maintenance of software. The key word is systematic. Instead of jumping straight into code, a software engineering team works through recognised phases, produces documents that others can check, and manages time, money and risk as the project moves along.

            It helps to compare software with other engineering. Nobody builds a bridge across a river by sending workers to start pouring concrete on the first morning. Engineers first study the site, agree what the bridge must carry, draw designs, check the designs, build in stages, inspect the work, and then maintain the bridge for decades. Software is invisible, so it is tempting to skip these steps. Experience has shown that skipping them is exactly what makes large projects fail.

            Throughout this module you will meet the phases that a structured process uses. Different textbooks name them slightly differently, but the core ideas are the same:

            PhaseMain questionLesson in this module
            Analysis (requirements)What must the system do, and is it worth building?Lessons 03 and 04
            DesignHow will the system be organised to meet the requirements?Lessons 05 and 06
            ImplementationHow do we turn the design into working code?Lesson 07
            Validation (testing)Does the system do what was specified, and does it satisfy users?Lesson 08
            Evolution (maintenance)How do we keep the system useful as needs change?Lesson 09

            Lesson 02 looks at different process models, which arrange these phases in different ways. Lesson 10 steps back to examine wider issues such as privacy, security and intellectual property.

            Part 2: Why a structured approach is needed

            The syllabus groups the reasons for a structured software process under a handful of headings. Learn each one with its own short example, because exam questions often give you a situation and ask you to name or explain the reason that applies.

            1. Organisations depend on their computer systems

            Most organisations can no longer work without software. A supermarket cannot sell anything if its point-of-sale system is down. A credit union cannot process loans if its accounts system fails. When a business depends this heavily on a system, faults are expensive: lost sales, angry customers, legal trouble and damage to reputation. A structured process reduces the chance of serious faults reaching the live system and makes faults quicker to find and fix when they do appear.

            2. Lessons from troubled projects

            From the 1960s onwards, as programs grew larger, many software projects ran badly. Writers at the time described a software crisis. Three problems kept recurring:

            • Rising cost. Projects went far over budget, and the cost of software overtook the cost of the hardware it ran on.
            • Dissatisfied users and managers. Finished systems often did not do what users needed, were hard to use, or arrived too late to be useful.
            • Growing length and complexity. Programs grew to hundreds of thousands, then millions, of lines. No single programmer could keep the whole system in their head.

            A structured approach responds to each problem. Careful requirements analysis checks that the system is what users actually need. Design breaks complexity into manageable modules. Planning and estimation keep costs visible from the start rather than discovered at the end.

            3. The need for standard interfaces

            Software rarely works alone. It must talk to people (the user interface) and to other software (for example a payroll system sending data to a bank, or an app reading data from a web service). If every programmer invents their own screens, file formats and data exchanges, users have to relearn each system and other systems cannot connect to it. A structured process agrees interfaces early and documents them, so that screens behave consistently and other programs know exactly what data to send and expect.

            4. Control, visibility and risk management

            Managers must be able to answer simple questions at any time: How far along are we? Are we on budget? What could go wrong? Code on a programmer’s laptop is invisible to a manager. A structured process creates visibility by producing deliverables at the end of each phase, such as a requirements specification or a test report, that can be reviewed and signed off. It gives control because the next phase does not start until the current one is checked. It supports risk management: identifying what could go wrong (a key programmer leaving, a supplier delivering late, a requirement turning out to be impossible) and planning how to reduce or respond to each risk.

            5. Involving end users and management

            The people who will use a system know things that programmers do not: how the work really happens, which screens they need, and which mistakes are common. Management decides budgets and priorities and must support the change the system brings. When users and managers are involved from the start, through interviews, reviews of prototypes and acceptance testing, the finished system is far more likely to be accepted and used. When they are left out, systems are often rejected even if they work technically.

            Try it 1Which reason for a structured process?

            Read each short project story. Choose the reason for a structured approach that it best illustrates.

            Part 3: Planning and tracking with a Gantt chart

            Control and visibility need a plan that everyone can see. A common planning tool is the Gantt chart, a bar chart in which each row is a task and each bar shows when the task starts and finishes. Time runs from left to right, usually in days or weeks.

            123456789101112FeasibilityRequirementsDesignCodingTestingHandoverGo-live (end of week 12)Task / week
            A simple Gantt chart for a 12-week project. Each bar shows when a task starts and ends; overlapping bars run at the same time.

            Read the chart above for a 12-week project to build a homework-tracking app for a school.

            • Each task has a start week and an end week. Coding runs from week 6 to week 9.
            • Some bars overlap. Testing begins in week 8 while coding is still finishing, because finished modules can be tested early.
            • Some tasks depend on others. Design cannot begin until enough requirements are known, so its bar starts after requirements are under way.
            • The final marker shows the planned go-live date. If coding slips by two weeks, the manager can see at once that testing and handover will slip too, unless something changes.

            A Gantt chart does not make a project succeed by itself, but it gives managers and users a shared picture of the timeline. During the project, the team can shade completed parts of each bar to compare progress against the plan. That is visibility and control in practice. Spreadsheet programs and project-management software can draw Gantt charts automatically from a list of tasks, start dates and durations.

            Try it 2Read the Gantt chart

            Use the Gantt chart above to answer each question.

            Part 4: Attributes of well-engineered software

            A structured process aims to produce a well-engineered software product. A program can produce correct output and still be poorly engineered: hard to change, slow, confusing or impossible to move to new hardware. The syllabus names six attributes. Learn a definition and an example for each.

            AttributeWhat it meansExample
            MaintainabilityThe software can be changed easily to fix faults, adapt to new conditions or add features, because it is clearly structured and documented.Tax rates are stored as named constants in one place, so a rate change needs one edit, not fifty.
            DependabilityUsers can trust it: it is reliable (works without failing), available when needed, safe, and secure against misuse.A hospital booking system runs all day without crashing and refuses unauthorised logins.
            EfficiencyIt does not waste resources such as processor time, memory, storage or network bandwidth.Searching a sorted list of 10,000 records with binary search instead of checking every record.
            UsabilityIntended users can learn and use it with reasonable effort, and the interface suits the task and the users.Clear labels, sensible defaults and helpful error messages on a school registration form.
            PortabilityIt can be moved to a different hardware platform or operating system with little change.A C program written to the standard, without system-specific calls, compiles on Windows, macOS and Linux.
            Appropriate documentationSuitable written material exists for those who maintain the system and those who use it.A technical manual for programmers and a step-by-step user guide for office staff.

            Some attributes pull against each other. Making software extremely efficient can make the code harder to read, which reduces maintainability. Adding strong security checks can make a system slightly harder to use. Good engineers make sensible trade-offs based on what matters most for each system. For an air-traffic system, dependability comes first. For a game, usability and efficiency matter a great deal.

            System documentation vs user documentation

            The documentation attribute has two audiences, and exam questions often ask you to tell them apart.

            System (technical) documentationUser documentation
            Written forProgrammers and analysts who maintain or extend the systemPeople who use the system day to day
            Typical contentsRequirements and design documents, data dictionary, structure charts, program listings with comments, test plans and resultsInstallation steps, how to carry out each task, screenshots, error messages and what to do, frequently asked questions, tutorials
            PurposeExplain how the system works inside, so it can be maintainedExplain how to use the system to get work done

            Try it 3Name the attribute

            Each description shows a strength or a weakness. Choose the attribute it is mainly about.

            Part 5: Seeing the difference in C

            Software engineering is not only about documents and diagrams. The same ideas show up in code. Here is a small program from a school that hires out laptops. Both versions print exactly the same output. Read the first one and imagine you have been asked to change the daily rate.

            Worked example 1: works, but hard to maintain

            #include <stdio.h>
            
            int main(void)
            {
                int d[4] = {3, 7, 12, 5};
                for (int i = 0; i < 4; i++) {
                    double t = d[i] * 45.0;
                    if (d[i] > 10) t = t * 0.9;
                    printf("%d %.2f\n", d[i], t);
                }
                return 0;
            }
            

            Output:

            3 135.00
            7 315.00
            12 486.00
            5 225.00

            The program is correct, yet a maintainer has to guess what 45.0, 10 and 0.9 mean. These are magic numbers: unexplained values written directly into the code. The variable names d and t say nothing. The calculation is buried inside the loop, so it cannot be reused or tested on its own.

            Worked example 2: the same job, well engineered

            #include <stdio.h>
            
            #define DAILY_RATE    45.00
            #define LONG_HIRE     10   /* days */
            #define LONG_DISCOUNT 0.10 /* 10% off */
            
            /* Cost of hiring one laptop for days. */
            double hireCost(int days)
            {
                double cost = days * DAILY_RATE;
                if (days > LONG_HIRE)
                    cost = cost * (1 - LONG_DISCOUNT);
                return cost;
            }
            
            int main(void)
            {
                int days[] = {3, 7, 12, 5};
                int n = 4;
                printf("Days  Cost ($)\n");
                for (int i = 0; i < n; i++)
                    printf("%4d  %8.2f\n", days[i],
                           hireCost(days[i]));
                return 0;
            }
            

            Output:

            Days  Cost ($)
               3    135.00
               7    315.00
              12    486.00
               5    225.00

            Compare the two. Named constants (DAILY_RATE, LONG_HIRE, LONG_DISCOUNT) put each business rule in one place with a comment. The calculation is in its own function, hireCost, with a comment saying what it does, so it can be tested separately and reused by other parts of a larger system. The output has headings, which helps usability. The code uses only standard C, which helps portability. None of this changes what the program computes. It changes how cheaply and safely the program can be looked after for years, and that is what maintainability means.

            You met these habits in Unit 1 • Module 3 • Lesson 10 – Testing, Debugging and Good Style in C. Software engineering explains why they matter: on a real system, most of the total cost comes after the first release, when people need to read and change the code.

            Try it 4Software engineering basics drill

            Pick a mode. “Reasons” asks why a structured process is needed. “Attributes” asks which quality of well-engineered software is involved.

            Common mistakes

            • Saying software engineering is "just programming". Programming is one activity inside a much larger process that includes analysis, design, testing and maintenance.
            • Listing an attribute without explaining it. In an exam, "maintainability" alone may earn little. Add a short meaning, such as "easy to change because the code is modular and documented".
            • Mixing up efficiency and dependability. Efficiency is about not wasting resources. Dependability is about trust: reliability, availability, safety and security.
            • Treating documentation as one thing. Name the audience: system documentation for maintainers, user documentation for users.
            • Thinking a Gantt chart shows how tasks are done. It shows when tasks happen and how long they take, not how to do them.

            Summary

            IdeaKey point
            Software engineeringA systematic, disciplined approach to developing, operating and maintaining software.
            Why a structured processDependence on systems; past troubled projects (cost, dissatisfaction, complexity); standard interfaces; control, visibility and risk management; user and management involvement.
            Gantt chartBars against a timeline showing when each task starts and ends; supports planning, visibility and control.
            Six attributesMaintainability, dependability, efficiency, usability, portability and appropriate documentation.
            Two kinds of documentationSystem documentation for maintainers; user documentation for users.

            Review questions

            1. Define software engineering in one or two sentences.

            Show answer

            Software engineering is a systematic, disciplined approach to specifying, designing, building, testing and maintaining software so that it is delivered on time and within budget and meets users’ needs.

            2. Give THREE reasons why organisations need a structured approach to software development.

            Show answer

            Any three, for example: organisations depend on their systems, so faults are costly; past projects suffered from rising costs, dissatisfied users and growing complexity; systems need standard interfaces to users and other software; managers need control, visibility of progress and risk management; users and management must be involved for the system to be accepted.

            3. Explain what is meant by "visibility of the process" and how a structured approach provides it.

            Show answer

            Visibility means managers and clients can see how far the project has progressed. A structured approach provides it by producing deliverables (such as a requirements specification, design documents and test reports) at the end of each phase that can be reviewed and signed off.

            4. Why should end users be involved in a software project?

            Show answer

            Users know how the work is really done and what they need. Involving them through interviews, prototype reviews and acceptance testing makes it more likely the system fits their needs and is accepted.

            5. State and explain FOUR attributes of well-engineered software.

            Show answer

            Any four, for example: maintainability (easy to change because it is clear and documented); dependability (reliable, available, safe and secure); efficiency (does not waste processor time, memory or other resources); usability (easy for its users to learn and use); portability (can be moved to another platform with little change); appropriate documentation (system and user documentation exist).

            6. Distinguish between system documentation and user documentation, giving an example of each.

            Show answer

            System documentation is for programmers and analysts and explains how the system works (for example a data dictionary or structure chart). User documentation is for people who use the system and explains how to carry out tasks (for example a user guide with screenshots).

            7. Using Worked example 2, explain TWO ways the program is more maintainable than Worked example 1.

            Show answer

            Named constants put each business rule in one labelled place, so a rate change is one edit; the calculation is in its own commented function hireCost, so it can be understood, tested and reused separately. Meaningful names also help.

            8. What does a Gantt chart show, and how does it help a project manager?

            Show answer

            It shows each task as a bar on a timeline from its start to its end. It helps the manager plan, see which tasks overlap or depend on each other, compare progress with the plan and spot delays early.

            Homework

            1. Interview someone who uses software at work (a shop, office, school or clinic). Ask what happens when the system fails, and write a short paragraph linking their answer to "dependence on computer systems".
            2. Draw a Gantt chart for a five-week school project of your choice with at least five tasks, including at least one overlap.
            3. For an app you use daily, give one example each of good usability and poor usability, and suggest an improvement.
            4. Rewrite a short C program you wrote in Unit 1 using named constants, meaningful names and at least one function with a comment. Explain how your changes improve maintainability.
            5. Write a half-page user guide for one task in that program, for someone who has never seen it.

            Mastery quiz: Structured process and well-engineered software

            This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

            Mastery quiz: Why a Structured Software Process, and What Well-Engineered Software Looks Like

            Your course badges: loading saved progress…

            View badges

              No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

              Saved in this browser on this device. Clearing browser data may remove your badges.

              Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

              1. Which statement best describes software engineering?
              2. A company cannot trade when its system is down. Which reason for a structured approach does this illustrate?
              3. Producing a reviewed document at the end of each phase mainly improves
              4. Planning in advance for a key programmer leaving is an example of
              5. Which is an attribute of well-engineered software named in the syllabus?
              6. Software that does not waste processor time or memory has the attribute of
              7. A program that can be moved to a new operating system with little change is
              8. Which item is system documentation?
              9. In a Gantt chart, two bars that cover the same week show tasks that
              10. In Worked example 2, why is DAILY_RATE written as a named constant?

              Exam tips

              Specimen Unit 2 Paper 01 (2021), Items 17 and 20. Both test the syllabus list of attributes of well-engineered software. One asks you to reject an option that is not on the list; the other describes a property and asks you to name it. Learn the six attributes by name, and attach a one-line meaning to each so that you can recognise a description as well as a label.

              For a written question asking for reasons for a structured approach, give the reason and a short consequence, for example: "Organisations depend on their systems, so a fault can stop the business; a structured process reduces faults." A bare list usually earns fewer marks than reasons with explanations.

              When asked to distinguish two types of documentation, use a comparison: who it is for, what it contains, and why it is needed.

              Previous: Unit 2 • Module 1 • Lesson 10 – Selection Sort vs Bubble Sort Compared. Next: Unit 2 • Module 2 • Lesson 02 – Software Process Models: Waterfall, Evolutionary, Reuse-Oriented and Agile.

              Syllabus link: CAPE Computer Science (CXC A19/U2/21), Software Engineering (Unit 2, Module 2). Specific Objectives 1 and 2: explain the reasons for a structured approach to the software development process; describe what makes a software product well engineered (maintainability, dependability, efficiency, usability, portability and appropriate system and user documentation).

              Video search terms

              Search YouTube for: "what is software engineering", "software crisis explained", "Gantt chart for beginners", "software quality attributes maintainability portability".

              Try it 5Quick quiz

              Tap an answer. All eight questions are self-checks on this lesson.

              Updates

              2026/12/01

              - First version of the lesson.

              © 2026 islandclass.org

              Selection Sort vs Bubble Sort Compared

              UNIT 2 • MODULE 1 • LESSON 10

              You now know two sorting algorithms. Both put a list in order. Both use two nested loops and a three-step swap. Both make about the same number of comparisons on a random list. So does it matter which one you use? It does, and knowing when each one is the better choice is exactly the kind of judgement CAPE examiners reward.

              In this lesson you will put selection sort and bubble sort side by side, count their comparisons and swaps on different kinds of data, race them in a Try it, and practise the “which would you choose, and why?” questions that turn up in Paper 02.

              What you will learn

              • How selection sort and bubble sort differ in what they compare, what they move and where the sorted part grows.
              • The number of comparisons and swaps each makes in the best, worst and typical cases.
              • How the kind of data (random, reversed, sorted, nearly sorted) changes the result.
              • How to choose the better sort for a given situation and justify your choice.
              • How to answer comparison questions clearly in an exam.

              Part 1: Side by side

              Here are the two algorithms next to each other. Read them line by line and spot the differences.

              Selection sort

              FOR i ← 0 TO n - 2
                  minIdx ← i
                  FOR j ← i + 1 TO n - 1
                      IF list[j] < list[minIdx] THEN
                          minIdx ← j
                      ENDIF
                  ENDFOR
                  IF minIdx ≠ i THEN
                      swap list[i], list[minIdx]
                  ENDIF
              ENDFOR

              Bubble sort (with flag)

              FOR pass ← 0 TO n - 2
                  swapped ← FALSE
                  FOR j ← 0 TO n - 2 - pass
                      IF list[j] > list[j + 1] THEN
                          swap list[j], list[j + 1]
                          swapped ← TRUE
                      ENDIF
                  ENDFOR
                  IF NOT swapped THEN EXIT
              ENDFOR
              FeatureSelection sortBubble sort
              Main ideaSelect the smallest, swap it into placeSwap neighbours that are out of order
              ComparesEach item with the smallest so farEach item with its right neighbour
              Swaps per passAt most 1Up to the length of the unsorted part
              Sorted part grows fromThe left (smallest first)The right (largest first)
              Can stop early?NoYes, with a swapped flag
              Stable?NoYes (equal values never swap)

              The key difference is where the work goes. Selection sort spends its effort searching, then makes one decisive swap per pass. Bubble sort mixes searching and moving together: every out-of-order pair it meets is swapped on the spot. That single difference explains almost every result in this lesson.

              Bubble sort is stable because it only swaps when the left value is strictly greater, so two equal values never change places. Selection sort’s long-distance swap can jump one value over an equal one. If you sort students by form after sorting them by name, a stable sort keeps the names in order within each form.

              Part 2: Counting the work

              Measure (n items)Selection sortBubble sort (with flag)
              Comparisons, best casen(n – 1) / 2n – 1 (already sorted)
              Comparisons, worst casen(n – 1) / 2n(n – 1) / 2
              Swaps, best case00
              Swaps, worst casen – 1n(n – 1) / 2 (reversed)
              PassesAlways n – 11 to n – 1

              Put numbers in for a class of n = 40 students. Selection sort always makes 780 comparisons and at most 39 swaps. Bubble sort with a flag makes anywhere from 39 comparisons (if the list is already sorted) to 780 comparisons and 780 swaps (if it is in reverse order). On random data, bubble sort typically makes about half the maximum number of swaps, around 390, ten times as many as selection sort.

              So neither sort is “faster” in every situation. Selection sort is predictable and swap-light. Bubble sort is data-sensitive: brilliant on nearly sorted data, poor on reversed data.

              Part 3: The race

              Race the two sorts on the same 8 numbers. Before each race, predict which one will make fewer swaps, then step through or race to the end and compare the counters. Your results build up underneath so you can compare data sets.

              Try it 1Sort race: selection vs bubble

              Choose the data, make your prediction, then step both sorts together. Try every data set, then turn early exit off and race again.

              Choose data

              Selection sort

              Bubble sort

              Your race results

              Look at your results list. You should see four patterns: on random data the comparisons are close but bubble sort makes far more swaps; on reversed data bubble sort swaps on every comparison; on already sorted data bubble sort with early exit wins easily; and on nearly sorted data bubble sort still wins on comparisons while both make the same tiny number of swaps. Turn early exit off and bubble sort loses its advantage on sorted data, because it then makes all its comparisons too.

              Part 4: Measuring in C

              This program runs both sorts on copies of the same four data sets and prints the comparisons and swaps for each, as a small table (c/s means comparisons/swaps).

              #include <stdio.h>
              
              #define N 8
              
              void selection(int a[], int n,
                             int *comps, int *swaps)
              {
                  int i, j, m, t;
                  *comps = *swaps = 0;
                  for (i = 0; i < n - 1; i++) {
                      m = i;
                      for (j = i + 1; j < n; j++) {
                          (*comps)++;
                          if (a[j] < a[m])
                              m = j;
                      }
                      if (m != i) {
                          t = a[i]; a[i] = a[m]; a[m] = t;
                          (*swaps)++;
                      }
                  }
              }
              
              void bubble(int a[], int n,
                          int *comps, int *swaps)
              {
                  int p, j, t, swapped = 1;
                  *comps = *swaps = 0;
                  for (p = 0; p < n - 1 && swapped; p++) {
                      swapped = 0;
                      for (j = 0; j < n - 1 - p; j++) {
                          (*comps)++;
                          if (a[j] > a[j + 1]) {
                              t = a[j];
                              a[j] = a[j + 1];
                              a[j + 1] = t;
                              (*swaps)++;
                              swapped = 1;
                          }
                      }
                  }
              }
              
              int main(void)
              {
                  const char *name[4] = {"Random",
                      "Reversed", "Sorted", "Nearly"};
                  int data[4][N] = {
                      {42, 17, 88, 5, 63, 29, 71, 36},
                      {80, 70, 60, 50, 40, 30, 20, 10},
                      {10, 20, 30, 40, 50, 60, 70, 80},
                      {10, 20, 30, 40, 60, 50, 70, 80}};
                  int s[N], b[N], k, i, sc, ss, bc, bs;
              
                  printf("Data      Sel c/s  Bub c/s\n");
                  for (k = 0; k < 4; k++) {
                      for (i = 0; i < N; i++)
                          s[i] = b[i] = data[k][i];
                      selection(s, N, &sc, &ss);
                      bubble(b, N, &bc, &bs);
                      printf("%-9s %3d/%-3d  %3d/%d\n",
                             name[k], sc, ss, bc, bs);
                  }
                  return 0;
              }
              

              Output:

              Data      Sel c/s  Bub c/s
              Random     28/5     25/13
              Reversed   28/4     28/28
              Sorted     28/0      7/0
              Nearly     28/1     13/1

              The numbers confirm the race. Selection sort makes 28 comparisons every time (8 × 7 / 2), and never more than 7 swaps; here it made 5, 4, 0 and 1. Bubble sort’s comparisons range from 7 to 28 and its swaps from 0 to 28. Notice two details in the code. First, each sort works on its own copy of the data (s and b); otherwise the second sort would receive an already sorted list and the comparison would be unfair. Second, both functions report their counts through pointer parameters, a technique you have used since Lesson 03.

              Counting operations is a better way to compare algorithms than timing them with a stopwatch. Times depend on the computer, the compiler and what else is running; counts depend only on the algorithm and the data, so anyone can check them by hand.

              Part 5: Same list, two sorts

              Small examples show the difference most clearly. On the list 9, 4, 7, 1, selection sort finishes the job with a single swap in pass 1 (the 1 and the 9 trade places), while bubble sort needs five swaps because the 1 has to creep one step left in every pass. Step through both in the tracer.

              Try it 2Trace both sorts on one list

              Run selection sort, then bubble sort, on the same list. Compare the counters at the end.

              Output

              
              

              AfterSelection sortBubble sort
              Pass 11, 4, 7, 94, 7, 1, 9
              Pass 21, 4, 7, 94, 1, 7, 9
              Pass 31, 4, 7, 91, 4, 7, 9
              Totals6 comparisons, 1 swap6 comparisons, 5 swaps

              Exams often show you a list after some passes and ask which sort produced it. Use the patterns: after pass k of selection sort, the k smallest values sit in order at the start. After pass k of bubble sort, the k largest values sit in order at the end. In the table, only selection sort could have produced 1, 4, 7, 9 after pass 1, and only bubble sort could have produced 4, 7, 1, 9.

              Part 6: Which one would you choose?

              SituationBetter choiceReason
              Data is already or nearly sortedBubble sort with a flagStops after a pass with no swaps; few comparisons
              Swapping is expensive (large records, slow storage)Selection sortAt most n - 1 swaps
              Data in reverse orderSelection sortBubble sort swaps on every comparison
              Equal values must keep their orderBubble sortIt is stable
              Running time must be predictableSelection sortAlways n(n - 1) / 2 comparisons
              Very large data setNeither, ideallyBoth grow with n squared; faster sorts exist

              Which-to-choose exam questions

              Try these before opening the model answers. A good answer names the sort and gives a reason linked to the data or the cost of operations.

              1. A teacher keeps 2,000 marks in ascending order. Each day a handful of marks are corrected by one or two points, so a few values end up just one or two places out of position. Which sort would you recommend for putting the list back in order, and why?

              Show answer

              Bubble sort with a swapped flag. Because every value is at most a couple of places from where it belongs, one or two passes of neighbour swaps put the list right, and the next pass makes no swaps, so the flag stops the sort after only a few thousand comparisons. Selection sort would always make about two million comparisons (2,000 × 1,999 / 2). Be careful, though: if a new small value were added at the END of the list, bubble sort would need many passes, because small values move left only one place per pass.

              2. Records of 500 students are stored on a slow memory card where every write takes a long time. The records are in random order. Which sort would you recommend?

              Show answer

              Selection sort. It makes at most 499 swaps, and each swap means writing records, whereas bubble sort on random data typically makes tens of thousands of swaps. The extra comparisons of selection sort only need reads, which are cheaper.

              3. A program must sort a list that is known to be in exactly reverse order. Compare the work done by the two sorts on n items.

              Show answer

              Both make n(n - 1) / 2 comparisons. Selection sort makes about n / 2 swaps (each swap fixes two values), while bubble sort makes n(n - 1) / 2 swaps, one for every comparison. Selection sort is better here.

              4. A list of exam candidates is already sorted by name. It must now be sorted by school, keeping candidates from the same school in name order. Which sort should be used?

              Show answer

              Bubble sort, because it is stable: it never swaps equal values, so candidates from the same school stay in name order. Selection sort could break the name order.

              5. A student says, "Bubble sort is always slower than selection sort." Evaluate this statement.

              Show answer

              It is not always true. On random or reversed data bubble sort usually makes many more swaps, so it is slower. But on sorted or nearly sorted data, bubble sort with a flag makes far fewer comparisons and stops early, so it is faster.

              6. After two passes, the list 30, 10, 50, 20, 40 has become 10, 20, 50, 30, 40. Which sort was used? Explain.

              Show answer

              Selection sort: the two smallest values (10 and 20) are in their final places at the start, and the rest are unsorted. After two passes of bubble sort, the two largest (40 and 50) would be at the end instead.

              Part 7: Beyond these two

              Selection sort and bubble sort are the two sorts in this syllabus, but they are not the only ones. Insertion sort builds the sorted part by taking each new item and sliding it back into place, rather like sorting cards as you pick them up; it is also excellent on nearly sorted data. Merge sort and quicksort use divide and conquer, the same idea as binary search, and make roughly n × log₂ n comparisons instead of n squared. For a million items that is about 20 million comparisons instead of 500 billion, which is why real software libraries use them. Knowing that faster sorts exist, and why, is a sign of a strong answer when a question asks about very large data sets.

              Try it 3Compare and choose drill

              Pick a mode. "Choose" gives a situation and asks which sort fits best. "Count" asks for comparisons or swaps for a given n.

              Summary

              IdeaRemember
              ComparisonsSelection: always n(n - 1) / 2. Bubble with flag: n - 1 to n(n - 1) / 2.
              SwapsSelection: at most n - 1. Bubble: up to n(n - 1) / 2.
              Early exitBubble sort only, using a swapped flag.
              StabilityBubble sort is stable; selection sort is not.
              After pass kSelection: k smallest at the start. Bubble: k largest at the end.
              ChooseNearly sorted: bubble with flag. Costly swaps or reversed: selection.

              Review questions

              1. State one similarity and two differences between selection sort and bubble sort.

              Show answer

              Similarity: both use nested loops and make n(n - 1) / 2 comparisons in their worst case. Differences: selection sort makes at most one swap per pass while bubble sort can make many; bubble sort can stop early with a flag while selection sort cannot (also: bubble sort is stable, selection is not).

              2. For 12 items, give the number of comparisons made by selection sort, and by bubble sort with a flag on sorted data.

              Show answer

              Selection: 66. Bubble with flag on sorted data: 11.

              3. Why does selection sort make the same number of comparisons on sorted and unsorted data?

              Show answer

              To find the smallest remaining value it must look at every value in the unsorted part, whatever their order. There is no test that lets it stop early.

              4. Why can bubble sort make many more swaps than selection sort?

              Show answer

              Bubble sort swaps every neighbouring pair that is out of order, so a value moves one place per swap. Selection sort moves a value straight to its final place with a single swap.

              5. Explain why counting comparisons and swaps is a fair way to compare sorting algorithms.

              Show answer

              Counts depend only on the algorithm and the data, not on the speed of a particular computer, so they can be checked by hand and compared directly.

              6. Starting from 41, 5, 23, 37, 12, one pass of a sort gives 5, 41, 23, 37, 12. Which sort was used?

              Show answer

              Selection sort. Its first pass swaps the smallest value (5) with the first value (41), which gives exactly this list. One pass of bubble sort would instead carry 41 to the end, giving 5, 23, 37, 12, 41.

              7. Give a situation where you would choose bubble sort, with a reason.

              Show answer

              When the data is already nearly sorted, because bubble sort with a flag stops after a pass with no swaps, needing only a few passes.

              8. Give a situation where you would choose selection sort, with a reason.

              Show answer

              When swaps are expensive, for example moving large records or writing to slow storage, because selection sort makes at most n - 1 swaps.

              Homework

              1. Extend compare_sorts.c with a fifth data set of your own. Predict the counts before you run it.
              2. Remove the flag from the bubble function in compare_sorts.c. Which results change, and why?
              3. Write a paragraph answering: "Which sort should a teacher use to order 35 marks typed in random order?" Justify your answer using counts.
              4. Find a list of 6 numbers on which selection sort and bubble sort make exactly the same number of swaps.
              5. Research insertion sort. Trace it on 9, 4, 7, 1 and count its comparisons and moves. How does it compare with the two sorts in this lesson?

              Mastery quiz: Comparing the sorts

              This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

              Mastery quiz: Selection Sort vs Bubble Sort Compared

              Your course badges: loading saved progress…

              View badges

                No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                Saved in this browser on this device. Clearing browser data may remove your badges.

                Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                1. Which sort makes at most n - 1 swaps?
                2. Which sort can stop early when the list is already sorted?
                3. Selection sort on 10 items makes how many comparisons?
                4. On reversed data, which makes fewer swaps?
                5. Which sort is stable?
                6. After pass 2, the two LARGEST values are in place at the end. Which sort was used?
                7. Records are huge and every swap is slow. Which sort?
                8. The data is nearly sorted. Which sort usually finishes with least work?
                9. Bubble sort with a flag on 9 sorted items makes how many comparisons?
                10. Why compare algorithms by counting operations rather than timing them?

                Exam tips

                Comparison questions. Structure your answer as similarity, then differences, then a conclusion tied to the scenario. Use numbers when you can: "selection sort makes at most n - 1 swaps, whereas bubble sort can make up to n(n - 1) / 2" earns more credit than "selection sort swaps less".

                Which-to-choose questions. Look for clues in the scenario: nearly sorted, new items added or check if sorted point to bubble sort with a flag; large records, slow writes or reversed point to selection sort; keep the existing order of equal items points to bubble sort because it is stable.

                Paper 01 items on passes. When shown a list after some passes, check the ends: smallest values fixed at the start means selection sort; largest values fixed at the end means bubble sort. Lessons 08 and 09 have tips on the specimen items for each sort.

                More worked answers are on the CS Solutions page.

                Previous: 2009 U1 Q1. Next: Unit 2 • Module 2: Software Engineering (coming soon in this course).

                Syllabus link: CAPE Computer Science (CXC A19/U2/21), Data Structures (Unit 2, Module 1). Specific Objective 5: apply searching and sorting algorithms (comparing selection sort and bubble sort).

                Video search terms

                Search YouTube for: "selection sort vs bubble sort", "sorting algorithms compared visualisation", "stable vs unstable sorting".

                Try it 4Quick quiz

                Tap an answer. All eight questions are self-checks on this lesson.

                Updates

                2026/12/01

                - First version of the lesson.

                © 2026 islandclass.org

                Bubble Sort in C

                UNIT 2 • MODULE 1 • LESSON 09

                Drop a handful of small stones and a few bubbles of air into a glass of water and watch: the bubbles rise to the top, one after another. Bubble sort gets its name from that picture. It walks along the list comparing each pair of neighbours, and whenever a bigger value sits in front of a smaller one, the two swap places. Big values rise, one step at a time, towards the end of the list.

                Bubble sort is one of the most famous algorithms in computer science and a favourite of examiners, because it is short enough to write on paper but has enough moving parts (two loops, a shrinking range, a swap and an optional flag) to test real understanding. In this lesson you will learn how it works, trace it pass by pass, write it in C, make it stop early on sorted data, and find the classic bugs.

                What you will learn

                • How bubble sort compares and swaps neighbouring values.
                • Why the largest unsorted value reaches its final place in each pass.
                • The algorithm in pseudocode and in C, including the purpose of each loop.
                • Why the inner loop stops one place earlier on each pass.
                • How a swapped flag lets bubble sort stop early.
                • How to count comparisons and swaps, and how to spot common bubble sort bugs.

                Part 1: One pass

                A pass of bubble sort compares positions 0 and 1, then 1 and 2, then 2 and 3, and so on to the end of the unsorted part. If a pair is in the wrong order, it is swapped before moving on. Here is the first pass on six numbers:

                CompareResultList after this step
                [0] 29 and [1] 64In order29, 64, 12, 51, 8, 37
                [1] 64 and [2] 12Swap29, 12, 64, 51, 8, 37
                [2] 64 and [3] 51Swap29, 12, 51, 64, 8, 37
                [3] 64 and [4] 8Swap29, 12, 51, 8, 64, 37
                [4] 64 and [5] 37Swap29, 12, 51, 8, 37, 64

                Notice what happened to 64. Once the pass reached it, it was bigger than everything after it, so it kept swapping and was carried all the way to the end. That is always true: after pass 1, the largest value is in the last position. After pass 2, the second largest is next to it, and so on. The sorted part grows from the right, one value per pass.

                Small values move differently. 8 started at index 4 and moved only one place left during pass 1 (to index 3). Small values near the end creep towards the front one step per pass, which is why bubble sort can need many passes.

                Part 2: The algorithm

                PROCEDURE bubbleSort(list, n)
                    FOR pass ← 0 TO n - 2
                        FOR j ← 0 TO n - 2 - pass
                            IF list[j] > list[j + 1] THEN
                                temp ← list[j]
                                list[j] ← list[j + 1]
                                list[j + 1] ← temp
                            ENDIF
                        ENDFOR
                    ENDFOR
                END PROCEDURE
                • The outer loop counts the passes. It runs n – 1 times because each pass fixes one more value at the end, and once n – 1 values are in place, the last one must be too.
                • The inner loop walks along the unsorted part, comparing list[j] with its right-hand neighbour list[j + 1] and swapping them if they are in the wrong order.
                • The inner loop’s limit is n – 2 – pass (in C, j < n - 1 - pass). The “- 1” stops j + 1 running off the end of the array. The “- pass” skips the values already settled at the end, which saves comparisons.
                • The swap uses a temporary variable, exactly as in selection sort.

                Being able to explain the job of each loop in your own words, and why the inner limit shrinks, is worth as much in an exam as being able to write the code.

                Part 3: Watch it bubble

                Step through bubble sort on different data. Orange shows a comparison, darker orange a swap, and green the settled part at the end. Turn on Early exit for the third challenge; you will learn how it works in Part 5.

                Try it 1Bubble sort animator

                Choose some data, then step one comparison at a time, finish a pass, or run to the end. Complete the three challenges.

                Choose data

                Compare the counters with selection sort from Lesson 08. On the Reversed list, bubble sort makes the same 21 comparisons but 21 swaps, because every single comparison finds a pair in the wrong order. Selection sort needed only 3 swaps for the same data.

                Part 4: Bubble sort in C

                Worked example 1: sorting numbers, pass by pass

                This uses the same six numbers as Lesson 08, so you can compare the two sorts directly. It prints the array after every pass and counts the work.

                #include <stdio.h>
                
                #define N 6
                
                void show(const int a[], int n)
                {
                    int k;
                    for (k = 0; k < n; k++)
                        printf(" %d", a[k]);
                    printf("\n");
                }
                
                void bubbleSort(int list[], int n)
                {
                    int pass, j, temp;
                    int comps = 0, swaps = 0;
                
                    for (pass = 0; pass < n - 1; pass++) {
                        for (j = 0; j < n - 1 - pass; j++) {
                            comps++;
                            if (list[j] > list[j + 1]) {
                                temp = list[j];
                                list[j] = list[j + 1];
                                list[j + 1] = temp;
                                swaps++;
                            }
                        }
                        printf("Pass %d:", pass + 1);
                        show(list, n);
                    }
                    printf("Comparisons: %d, swaps: %d\n",
                           comps, swaps);
                }
                
                int main(void)
                {
                    int a[N] = {29, 64, 12, 51, 8, 37};
                
                    printf("Start: ");
                    show(a, N);
                    bubbleSort(a, N);
                    return 0;
                }
                

                Output:

                Start:  29 64 12 51 8 37
                Pass 1: 29 12 51 8 37 64
                Pass 2: 12 29 8 37 51 64
                Pass 3: 12 8 29 37 51 64
                Pass 4: 8 12 29 37 51 64
                Pass 5: 8 12 29 37 51 64
                Comparisons: 15, swaps: 9

                Read the passes from the right: 64 settles in pass 1, 51 in pass 2, 37 in pass 3. Meanwhile 8 creeps left one place per pass and only reaches the front in pass 4. Pass 5 makes no swaps at all, but this basic version runs it anyway, because it always does n - 1 passes. Selection sort sorted the same data with 5 swaps; bubble sort needed 9.

                Trace a smaller example step by step in the tracer. The second program previews the early-exit idea.

                Try it 2Trace bubble sort

                Choose a list, then step through it. Decide each swap before you reveal it.

                Output

                
                

                Part 5: Stopping early

                If a whole pass makes no swaps, every neighbouring pair is already in order, so the list is sorted and further passes are a waste of time. A Boolean flag records whether any swap happened during the current pass:

                FOR pass ← 0 TO n - 2
                    swapped ← FALSE
                    FOR j ← 0 TO n - 2 - pass
                        IF list[j] > list[j + 1] THEN
                            swap list[j] and list[j + 1]
                            swapped ← TRUE
                        ENDIF
                    ENDFOR
                    IF swapped = FALSE THEN
                        EXIT the outer loop
                    ENDIF
                ENDFOR

                Worked example 2: the flag in action

                #include <stdio.h>
                
                int bubbleSort(int list[], int n,
                               int *comps)
                {
                    int pass, j, temp, swapped;
                
                    *comps = 0;
                    for (pass = 0; pass < n - 1; pass++) {
                        swapped = 0;
                        for (j = 0; j < n - 1 - pass; j++) {
                            (*comps)++;
                            if (list[j] > list[j + 1]) {
                                temp = list[j];
                                list[j] = list[j + 1];
                                list[j + 1] = temp;
                                swapped = 1;
                            }
                        }
                        if (!swapped)
                            return pass + 1;
                    }
                    return n - 1;
                }
                
                int main(void)
                {
                    int a[8] = {3, 7, 12, 9,
                                15, 18, 21, 25};
                    int b[8] = {3, 7, 9, 12,
                                15, 18, 21, 25};
                    int passes, comps;
                
                    passes = bubbleSort(a, 8, &comps);
                    printf("Nearly sorted: %d passes,"
                           " %d comparisons\n",
                           passes, comps);
                    passes = bubbleSort(b, 8, &comps);
                    printf("Already sorted: %d pass,"
                           " %d comparisons\n",
                           passes, comps);
                    return 0;
                }
                

                Output:

                Nearly sorted: 2 passes, 13 comparisons
                Already sorted: 1 pass, 7 comparisons

                With 8 items, the basic version always makes 7 passes and 28 comparisons. With the flag, a nearly sorted list (only 12 and 9 out of place) is finished after 2 passes and 13 comparisons, and an already sorted list after just 1 pass and 7 comparisons. This is bubble sort’s big advantage over selection sort, which cannot detect sorted data at all.

                Data (n items)Comparisons, basicComparisons, with flagSwaps
                Already sortedn(n - 1) / 2n - 1 (one pass)0
                Nearly sortedn(n - 1) / 2Only a few passesFew
                Reversed (worst case)n(n - 1) / 2n(n - 1) / 2n(n - 1) / 2

                Part 6: Spot the bug

                Bubble sort is short, which makes it easy to get almost right. Each program below has one faulty line. Tap it to see what goes wrong and how to fix it.

                Try it 3Spot the bug in bubble sort

                Four short bubble sort fragments, each with one bug. Tap the faulty line, then move to the next program.

                Notice that bugs 2 and 4 still produce a sorted-looking result: one sorts the wrong way and the other is merely slow. Always test with data where you know the right answer, and check the counts, not just the final list. Counting passes and swaps is the quickest way to notice that an early exit never fires.

                Part 7: Tracing a whole sort and other variations

                When an exam asks for the list after each pass, a compact table keeps you accurate. Write one row per pass and box the settled values at the end. Here is the full sort of the numbers from Worked example 1:

                After[0][1][2][3][4][5]Swaps in pass
                Start29641251837
                Pass 1291251837644
                Pass 2122983751643
                Pass 3128293751641
                Pass 4812293751641
                Pass 5812293751640

                The swaps add up to 4 + 3 + 1 + 1 + 0 = 9, matching the program. Pass 5 made no swaps, so a version with the flag would have stopped there; on this data the flag saves nothing, because the last pass is needed anyway to prove the list is sorted.

                Variations you may meet

                • Descending order: swap when the left value is smaller (< instead of >). Now the smallest value sinks to the end on each pass.
                • Bubbling to the front: run the inner loop from the end towards the start, so the smallest value moves to index 0 on each pass. The counts are the same.
                • Cocktail shaker sort: alternate a left-to-right pass with a right-to-left pass. Small values near the end no longer creep slowly, which helps on some data, but the worst case is unchanged.
                • Sorting records: compare one field (say, surname) but swap the whole record, or every parallel array together, exactly as with selection sort.

                Where bubble sort is used

                In practice, bubble sort is rarely the fastest choice for large data, and professional libraries use cleverer algorithms. It survives for three reasons. It is an excellent teaching algorithm, because every step is visible. It is tiny, so it fits on simple devices with very little memory. And with the swapped flag it is genuinely quick on data that is already almost in order, such as a list where only two neighbouring values have been swapped by mistake. In that case one pass puts the pair right and a second pass with no swaps confirms the order, however long the list is.

                Common mistakes

                • Comparing a value with one two places away (j and j + 2) instead of its neighbour.
                • Letting the inner loop run to n, so that list[j + 1] reads past the end of the array.
                • Resetting the swapped flag outside the outer loop, so early exit never happens.
                • Stopping after one pass because the largest value has reached the end. One pass fixes one value, not the whole list.
                • In a trace, forgetting that a value just swapped to the right is compared again with its new neighbour straight away.

                The last point is the heart of bubble sort: a large value keeps travelling within a single pass, because after each swap it becomes the left member of the next pair. Keep that picture in mind and your traces will be accurate, whether the list has four items or forty.

                Try it 4Bubble sort drill

                Pick a mode. "Passes" gives a fresh array and asks about it after one or two passes, or how many swaps pass 1 makes. "Rules" checks the key facts.

                Summary

                IdeaRemember
                Each comparisonNeighbours list[j] and list[j + 1]; swap if the left is bigger.
                Each passCarries the largest unsorted value to the end of the unsorted part.
                Outer loopCounts passes: n - 1 of them at most.
                Inner loop limitj < n - 1 - pass: stay inside the array and skip the settled end.
                Swapped flagA pass with no swaps means sorted: stop early.
                Workn(n - 1) / 2 comparisons (basic); swaps from 0 up to n(n - 1) / 2.

                Review questions

                1. Describe how bubble sort arranges a list in ascending order.

                Show answer

                It repeatedly passes through the list comparing each pair of neighbouring items and swapping them if the left one is bigger. Each pass moves the largest unsorted value to the end, and the passes continue until the list is sorted.

                2. Show 41, 17, 36, 8, 22 after each pass of bubble sort.

                Show answer

                Pass 1: 17, 36, 8, 22, 41. Pass 2: 17, 8, 22, 36, 41. Pass 3: 8, 17, 22, 36, 41. Pass 4: 8, 17, 22, 36, 41 (no swaps).

                3. Explain the job of the outer loop in bubble sort.

                Show answer

                It controls the number of passes through the list. Each pass places one more value in its final position at the end, so at most n - 1 passes are needed.

                4. Explain what happens inside the inner loop.

                Show answer

                It moves along the unsorted part of the list, comparing each item with the next one. When an item is greater than its right neighbour, the two are exchanged using a temporary variable, so larger values move right.

                5. Why is the inner loop’s limit n - 1 - pass rather than n - 1?

                Show answer

                After each pass, one more value at the end is already in its final place, so there is no need to compare it again. Subtracting pass avoids those wasted comparisons.

                6. How does a swapped flag improve bubble sort?

                Show answer

                It records whether any swap was made in a pass. If a pass makes no swaps, the list is sorted, so the algorithm stops early instead of doing the remaining passes.

                7. How many comparisons does basic bubble sort make on 10 items? How many with the flag if the list is already sorted?

                Show answer

                45 (10 × 9 / 2). With the flag: 9 (one pass).

                8. Compare bubble sort and selection sort on number of swaps.

                Show answer

                Selection sort makes at most n - 1 swaps. Bubble sort makes one swap for every pair that is out of order, which can be as many as n(n - 1) / 2.

                Homework

                1. Trace bubble sort on 15, 3, 27, 9, 11, 2. Show the list after every pass and count the swaps.
                2. Add the swapped flag to bubble_sort.c and print how many passes were actually made.
                3. Change bubble_sort.c to sort into descending order. Which single character changes?
                4. Write a bubble sort for an array of strings using strcmp and strcpy.
                5. In your own words, explain why a small value at the end of the list takes many passes to reach the front, but a large value at the front reaches the end in one pass.

                Mastery quiz: Bubble sort

                This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

                Mastery quiz: Bubble Sort in C

                Your course badges: loading saved progress…

                View badges

                  No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                  Saved in this browser on this device. Clearing browser data may remove your badges.

                  Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                  1. Bubble sort compares...
                  2. After the first pass of an ascending bubble sort, which value is certainly in its final place?
                  3. List 5, 1, 4, 2. What is it after pass 1?
                  4. What job does the outer loop do?
                  5. Why does the inner loop use j < n - 1 - pass?
                  6. Basic bubble sort on 7 items makes how many comparisons?
                  7. With a swapped flag, how many passes are needed for sorted data?
                  8. Which data gives bubble sort the most swaps?
                  9. Swapping list[k] with the value to its right, which statement must come first?
                  10. Compared with selection sort, bubble sort usually makes...

                  Exam tips

                  Specimen Unit 2 Paper 02 (2021), Question 2(a). You are given a C bubble sort function and asked to explain the outer loop, the inner loop, and why the inner loop’s limit subtracts the pass counter. Use the language of Part 2: the outer loop controls the passes; the inner loop compares neighbours and swaps them when they are out of order; the limit shrinks because the largest values are already settled at the end (and the "- 1" keeps j + 1 inside the array). Mention the temporary variable when describing the swap.

                  Trace questions. Rewrite the list after each comparison during the first pass, then after each whole pass. A common error is to compare against the original list rather than the list as it changes.

                  Count questions. Comparisons in basic bubble sort depend only on n. Swaps depend on the data: count one for every pair that is out of order when compared.

                  More worked answers are on the CS Solutions page.

                  Previous: Unit 2 • Module 1 • Lesson 08 – Selection Sort in C. Next: Unit 2 • Module 1 • Lesson 10 – Selection Sort vs Bubble Sort Compared.

                  Syllabus link: CAPE Computer Science (CXC A19/U2/21), Data Structures (Unit 2, Module 1). Specific Objective 5: apply searching and sorting algorithms (bubble sort).

                  Video search terms

                  Search YouTube for: "bubble sort explained", "bubble sort passes trace", "bubble sort in C with flag".

                  Try it 5Quick quiz

                  Tap an answer. All eight questions are self-checks on this lesson.

                  Updates

                  2026/12/01

                  - First version of the lesson.

                  © 2026 islandclass.org

                  Selection Sort in C

                  UNIT 2 • MODULE 1 • LESSON 08

                  Give someone a hand of playing cards and ask them to put them in order. Many people do something like this: look through all the cards for the lowest one and put it at the left; then look through the rest for the next lowest and put it next; and so on until every card is in place. Without knowing it, they have just performed a selection sort.

                  Sorting matters because sorted data is much easier to use. You saw in Lesson 07 that binary search only works on sorted lists, and sorted reports, league tables and registers are easier for people to read. In this lesson you will learn selection sort in detail: the idea, the algorithm in pseudocode, a C version, how to trace it pass by pass, and how much work it does. In Lesson 09 you will meet bubble sort, and in Lesson 10 you will race the two against each other.

                  What you will learn

                  • The idea behind selection sort: select the smallest, swap it into place.
                  • The selection sort algorithm in pseudocode and in C.
                  • How to trace selection sort pass by pass, for numbers and for letters.
                  • How to count comparisons and swaps, and why the comparison count never changes.
                  • Which values move and which stay put, a favourite exam question.
                  • The strengths and weaknesses of selection sort.

                  Part 1: The idea

                  Selection sort splits the list into two parts: a sorted part on the left, which starts empty, and an unsorted part on the right, which starts as the whole list. Each pass does two things:

                  1. Select: scan the unsorted part to find the position of its smallest value.
                  2. Swap: exchange that smallest value with the first value of the unsorted part. The sorted part grows by one.

                  After the first pass the smallest value in the whole list is at index 0. After the second pass the two smallest values are at indexes 0 and 1, in order. After n – 1 passes, the last remaining value must be the largest, so the list is sorted. Here is a full example on six numbers:

                  [0][1][2][3][4][5]Smallest found
                  Start29641251837
                  Pass 1864125129378 at [4], swap with [0]
                  Pass 28126451293712 at [2], swap with [1]
                  Pass 38122951643729 at [4], swap with [2]
                  Pass 48122937645137 at [5], swap with [3]
                  Pass 58122937516451 at [5], swap with [4]

                  Bold values are in the sorted part. Notice that each pass places exactly one value in its final position, and that a swap can send a value from the front a long way to the right (29 jumped from index 0 to index 4 in pass 1). That long jump is why selection sort is not stable: two equal values can end up in the opposite order from how they started. Stability matters when sorting records by one field, for example sorting students by form when they are already in alphabetical order.

                  Part 2: The algorithm

                  PROCEDURE selectionSort(list, n)
                      FOR i ← 0 TO n - 2
                          minIdx ← i
                          FOR j ← i + 1 TO n - 1
                              IF list[j] < list[minIdx] THEN
                                  minIdx ← j
                              ENDIF
                          ENDFOR
                          IF minIdx ≠ i THEN
                              temp ← list[i]
                              list[i] ← list[minIdx]
                              list[minIdx] ← temp
                          ENDIF
                      ENDFOR
                  END PROCEDURE
                  • The outer loop (i) counts the passes and marks where the next smallest value must go.
                  • The inner loop (j) scans the unsorted part, remembering the index of the smallest value seen so far. Storing the index, not the value, is what makes the swap possible afterwards.
                  • The swap uses a temporary variable, because assigning list[i] ← list[minIdx] first would overwrite list[i] before it was saved.
                  • The test minIdx ≠ i skips pointless swaps when the smallest value is already in place. Some versions leave this test out and swap a value with itself, which is harmless but wastes a little time.

                  To sort into descending order, select the largest value instead: change < to > in the comparison (and call the variable maxIdx so your code stays readable).

                  Part 3: Watch it work

                  Step through selection sort on different kinds of data. Orange outlines show the current comparison or swap; green bars are in the sorted part. Keep an eye on the comparison and swap counters.

                  Try it 1Selection sort animator

                  Choose some data, then step one comparison at a time, finish a pass, or run to the end. Complete the three challenges.

                  Choose data

                  Did you notice that sorting the already sorted list took exactly as many comparisons (21) as sorting the reversed list? Selection sort cannot tell that the list is already in order, because finding the smallest value always means looking at every remaining value. What changes is the number of swaps: zero for sorted data, and never more than n - 1 for any data.

                  Part 4: Selection sort in C

                  Worked example 1: sorting numbers, pass by pass

                  This program prints the array after every pass and counts comparisons and swaps, so its output matches the hand trace in Part 1.

                  #include <stdio.h>
                  
                  #define N 6
                  
                  void show(const int a[], int n)
                  {
                      int i;
                      for (i = 0; i < n; i++)
                          printf(" %d", a[i]);
                      printf("\n");
                  }
                  
                  void selectionSort(int a[], int n)
                  {
                      int i, j, minIdx, temp;
                      int comps = 0, swaps = 0;
                  
                      for (i = 0; i < n - 1; i++) {
                          minIdx = i;
                          for (j = i + 1; j < n; j++) {
                              comps++;
                              if (a[j] < a[minIdx])
                                  minIdx = j;
                          }
                          if (minIdx != i) {
                              temp = a[i];
                              a[i] = a[minIdx];
                              a[minIdx] = temp;
                              swaps++;
                          }
                          printf("Pass %d:", i + 1);
                          show(a, n);
                      }
                      printf("Comparisons: %d, swaps: %d\n",
                             comps, swaps);
                  }
                  
                  int main(void)
                  {
                      int a[N] = {29, 64, 12, 51, 8, 37};
                  
                      printf("Start: ");
                      show(a, N);
                      selectionSort(a, N);
                      return 0;
                  }
                  

                  Output:

                  Start:  29 64 12 51 8 37
                  Pass 1: 8 64 12 51 29 37
                  Pass 2: 8 12 64 51 29 37
                  Pass 3: 8 12 29 51 64 37
                  Pass 4: 8 12 29 37 64 51
                  Pass 5: 8 12 29 37 51 64
                  Comparisons: 15, swaps: 5

                  Six items need five passes. The comparisons are 5 + 4 + 3 + 2 + 1 = 15, which is n(n - 1) / 2 with n = 6. Every pass in this example needed a real swap, so there were 5, the most possible.

                  Worked example 2: sorting letters

                  Characters in C are small integers (their character codes), and the capital letters A to Z have codes in alphabetical order, so the same algorithm sorts letters. This version always swaps, even when the smallest letter is already in place.

                  #include <stdio.h>
                  #include <string.h>
                  
                  void sortLetters(char s[])
                  {
                      int n = (int) strlen(s);
                      int i, j, m;
                      char t;
                  
                      for (i = 0; i < n - 1; i++) {
                          m = i;
                          for (j = i + 1; j < n; j++)
                              if (s[j] < s[m])
                                  m = j;
                          t = s[i];
                          s[i] = s[m];
                          s[m] = t;
                          printf("After pass %d: %s\n",
                                 i + 1, s);
                      }
                  }
                  
                  int main(void)
                  {
                      char word[] = "PKEWBTM";
                  
                      printf("Start:        %s\n", word);
                      sortLetters(word);
                      return 0;
                  }
                  

                  Output:

                  Start:        PKEWBTM
                  After pass 1: BKEWPTM
                  After pass 2: BEKWPTM
                  After pass 3: BEKWPTM
                  After pass 4: BEKMPTW
                  After pass 5: BEKMPTW
                  After pass 6: BEKMPTW

                  Look at passes 3, 5 and 6: the string does not change because the smallest remaining letter was already at the front of the unsorted part (K, P and T). The program swapped each with itself. Look also at which letters never moved from their starting position: E at index 2 moved to index 1, but T at index 5 started and finished at index 5. Questions that ask which values keep their original positions are answered by tracing every pass, not by comparing the start and end at a glance, because a value can move away and back again.

                  Trace both programs step by step in the tracer, answering the questions as you go.

                  Try it 2Trace selection sort

                  Choose a list, then step through it. Find the smallest before you reveal it.

                  Output

                  
                  

                  Part 5: How much work?

                  Computer scientists measure sorting algorithms by counting comparisons (checking two values) and swaps (exchanging two values). For selection sort on n items:

                  MeasureSelection sortExample: n = 10
                  Passesn - 19
                  Comparisons(n - 1) + (n - 2) + ... + 1 = n(n - 1) / 2, always45
                  Swaps (best case: sorted data)00
                  Swaps (worst case)n - 19
                  Extra memoryOne temporary variable1

                  Because the number of comparisons grows with the square of n, doubling the list roughly quadruples the work: 100 items need 4,950 comparisons and 1,000 items need 499,500. That is fine for small lists but slow for big ones, where faster algorithms such as merge sort and quicksort (beyond this module) are used. Selection sort’s strength is its small number of swaps, which matters when moving data is expensive, such as large records or writing to flash memory.

                  StrengthsWeaknesses
                  Simple to understand and codeAlways makes n(n - 1) / 2 comparisons, even on sorted data
                  At most n - 1 swapsSlow for large lists
                  Sorts in place, needing almost no extra memoryNot stable: equal values may change order

                  To feel the difference that squaring makes, imagine a computer that can do one million comparisons per second. Sorting the 1,500 students of a large secondary school by selection sort needs about 1.1 million comparisons, so it is done in about a second. Sorting the roughly 400,000 candidates in a national examination database would need about 80 billion comparisons, which would take nearly a day. An algorithm that is perfectly sensible for a class register can be hopeless for a national database. This is why the size of the data should always be part of your answer when you recommend an algorithm.

                  Part 6: Tracing tips for exams

                  • Write the indexes above the list before you start, so you never lose track of positions.
                  • For each pass, underline the part still unsorted, circle its smallest value, and draw an arrow for the swap.
                  • Rewrite the whole list after every pass; do not try to do several passes in your head.
                  • If asked "how many swaps", count only swaps of two different values; a pass where the smallest is already in place has no swap.
                  • If asked for the list after a certain number of passes, stop exactly there. A common mistake is to give the fully sorted list.

                  Practise with the drill below until you can do a pass in a few seconds. Speed matters in Paper 01, where each item is worth the same mark, but accuracy matters more: a single slip in pass 1 spoils every pass after it, so check each pass before moving on.

                  Part 7: Sorting records and parallel arrays

                  In a real program you usually sort records, not bare numbers. Suppose a teacher stores names in one array and marks in a parallel array, so names[i] and marks[i] belong to the same student. If you sort only the marks, every name ends up next to the wrong mark. The rule is simple: compare one field, but swap every field.

                  IF minIdx ≠ i THEN
                      tempMark ← marks[i]
                      marks[i] ← marks[minIdx]
                      marks[minIdx] ← tempMark
                      tempName ← names[i]
                      names[i] ← names[minIdx]
                      names[minIdx] ← tempName
                  ENDIF

                  With an array of structs, the job is easier: one struct assignment copies every field at once, so the three-step swap moves the whole record. In C, names are strings, so swapping them in parallel char arrays needs strcpy and a temporary string. This is one reason programmers prefer arrays of structs to parallel arrays.

                  A variation: select the largest

                  Selection sort can also work from the other end. In each pass, find the largest value in the unsorted part and swap it with the last position of that part. The sorted part then grows from the right instead of the left. The number of passes, comparisons and swaps is exactly the same, and the final list is still ascending. Exam questions occasionally use this version, so read the description carefully and trace what it says, not what you expect.

                  Common mistakes

                  • Swapping inside the inner loop every time a smaller value is found. That turns the algorithm into something else and makes far more swaps. The swap belongs after the inner loop.
                  • Starting the inner loop at j = 0 instead of j = i + 1, which drags already-sorted values back into the search.
                  • Resetting minIdx to 0 instead of i at the start of each pass.
                  • Writing a[i] = a[minIdx]; a[minIdx] = a[i]; without a temporary variable, which copies one value twice and loses the other.
                  • Running the outer loop to n instead of n - 1. It still works, but the last pass does nothing useful.

                  If your selection sort gives a wrong answer, add a printf after each pass that shows the whole array, exactly as Worked example 1 does, and compare it with a hand trace. The first pass that differs tells you where the bug is.

                  Try it 3Selection sort drill

                  Pick a mode. "Passes" gives a fresh array and asks about it after some passes, or how many swaps a full sort makes. "Rules" checks the key facts.

                  Summary

                  IdeaRemember
                  Each passFind the smallest in the unsorted part; swap it to the front of that part.
                  Passesn - 1
                  ComparisonsAlways n(n - 1) / 2
                  Swaps0 to n - 1
                  Outer loopChooses the position to fill.
                  Inner loopFinds the index of the smallest remaining value.

                  Review questions

                  1. Describe how selection sort arranges a list in ascending order.

                  Show answer

                  It repeatedly finds the smallest value in the unsorted part of the list and swaps it with the first value of the unsorted part. After each pass the sorted part at the front grows by one, and after n - 1 passes the list is sorted.

                  2. Show the list 46, 19, 73, 5, 32 after each pass of selection sort.

                  Show answer

                  Pass 1: 5, 19, 73, 46, 32. Pass 2: 5, 19, 73, 46, 32 (no swap). Pass 3: 5, 19, 32, 46, 73. Pass 4: 5, 19, 32, 46, 73 (no swap).

                  3. How many swaps of different values were made in the previous question?

                  Show answer

                  2 (passes 1 and 3).

                  4. Why does the inner loop store the index of the smallest value rather than the value itself?

                  Show answer

                  Because the swap needs to know where the smallest value is, so it can move the value at position i into that position.

                  5. How many comparisons does selection sort make on 8 items? Does it depend on the order of the data?

                  Show answer

                  8 × 7 / 2 = 28. No: the comparisons are the same for any order.

                  6. Write the C code for the swap in selection sort.

                  Show answer

                  temp = a[i];
                  a[i] = a[minIdx];
                  a[minIdx] = temp;

                  7. What change sorts the list into descending order?

                  Show answer

                  Look for the largest instead: use > instead of < in the comparison (and track maxIdx).

                  8. Give a strength and a weakness of selection sort.

                  Show answer

                  Strength: few swaps (at most n - 1) and very simple. Weakness: always makes n(n - 1) / 2 comparisons, so it is slow on large lists and gains nothing when data is already sorted.

                  Homework

                  1. Trace selection sort on the letters Q, D, X, A, M, H. Show the list after every pass and count the swaps.
                  2. Modify selection_sort.c to sort into descending order. Test it with the same data.
                  3. Write a C function that sorts an array of student structs by average mark using selection sort. Swap whole structs.
                  4. Count how many times each value in 31, 7, 18, 7, 25 moves during selection sort. Do the two 7s stay in their original order?
                  5. Explain why selection sort is a good choice when writing to memory is slow but reading is fast.

                  Mastery quiz: Selection sort

                  This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

                  Mastery quiz: Selection Sort in C

                  Your course badges: loading saved progress…

                  View badges

                    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                    Saved in this browser on this device. Clearing browser data may remove your badges.

                    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                    1. What does each pass of selection sort do?
                    2. How many passes does selection sort need for 9 items?
                    3. How many comparisons does selection sort make on 6 items?
                    4. What is the most swaps selection sort can make on 6 items?
                    5. List: 40, 10, 30, 20. What is it after pass 1?
                    6. List: 40, 10, 30, 20. What is it after pass 2?
                    7. On an already sorted list, selection sort makes...
                    8. Why is a temp variable used in the swap?
                    9. What does the inner loop of selection sort find?
                    10. To sort in descending order, selection sort should select...

                    Exam tips

                    Specimen Unit 2 Paper 01 (2021), Item 4. A list of letters is shown and you must pick the list after the first three passes. Do exactly three passes, writing the list out after each one. Stop after the third: one of the wrong options is usually the fully sorted list.

                    Specimen Unit 2 Paper 01 (2021), Items 5 and 6. A list of numbers is sorted by selection sort and you count the swaps of distinct numbers, then name the numbers that never leave their original positions. Trace every pass, mark passes with no swap, and record each value’s position after every pass. A value that is swapped away and later swapped back does not count as staying put.

                    Written questions. When explaining selection sort, use the words pass, smallest (or minimum), unsorted part and swap. When writing code, show both loops, the minIdx variable, and a three-step swap with a temporary variable.

                    More worked answers are on the CS Solutions page.

                    Previous: Unit 2 • Module 1 • Lesson 07 – Searching in C: Linear Search and Binary Search. Next: 2009 U1 Q1.

                    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Data Structures (Unit 2, Module 1). Specific Objective 5: apply searching and sorting algorithms (selection sort).

                    Video search terms

                    Search YouTube for: "selection sort explained", "selection sort trace passes", "selection sort in C".

                    Try it 4Quick quiz

                    Tap an answer. All eight questions are self-checks on this lesson.

                    Updates

                    2026/12/01

                    - First version of the lesson.

                    © 2026 islandclass.org

                    Searching in C: Linear Search and Binary Search

                    UNIT 2 • MODULE 1 • LESSON 07

                    How do you find a word in a dictionary? You do not start at “aardvark” and read every entry. You open somewhere near the middle, see whether your word comes before or after that page, and throw away the half you do not need. Repeat a few times and you are there. Now imagine your friend has written words on cards and shuffled them. With no order to help you, the only option is to turn the cards over one at a time.

                    Those two strategies are the two searches in the CAPE syllabus: binary search (the dictionary method) and linear search (the shuffled-cards method). In this lesson you will write both as algorithms and in C, trace them step by step, count their comparisons, and learn when each one is the right choice.

                    What you will learn

                    • How linear search works, in pseudocode and in C, and how to count its comparisons.
                    • How binary search works using low, high and mid, and why the data must be sorted.
                    • How to trace both searches on a given array, including when the item is missing.
                    • How to compare the two searches: best case, worst case and typical case.
                    • Which search to choose for a given situation, including linked lists and unsorted data.

                    Part 1: Linear search

                    A linear search (also called a sequential search) starts at the first item and compares each item with the target, one after another, until it either finds the target or runs out of items. It makes no assumptions about the order of the data, so it works on any list.

                    FUNCTION linearSearch(list, n, key)
                        FOR i ← 0 TO n - 1
                            IF list[i] = key THEN
                                RETURN i
                            ENDIF
                        ENDFOR
                        RETURN -1
                    END FUNCTION

                    The function returns the index where the key was found, or -1 if it is not in the list. Returning straight away when the key is found is important: there is no need to keep looking. A common variation uses a WHILE loop and a Boolean found flag, which some teachers prefer because it has only one exit point:

                    i ← 0
                    found ← FALSE
                    WHILE i < n AND found = FALSE DO
                        IF list[i] = key THEN
                            found ← TRUE
                        ELSE
                            i ← i + 1
                        ENDIF
                    ENDWHILE

                    Counting comparisons

                    CaseWhen it happensComparisons (n items)
                    BestThe key is the first item1
                    WorstThe key is last, or not in the listn
                    Average (key present)The key is equally likely to be anywhereabout n / 2

                    Worked example 1: linear search in C

                    This function receives the array, its length and the key, and also reports how many comparisons it made through a pointer parameter. main searches for a value at the very start, one in the middle and one that is missing.

                    #include <stdio.h>
                    
                    #define N 8
                    
                    int linearSearch(const int a[], int n,
                                     int key, int *comps)
                    {
                        int i;
                        *comps = 0;
                        for (i = 0; i < n; i++) {
                            (*comps)++;
                            if (a[i] == key)
                                return i;
                        }
                        return -1;
                    }
                    
                    int main(void)
                    {
                        int marks[N] = {64, 12, 89, 45,
                                        70, 33, 91, 58};
                        int keys[3] = {64, 33, 50};
                        int k, pos, comps;
                    
                        for (k = 0; k < 3; k++) {
                            pos = linearSearch(marks, N,
                                               keys[k], &comps);
                            if (pos == -1)
                                printf("%d missing", keys[k]);
                            else
                                printf("%d at index %d",
                                       keys[k], pos);
                            printf(", comparisons: %d\n",
                                   comps);
                        }
                        return 0;
                    }
                    

                    Output:

                    64 at index 0, comparisons: 1
                    33 at index 5, comparisons: 6
                    50 missing, comparisons: 8

                    The output matches the table exactly. 64 is first (best case, one comparison). 33 is at index 5, so six comparisons. 50 is missing, so every one of the eight items is checked (worst case) before the function returns -1.

                    Part 2: Binary search

                    A binary search works only on a sorted list. It keeps track of the part of the list that could still contain the key, using two indexes, low and high. Each step it looks at the item in the middle of that range:

                    • If the middle item is the key, the search is over.
                    • If the middle item is smaller than the key, the key can only be in the upper half, so move low to mid + 1.
                    • If the middle item is larger than the key, the key can only be in the lower half, so move high to mid – 1.
                    • If low passes high, the range is empty and the key is not in the list.
                    FUNCTION binarySearch(list, n, key)
                        low ← 0
                        high ← n - 1
                        WHILE low ≤ high DO
                            mid ← (low + high) DIV 2
                            IF list[mid] = key THEN
                                RETURN mid
                            ELSE IF list[mid] < key THEN
                                low ← mid + 1
                            ELSE
                                high ← mid - 1
                            ENDIF
                        ENDWHILE
                        RETURN -1
                    END FUNCTION

                    Because every comparison throws away half of what is left, binary search is described as a divide and conquer algorithm. The number of comparisons grows very slowly: a list of 15 items needs at most 4 comparisons, 1,000 items at most 10, and a million items at most 20. Each doubling of the list adds just one more comparison.

                    Items (n)Linear search, worst caseBinary search, worst case
                    15154
                    1001007
                    1,0001,00010
                    1,000,0001,000,00020

                    Worked example 2: binary search in C, with a trace

                    This version prints low, high and mid every time round the loop, so the output is a ready-made trace table. It searches for 63 (present) and 20 (missing) in a sorted array of 11 items.

                    #include <stdio.h>
                    
                    #define N 11
                    
                    int binarySearch(const int a[], int n,
                                     int key)
                    {
                        int low = 0, high = n - 1, mid;
                        while (low <= high) {
                            mid = (low + high) / 2;
                            printf("  low=%d high=%d mid=%d"
                                   " a[mid]=%d\n",
                                   low, high, mid, a[mid]);
                            if (a[mid] == key)
                                return mid;
                            if (a[mid] < key)
                                low = mid + 1;
                            else
                                high = mid - 1;
                        }
                        return -1;
                    }
                    
                    int main(void)
                    {
                        int a[N] = {3, 8, 14, 21, 27, 35,
                                    42, 50, 63, 77, 88};
                        int pos;
                    
                        printf("Search for 63:\n");
                        pos = binarySearch(a, N, 63);
                        printf("Result: index %d\n", pos);
                        printf("Search for 20:\n");
                        pos = binarySearch(a, N, 20);
                        printf("Result: %d (not found)\n", pos);
                        return 0;
                    }
                    

                    Output:

                    Search for 63:
                      low=0 high=10 mid=5 a[mid]=35
                      low=6 high=10 mid=8 a[mid]=63
                    Result: index 8
                    Search for 20:
                      low=0 high=10 mid=5 a[mid]=35
                      low=0 high=4 mid=2 a[mid]=14
                      low=3 high=4 mid=3 a[mid]=21
                    Result: -1 (not found)

                    Finding 63 takes two comparisons: 35 is too small, so low jumps to 6; then mid is 8 and a[8] is 63. Searching for 20 takes three: 35 is too big (high becomes 4), 14 is too small (low becomes 3), 21 is too big (high becomes 2). Now low (3) is greater than high (2), so the loop ends and -1 is returned. Notice mid = (low + high) / 2 uses whole-number division in C, which rounds down.

                    Part 3: Race them

                    The Try it runs both searches side by side on the same 15 numbers. Choose a target, then step. Linear search highlights the item it is checking; binary search shades the range that is still possible and outlines mid. Try the challenges to discover when each search wins.

                    Try it 1Search race: linear vs binary

                    Choose a target and step both searches together. Complete the four challenges.

                    Target

                    Linear search

                    Binary search

                    Did you see binary search fail on the unsorted data? It compared the target with the middle item, decided which half to throw away, and threw away the half that actually contained the target. Binary search does not crash on unsorted data; it quietly gives the wrong answer. That is why “the list must be sorted” is the first thing to say about it.

                    Part 4: Tracing searches by hand

                    For linear search, list each index checked until you stop. For binary search, use a table with columns low, high, mid, list[mid] and the decision. Here is a search for 27 in the 11-item array from Worked example 2:

                    Steplowhighmida[mid]Decision
                    101053535 > 27, so high ← 4
                    20421414 < 27, so low ← 3
                    33432121 < 27, so low ← 4
                    444427Found at index 4

                    Four comparisons for 11 items is the worst case here. Now step through both searches in the tracer, answering the questions as you go.

                    Try it 2Trace linear and binary search

                    Choose a search, then step through it. Predict each value before you reveal it.

                    Output

                    
                    

                    Part 5: Choosing a search

                    QuestionLinear searchBinary search
                    Does the data need to be sorted?NoYes
                    Works on a linked list?YesNot efficiently (no direct access to the middle)
                    Best case1 comparison (first item)1 comparison (middle item)
                    Worst case for n itemsn comparisonsabout log₂ n + 1 comparisons
                    Good forSmall or unsorted lists, lists searched onceLarge sorted arrays searched many times
                    CodeVery simpleA little more complex (low, high, mid)

                    Examiners like to ask what is true of both searches. Both can be used on a sorted list (linear search does not care about order, so sorted data is fine). Both return a position or a "not found" signal. But only linear search may need to examine every item in its worst case; binary search only ever examines a handful of middles. Be precise with words like both, always and require.

                    What if the data is unsorted but you need to search it thousands of times? Then it can be worth sorting it once (Lessons 08 and 09) and then using binary search for every look-up. That trade-off, paying once to save many times, is a big idea in computer science.

                    Duplicates

                    Neither search is broken by duplicate values. Linear search returns the first match it meets. Binary search returns a match, but not necessarily the first one, because it lands on whichever copy happens to be at a mid. If you need the first copy, you can keep searching to the left after a match.

                    Part 6: Searching records and strings

                    In real programs you rarely search for a bare number. You search for a student by ID, a product by code or a contact by name. The algorithms do not change; only the comparison does. To search an array of structs for a matching ID, compare one field:

                    FOR i ← 0 TO n - 1
                        IF students[i].id = targetId THEN
                            RETURN i
                        ENDIF
                    ENDFOR
                    RETURN -1

                    Strings need one extra step in C, because == compares the addresses of two strings, not their letters. Use strcmp from string.h, which returns 0 when two strings match, a negative number when the first comes earlier in alphabetical order, and a positive number when it comes later. That three-way answer is exactly what binary search needs:

                    cmp = strcmp(names[mid], key);
                    if (cmp == 0)
                        return mid;
                    else if (cmp < 0)
                        low = mid + 1;
                    else
                        high = mid - 1;

                    For binary search on names, the array must be in alphabetical order, and capital and small letters must be handled consistently, because strcmp compares character codes and every capital letter comes before every small letter. A school system might store all surnames in capitals for exactly this reason.

                    Efficiency in plain words

                    Computer scientists describe how the work grows as the data grows. For linear search, doubling the list doubles the worst-case work: the growth is linear. For binary search, doubling the list adds just one comparison: the growth is logarithmic. With small lists the difference hardly matters, and linear search may even be quicker because it is so simple. With large lists the difference is enormous: searching a sorted list of every person in the Caribbean, roughly 44 million people, takes at most 26 comparisons with binary search, against up to 44 million with linear search. That single example is worth remembering for any "compare the two searches" question.

                    Common mistakes

                    • Putting return -1; inside the linear search loop, so the function gives up after checking only the first item.
                    • Writing while (low < high) instead of low <= high in binary search, which skips the last remaining item and can miss the key.
                    • Setting low = mid or high = mid instead of mid + 1 or mid - 1. The range may stop shrinking and the loop can run forever.
                    • Using binary search on data that was never sorted, or was sorted in descending order while the code assumes ascending order.
                    • Comparing strings with == in C instead of strcmp.

                    Each of these mistakes compiles without any warning, so the only way to catch them is to test with the key at the start, in the middle, at the end and missing.

                    Try it 3Search drill

                    Pick a mode. "Count" asks for mids and comparison counts on a fresh sorted array. "Rules" checks which search to use and why.

                    Summary

                    IdeaRemember
                    Linear searchCheck each item from the start until found or the end; works on any list.
                    Binary searchSorted data only; check mid, discard half, repeat.
                    mid(low + high) DIV 2, rounding down.
                    Not foundLinear: reach the end. Binary: low > high. Return -1.
                    Worst caseLinear: n comparisons. Binary: about log₂ n + 1.
                    Linked listsLinear search only.

                    Review questions

                    1. Describe how a linear search works.

                    Show answer

                    Starting at the first item, compare each item with the target in turn. Stop when the target is found (return its position) or when every item has been checked (report not found).

                    2. State the condition that must be true before a binary search can be used, and explain why.

                    Show answer

                    The list must be sorted. Binary search decides which half to discard by comparing with the middle item; this only works if all smaller items are on one side and all larger items on the other.

                    3. Write a C function that searches an integer array called num of n items for key, one item at a time, returning the index of key or -1.

                    Show answer

                    int linearSearch(int num[], int n, int key)
                    {
                    int i;
                    for (i = 0; i < n; i++)
                    if (num[i] == key)
                    return i;
                    return -1;
                    }

                    4. Trace a binary search for 8 in [2, 5, 8, 12, 16, 23, 38]. Show low, high and mid.

                    Show answer

                    low=0, high=6, mid=3 (12 > 8) so high=2. low=0, high=2, mid=1 (5 < 8) so low=2. low=2, high=2, mid=2 (8) found at index 2. Three comparisons.

                    5. What is the maximum number of comparisons a binary search needs for 31 items? For a linear search?

                    Show answer

                    Binary: 5 (31 → 15 → 7 → 3 → 1). Linear: 31.

                    6. Why is binary search described as divide and conquer?

                    Show answer

                    Each step divides the remaining range in half and continues with only the half that can contain the key, so the problem shrinks quickly.

                    7. Give one situation where linear search is the better choice.

                    Show answer

                    When the data is unsorted and will only be searched once or twice, when the list is very small, or when the data is in a linked list.

                    8. A list contains 8, 9, 4, 5, 6, 9, 2. Can binary search be used on it? Explain.

                    Show answer

                    Not as it stands, because the list is not sorted. (Duplicates are not the problem.) It would first need to be sorted.

                    Homework

                    1. Write a C program that reads 10 integers into an array, asks for a key, and uses linear search to print every index where the key appears.
                    2. Trace binary search for 77 and for 40 on the 11-item array from Worked example 2. How many comparisons does each need?
                    3. Write the binary search as a recursive function binarySearch(a, low, high, key).
                    4. Copy the table in Part 2 and add a row for 1,000,000,000 items. How many comparisons does binary search need in the worst case?
                    5. Explain, with an example, why binary search can give the wrong answer on unsorted data without crashing.

                    Mastery quiz: Linear and binary search

                    This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

                    Mastery quiz: Searching in C: Linear Search and Binary Search

                    Your course badges: loading saved progress…

                    View badges

                      No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                      Saved in this browser on this device. Clearing browser data may remove your badges.

                      Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                      1. Which search checks items one after another from the start?
                      2. What must be true before binary search can be used?
                      3. Which phrase sums up the strategy of binary search?
                      4. Which statement is true for BOTH searches?
                      5. Linear search on 50 items, key not present. How many comparisons?
                      6. low = 4, high = 9. What is mid?
                      7. a[mid] is smaller than the key. What happens next?
                      8. When does binary search report not found?
                      9. Maximum binary search comparisons for 1,000 sorted items?
                      10. Which search should be used on a singly linked list?

                      Exam tips

                      Specimen Unit 2 Paper 01 (2021), Items 8, 9 and 10. Item 8 gives an unordered array (with a repeated value) and some statements about binary search: the reason binary search cannot be used is that the list is not sorted, not that it has duplicates. Item 9 asks what is true of both searches: think carefully about sorted lists, worst cases and averages. Item 10 asks for the best description of binary search: divide and conquer.

                      Specimen Unit 2 Paper 02 (2021), Question 2(b). You write C code for a linear search on a named array, accepting a key and returning a result. Include the function header with the array, its size and the key; a loop over every index; the comparison; returning the index on a match; and returning -1 after the loop. Do not put "return -1" inside the loop, or the function will give up after the first item.

                      Trace tables. For binary search, always show low, high and mid on every row, and use whole-number division for mid. Examiners award marks for each correct row.

                      More worked answers are on the CS Solutions page.

                      Previous: Unit 2 • Module 1 • Lesson 06 – Singly Linked Lists: Diagrams, Algorithms and Array-Based Nodes in C. Next: Unit 2 • Module 1 • Lesson 08 – Selection Sort in C.

                      Syllabus link: CAPE Computer Science (CXC A19/U2/21), Data Structures (Unit 2, Module 1). Specific Objective 5: apply searching and sorting algorithms (linear search and binary search).

                      Video search terms

                      Search YouTube for: "linear search vs binary search", "binary search trace low high mid", "binary search in C".

                      Try it 4Quick quiz

                      Tap an answer. All eight questions are self-checks on this lesson.

                      Updates

                      2026/12/01

                      - First version of the lesson.

                      © 2026 islandclass.org