Functions, Arrays and Data Structures
Arrays and Lists in Detail; Functions That Process Lists; Searching, Sorting and Why Data Structures Matter; Core Coding Styles and Structured Programming Principles; Control Structures: Sequence, Selection and Iteration; The Software Development Life Cycle in Overview
On this page9 sections
- 01Learning Objectives
- 02Arrays and Lists in Detail
- 03Functions That Process Lists
- 04Searching, Sorting and Why Data Structures Matter
- 05Core Coding Styles and Structured Programming Principles
- 06Control Structures: Sequence, Selection and Iteration
- 07The Software Development Life Cycle in Overview
- 08Practical Work
- 09Scenario-Based Questions
Learning Objectives
- Use arrays and lists to store many values.
- Write functions that process lists.
- Explain searching and sorting algorithms.
- Use structured programming and the SDLC in overview.
Arrays and Lists in Detail
Real-world data is almost always a collection. A school holds lists of students, subjects, fees and scores; a bank holds lists of transactions; a clinic holds lists of patients. Without lists a program could only handle one value at a time. An array or list is an ordered collection of values stored under one variable name. Each value is an element, and each element is identified by its index, the position number. In JavaScript, lists are written with square brackets and indexing starts at zero, so in the list [78, 85, 92, 60, 74] the first element (index 0) is 78 and scores[2] returns 92. The list name, scores, is a single variable that silently holds five values, which is far more practical than writing five separate variables for forty-five students.
Common list operations make the idea concrete. Creating a list uses square brackets and commas. Reading an element uses the index inside brackets such as names[0]. Changing an element assigns a new value such as names[1] = Obinna. Adding to the end uses the push method. The length property returns how many elements the list holds, and a for loop can visit every element in order. The natural way to process a whole list is iteration. A for loop runs the index i from 0 to one less than the length, and inside the loop scores[i] reaches each element in turn, adding it to a running total. After the loop ends, dividing by the length gives the average. This one pattern, loop through a list and accumulate, powers most real data-processing programs.
Functions That Process Lists
A function can receive a list as a parameter, just like any other value, and can loop through the list to compute a result. A function such as computeAverage(scores) sums every element with a for loop and returns total divided by scores.length. Parameters are the names in the definition; arguments are the actual values passed when the function is called. A function may also be given a default value, so a caller can omit the argument when the default is acceptable. A function can return a list containing several results, which the caller unpacks, and this is how one function provides the average, the highest and the lowest score at once.
Reuse is the power of functions. Once computeAverage or analyzeScores is written, it can be called with any suitable list. For three classes the same function runs three times with different data, once per class, without copying or changing the code. The same logic is written once and executes for every class, every term and every dataset the school will ever feed to it. This is why functions are the natural unit of decomposition, each one small, named and reusable, directly continuing the computational thinking of Week 1.
Searching, Sorting and Why Data Structures Matter
A data structure is a way of organising data so that operations on it are efficient. The same data can be stored in different structures, and the choice affects how fast a program can search, sort or update it. For small lists in school exercises the difference is negligible, but for a bank holding millions of transactions or a clinic holding thousands of patient records the choice can mean seconds instead of hours. Linear search is the simplest search method. It checks each element one by one from the beginning until it finds the target or reaches the end. Its main limitation is that for a very large list it may have to examine every element, which becomes slow; but for small lists it is perfectly adequate and easy to write.
A compare-and-swap sort, often called bubble sort, steps through the list repeatedly, compares neighbouring elements and swaps them whenever they are in the wrong order. Each full pass settles one more value into its final position, so the next pass can ignore it. Tracing, also called dry-running, is how learners truly understand an algorithm, writing down the list after every pass by hand. For [5, 3, 8, 1] the first pass carries 8 to the end to give [3, 5, 1, 8], the second pass gives [3, 1, 5, 8], the third pass gives [1, 3, 5, 8], and the final pass finds no swaps because the list is already sorted.
Bubble sort is not the fastest algorithm for large lists, but it is easy to understand and it demonstrates the core idea that sorting means repeatedly correcting the order until neighbour pairs are all in position. The choice of data structure and algorithm is deeply connected to the four pillars of computational thinking. Abstraction keeps only the attributes that matter, such as name and score. Pattern recognition sees the same compare-and-swap action repeated, which becomes the loop. Decomposition splits the overall task into separate functions for computing averages, sorting and searching. Algorithmic thinking designs the exact steps each function follows. In a school that must rank students by total score and then find where a specific student placed, a list of paired name-and-score records, a compare-and-swap sort and linear search work together to produce the ranked report.
Core Coding Styles and Structured Programming Principles
Good programs are not only correct; they are also easy to read, understand and change. Structured programming builds a program from clear, well-organised blocks instead of tangled jumps. Its core idea is that every program can be expressed using only three control structures: sequence (running statements one after another), selection (choosing between alternatives) and iteration (repeating a block of statements).
Clean code follows simple practices. Indentation shows which statements belong inside a loop or a decision. Descriptive names explain what a variable or function does, for example calling a variable classAverage instead of x. Short, focused functions do one job well, and comments explain why a tricky block exists rather than restating the code line by line.
Naming conventions keep a project consistent. JavaScript code in this course uses camelCase for variables and functions (computeAverage, totalScore), and CAPITAL_SNAKE_CASE for constants that never change. These habits make the difference between code that a learner can return to after a month and code that is impossible to trace. Structured, clean code is the foundation of every larger topic that follows, including functions, arrays and algorithms.
Sequence: run statements in order.
Selection: choose a path with if and else.
Iteration: repeat work with loops.
Use indentation and descriptive names.
Keep functions small and comments meaningful.
camelCase for variables; CAPITAL_SNAKE_CASE for constants.
Control Structures: Sequence, Selection and Iteration
Control structures decide the order in which statements run, and no program can be written without them. Sequence is the default: the program runs line by line from top to bottom, as when a program collects a student name, collects the score, then computes the average. Almost every block of real code begins with a sequence.
Selection lets a program choose between paths using conditions. The if statement checks a condition and runs its block only when the condition is true, while if else decides between two branches. Selection is what lets a search report Found or Not found, or a grading program award pass or fail based on a score.
Iteration repeats a block of statements, which is how a program processes every element of a list. A for loop with a counter visits each index, while a while loop repeats as long as a condition holds, such as reading scores until the user stops entering them. Because sequences, selections and iterations nest inside one another, tracing the control flow of a program predicts exactly what it will do.
Sequence: statements run in order.
if and if else: selection by condition.
for and while: iteration over a known or unknown number of runs.
Nesting lets small structures build complex behaviour.
Tracing control flow prevents logic errors.
The Software Development Life Cycle in Overview
Building real software is a project, not just typing code. The Software Development Life Cycle (SDLC) structures that project into phases. Planning defines the problem, the users and the goals, including budget and deadlines. Analysis studies the current situation and gathers detailed requirements, turning vague requests into a clear specification of what the software must do.
Design turns the requirements into a blueprint: the system architecture, the data structures, the modules and the user interface. Implementation is where the design becomes working code. Testing checks the software against the requirements and finds defects before the users do. Deployment releases the finished system, and maintenance keeps it working by fixing errors, adding features and adapting the software as needs change.
The SDLC is not always strictly linear. Many teams use agile approaches that repeat short cycles of plan, build, test and review, but the same activities always appear. The algorithms of this week, searching, sorting and data structures, feed directly into the analysis and design phases, because decisions about how data is organised are made before the implementation phase begins.
Planning: define the problem, users, budget and deadlines.
Analysis: gather and document the requirements.
Design: produce the architecture and data model.
Implementation: write and integrate the code.
Testing: verify the software against its requirements.
Deployment: release the working system.
Maintenance: fix, enhance and adapt the software over time.
| Pass | Comparisons and swaps | List after pass |
|---|---|---|
| 1 | 5 over 3 swap, 5 under 8 no swap, 8 over 1 swap | [3, 5, 1, 8] |
| 2 | 3 under 5 no swap, 5 over 1 swap, 5 under 8 no swap | [3, 1, 5, 8] |
| 3 | 3 over 1 swap, 3 under 5 no swap | [1, 3, 5, 8] |
| 4 | No swaps needed, list is sorted | [1, 3, 5, 8] |
Practical Work
- Write a function that finds the largest value in a list.
- Trace a linear search through a list of numbers.
- Sort a short list of numbers by hand using a sorting method.
- State one reason data structures matter.
Scenario-Based Questions
- A teacher stores the scores of five students in a list called scores = [72, 85, 61, 90, 54]. Write a Python function computeAverage that accepts this list, loops through it to find the sum and returns the average. Explain how 0-based indexing is used and why scores[0] gives 72.
- A bank stores the day's transactions in a queue. The first customer to arrive should be served first. Explain why a queue is more appropriate than a stack for this situation and describe what happens if the bank accidentally uses a stack instead.
- A librarian has 500 books sorted by catalogue number and needs to find whether number 347 exists. Compare linear search and binary search for this task: state the best-case and worst-case number of comparisons for each and explain why binary search is faster on sorted data.
- Trace the first two passes of bubble sort on the list [4, 1, 3, 2]. Show the list after each pass and state which swaps occur. Explain why bubble sort is described as a compare-and-swap algorithm.
- A developer has three different data storage needs: (a) the last 10 error messages displayed in reverse order, (b) a list of registered users that grows as people sign up, (c) a print queue where the longest job was submitted first. Choose a stack, a list or a queue for each case and justify each choice.
- A hospital records patient temperatures every hour for 24 hours in a list. Write a short Python function that finds the highest and lowest temperatures. Explain how the function processes the list and why passing the list as a parameter (rather than hard-coding values) makes the function reusable for any patient.
- A student implements bubble sort but the list [8, 3, 5, 1] is not sorted after one pass. Explain why multiple passes are needed and describe the condition that tells the algorithm the list is finally sorted.
LEARNING OBJECTIVES: BY THE END OF THE LESSON STUDENTS SHOULD BE ABLE TO:
| Cognitive | i. Use arrays and lists to store many values. ii. Write functions that process lists. iii. Explain searching and sorting algorithms. iv. Use structured programming and the SDLC in overview. |
| Affective | i. Appreciate the value of Functions, Arrays and Data Structures in school, at home and in the community. ii. Show willingness to use digital tools carefully, safely and responsibly. |
| Psychomotor | i. Write a function that finds the largest value in a list. ii. Trace a linear search through a list of numbers. iii. Sort a short list of numbers by hand using a sorting method. iv. State one reason data structures matter. |
Rationale: Real-world data is almost always a collection. Understanding arrays and Lists in Detail, functions That Process Lists, searching, Sorting and Why Data Structures Matter, core Coding Styles and Structured Programming Principles helps learners use digital technology confidently, safely and responsibly.
Pre-requisite Knowledge: In Week 2, learners studied Advanced Programming, including from a Clear Problem to a Working Program, control Structures and Structured Programming, functions, Modules and Coding Style. The knowledge from that week is used again in this lesson.
Learning Material/Teaching Aid: Whiteboard, markers, computer or laptop where available, printed notes and charts on Functions, Arrays and Data Structures, practical task sheets, learners' notebooks and pens.
Reference Materials: Digital Technology for Senior Secondary Schools (SS 3); NERDC Digital Technology Curriculum; Digital Technology SS 3 First Term Notes (Week 3); First Term examination and Continuous Assessment question papers.
LESSON DEVELOPMENT
| Stage/Step (Time) | Teacher's Activities | Student's Activities | Learning Points |
|---|---|---|---|
| Introduction 5 MINUTES | Welcomes learners, revises Week 2 (Advanced Programming) with two quick oral questions, and asks what they already know about Functions, Arrays and Data Structures. Elicits responses and writes the topic on the board. | Recall the previous lesson and share what they already know about Functions, Arrays and Data Structures. | Connecting prior knowledge to Functions, Arrays and Data Structures. |
| Step 1 6 MINUTES | Covers Arrays and Lists in Detail: Real-world data is almost always a collection. A school holds lists of students, subjects, fees and scores; a bank holds lists of transactions; a clinic holds lists of patients. Covers Functions That Process Lists: A function can receive a list as a parameter, just like any other value, and can loop through the list to compute a result. A function such as computeAverage(scores) sums every element with a for loop and returns total divided by scores.length. | Listen, take notes and answer oral questions on "Arrays and Lists in Detail" and related points. | Understanding: Arrays and Lists in Detail; Functions That Process Lists. |
| Step 2 6 MINUTES | Covers Searching, Sorting and Why Data Structures Matter: A data structure is a way of organising data so that operations on it are efficient. The same data can be stored in different structures, and the choice affects how fast a program can search, sort or update it. Covers Core Coding Styles and Structured Programming Principles: Good programs are not only correct; they are also easy to read, understand and change. Structured programming builds a program from clear, well-organised blocks instead of tangled jumps. | Copy the key points, give examples from school and everyday life, and ask questions on "Searching, Sorting and Why Data Structures Matter" and related points. | Understanding: Searching, Sorting and Why Data Structures Matter; Core Coding Styles and Structured Programming Principles. |
| Step 3 6 MINUTES | Covers Control Structures: Sequence, Selection and Iteration: Control structures decide the order in which statements run, and no program can be written without them. Sequence is the default: the program runs line by line from top to bottom, as when a program collects a student name, collects the score, then computes the average. | Discuss in pairs, then report one point on "Control Structures: Sequence, Selection and Iteration" to the class. | Understanding: Control Structures: Sequence, Selection and Iteration. |
| Step 4 6 MINUTES | Covers The Software Development Life Cycle in Overview: Building real software is a project, not just typing code. The Software Development Life Cycle (SDLC) structures that project into phases. Planning defines the problem, the users and the goals, including budget and deadlines. | Respond to questions, complete the examples on the board and note down "The Software Development Life Cycle in Overview". | Understanding: The Software Development Life Cycle in Overview. |
| Practical Work 6 MINUTES | Guides learners through the practical work: (i) Write a function that finds the largest value in a list. (ii) Trace a linear search through a list of numbers. (iii) Sort a short list of numbers by hand using a sorting method. Moves round the class to check progress and correct unsafe or careless use. | Carry out the practical tasks individually or in pairs and record what they did in their notebooks. | Applying the lesson through hands-on practice. |
| Evaluation 3 MINUTES | Asks learners to: i. Use arrays and lists to store many values. ii. Write functions that process lists. iii. Explain searching and sorting algorithms. iv. Use structured programming and the SDLC in overview. | Respond verbally and in writing to the evaluation questions. | Assessment and consolidation of the lesson content. |
| Conclusion 2 MINUTES | Recaps the main points: arrays and Lists in Detail, functions That Process Lists, searching, Sorting and Why Data Structures Matter, core Coding Styles and Structured Programming Principles, control Structures: Sequence, Selection and Iteration. Links them to the assignment and previews Week 4: Object-Oriented Programming. | Listen, ask questions and copy the assignment. | Reinforcement of key concepts and a preview of the next lesson. |
Assignment: i. A teacher stores the scores of five students in a list called scores = [72, 85, 61, 90, 54]. Write a Python function computeAverage that accepts this list, loops through it to find the sum and returns the average. Explain how 0-based indexing is used and why scores[0] gives 72. ii. A bank stores the day's transactions in a queue. The first customer to arrive should be served first. Explain why a queue is more appropriate than a stack for this situation and describe what happens if the bank accidentally uses a stack instead.
On this page9 sections
- 01Lesson objectives
- 02Key vocabulary
- 03Common misconceptions
- 04Teacher activities
- 05Student activities
- 06Practical / learning evidence
- 07Resources and preparation
- 08Assessment for learning
- 09Inclusion and homework
Lesson objectives
By the week's close, candidates should be able to:
- Define function, parameter and return.
- Write a function that averages a list.
- Apply append, index and len.
- Store a record in a dictionary.
- Trace two calls.
Key vocabulary
- Function: a named block performing one task.
- Parameter: a variable named in a definition.
- Return value: the result sent to the caller.
- List: an ordered collection read by index.
- Dictionary: a set of key and value pairs.
Common misconceptions
- "A parameter and an argument are the same." The parameter is the name; the argument is the supplied value.
- "Index 1 is always the first item." Python counts from 0.
Teacher activities
- Starter: trace a two-call function.
- Teach definition, call and return.
- Model average(marks) with a guard.
- Extend to append and lookup.
- Set two test lists.
- Review index errors.
Student activities
- Complete the starter trace.
- Label parameters and arguments.
- Type average(marks) and call it twice.
- Append 90 and recalculate.
- Build a three-key dictionary.
- Repair an IndexError.
def average(marks):
if len(marks) == 0:
return 0
return sum(marks) / len(marks)
scores = [62, 48, 71, 55]
print("Average:", average(scores))
scores.append(90)
print("Rounded:", round(average(scores), 1))
student = {"name": "Amaka", "score": 71}
print(student["name"], student["score"])
Expected output:
Average: 59.0
Rounded: 65.2
Amaka 71
Practical / learning evidence
ss3_scores_okoro.py defines average(marks), calls it on two lists, prints one rounded result and reads one dictionary record. Success needs an empty-list guard and two returned values.
Resources and preparation
Python 3, projector and a prepared empty list. Offline route: hand trace both calls beside the printed code.
Assessment for learning
Inspect the guard, the division and both calls. Award marks for argument order and dictionary access.
Inclusion and homework
Supply the function header; extend others to a highest(marks) function. Homework: write lowest(a, b, c) with one test call.