Nexus Learn

Lecture 18: Arrays Traversal Search

Lecture Notes CS-307 Programming Fundamentals 9 min read Updated 8 Nov 2026

↓ Download notes (Word)

On this page
  1. Learning Outcomes
  2. 1. Traversal and Partly-Filled Arrays
  3. 2. Sum, Average and Above Average
  4. 3. Linear Search
  5. 4. Maximum and Minimum With Position
  6. 5. Counting
  7. 6. Common Mistakes When Tracing Array Loops
  8. 7. Word Bank (Key Terms)
  9. 8. Self-Check Questions

UNIVERSITY OF AGRICULTURE, FAISALABAD

Department of Computer Science

LECTURE 18 · STUDENT NOTES

Lists (Arrays) II: Traversal, Searching, Max/Min & Counting

CS-307 Programming Fundamentals · BSCS Semester 1

Week

Slides

Linked practical

Reference ID

7

Lecture18_Arrays_Traversal_Search.pptx

Practical 13

N18

Learning Outcomes

SLO

By the end of this lecture you can…

Builds CLO

Bloom level

SLO 18.1

Traverse an array with a for loop to read, print, total and average its elements

CLO4: Describe the syntax and semantics of the C++ programming language.

C3

SLO 18.2

Apply linear search, maximum/minimum and counting patterns to an array

CLO1: Identify the necessary properties of good problem-solving techniques.

C3

SLO 18.3

Trace array loops and find off-by-one and wrong-start-value mistakes

CLO1: Identify the necessary properties of good problem-solving techniques.

C4

How to use these notes

Read these notes after the lecture and before the practical. Section numbers (for example §3.2) are used in the question bank, so you can always find where an answer comes from. Type every code example yourself — do not copy-paste.

1. Traversal and Partly-Filled Arrays

To traverse an array means to visit every element once, in order, with a loop. Every pattern in this lecture is the same loop with a different body. (Slide L18-S05)

Traversal template

for (int i = 0; i < n; i++) {

... a[i] ... // add, compare or count

}

The array size must be a constant, but the number of students is known only when the program runs. So we declare the array for the largest case (const int MAX = 30;), read n with validation (1 to MAX), and use only the first n boxes. Every loop then runs to n, never to MAX. This is called a partly-filled array.

Partly-filled array

const int MAX = 30;

int marks[MAX], n;

do {

cout << "How many students (1-30)? ";

cin >> n;

} while (n < 1 || n > MAX);

for (int i = 0; i < n; i++) // only n boxes

cin >> marks[i];

Real-world

A 30-seat coaster with 18 passengers: it is still a 30-seat coaster, but the conductor only checks tickets in seats 1–18.

2. Sum, Average and Above Average

This is the problem that shows why arrays exist: the average is known only after all marks are read, so the marks must be kept to compare them with the average. (Slide L18-S06)

above_avg.cpp

#include <iostream>

using namespace std;

int main() {

const int MAX = 30;

int marks[MAX], n;

do {

cout << "How many students (1-30)? ";

cin >> n;

} while (n < 1 || n > MAX);

int total = 0;

for (int i = 0; i < n; i++) { // pass 1: read and add

cin >> marks[i];

total += marks[i];

}

double avg = (double) total / n;

cout << "Average: " << avg << endl;

int above = 0;

cout << "Above average:";

for (int i = 0; i < n; i++) { // pass 2: compare with the average

if (marks[i] > avg) {

cout << " " << marks[i];

above++;

}

}

cout << endl << "Count above average: " << above << endl;

return 0;

}

Session

How many students (1-30)? 0

How many students (1-30)? 5

70 85 64 90 58

Average: 73.4

Above average: 85 90

Count above average: 2

  • Pass 1 reads and adds (sum pattern). Pass 2 compares each stored mark with the average (count pattern).
  • (double) total / n avoids integer division: 367 / 5 would give 73, not 73.4.

Linear search checks the elements one by one from the start until the key (the value we are looking for) is found or the list ends. Real-world: finding your roll number on the seating plan outside the exam hall. (Slides L18-S07, S08)

Figure 18.1 – Linear search for 1052 stops at index 3 after four comparisons (Slide L18-S07)

search.cpp

#include <iostream>

using namespace std;

int main() {

const int N = 8;

int roll[N] = {1021, 1034, 1047, 1052, 1068, 1075, 1083, 1096};

int key;

cout << "Roll number to find: ";

cin >> key;

int pos = -1; // -1 means "not found yet"

for (int i = 0; i < N; i++) {

if (roll[i] == key) {

pos = i;

break; // stop at the first match

}

}

if (pos != -1)

cout << key << " found at index " << pos << " (seat " << pos + 1 << ")" << endl;

else

cout << key << " is not in the list" << endl;

return 0;

}

Three runs

Roll number to find: 1052

1052 found at index 3 (seat 4)

Roll number to find: 1050

1050 is not in the list

Roll number to find: 1021

1021 found at index 0 (seat 1)

  • pos = -1 means not found yet; -1 can never be a real index.
  • When the key is found, store the index and break (search pattern from Lecture 14).
  • People count from 1, arrays from 0: print pos + 1 for the seat number.

3.1 Decide 'not found' after the loop

search_bug.cpp

#include <iostream>

using namespace std;

int main() {

int roll[5] = {1021, 1034, 1047, 1052, 1068};

int key = 1047;

for (int i = 0; i < 5; i++) {

if (roll[i] == key)

cout << "Found at index " << i << endl;

else

cout << "Not found" << endl; // BUG: decided too early

}

return 0;

}

Output — wrong

Not found

Not found

Found at index 2

Not found

Not found

The program decides after looking at only one element. 'Found' can be decided as soon as a match is seen, but 'not found' is true only after every element has been checked — so the decision goes after the loop, using pos (or a bool flag).

4. Maximum and Minimum With Position

Keep the index of the best value so far (maxPos), not only the value. Then temp[maxPos] is the value and maxPos + 1 is the day. (Slide L18-S09)

Figure 18.2 – Maximum with position: maxPos changes 0 → 1 → 3 (Slide L18-S09)

maxmin.cpp

#include <iostream>

using namespace std;

int main() {

const int N = 7;

int temp[N] = {31, 36, 29, 41, 38, 27, 33};

int maxPos = 0, minPos = 0; // start from the FIRST element

for (int i = 1; i < N; i++) {

if (temp[i] > temp[maxPos]) maxPos = i;

if (temp[i] < temp[minPos]) minPos = i;

}

cout << "Hottest: " << temp[maxPos] << " on day " << maxPos + 1 << endl;

cout << "Coolest: " << temp[minPos] << " on day " << minPos + 1 << endl;

return 0;

}

Output

Hottest: 41 on day 4

Coolest: 27 on day 6

i

temp[i]

maxPos after

minPos after

start

31

0

0

1

36

1

0

2

29

1

2

3

41

3

2

4

38

3

2

5

27

3

5

6

33

3

5

4.1 The start-value trap

Never start a maximum at 0. (Slide L18-S10)

max_zero_bug.cpp

#include <iostream>

using namespace std;

int main() {

int t[5] = {-3, -7, -1, -5, -4}; // night temperatures in Skardu

int highest = 0; // BUG: should start as t[0]

for (int i = 0; i < 5; i++) {

if (t[i] > highest) highest = t[i];

}

cout << "Highest: " << highest << endl;

return 0;

}

Output — wrong (the answer is -1)

Highest: 0

Every value is below 0, so highest never changes and the program prints 0 — a value that is not even in the list. Fix: int highest = t[0];. The same rule applies to a minimum (starting at 0 fails when all values are positive).

Pattern

Start value

Loop from

Sum / count

0

i = 0

Max / min (value or position)

the first element (index 0)

i = 1

Search position

-1 (not found)

i = 0, break when found

5. Counting

Count pattern: count = 0; before the loop and if (rule) count++; inside it. Several counters can be updated in the same loop. (Slide L18-S11)

counting.cpp

#include <iostream>

using namespace std;

int main() {

const int N = 10;

int runs[N] = {45, 0, 102, 67, 0, 12, 50, 88, 3, 0};

int fifties = 0, ducks = 0;

for (int i = 0; i < N; i++) {

if (runs[i] >= 50) fifties++; // count pattern

if (runs[i] == 0) ducks++;

}

cout << "Scores of 50 or more: " << fifties << endl;

cout << "Ducks (0 runs): " << ducks << endl;

return 0;

}

Output

Scores of 50 or more: 4

Ducks (0 runs): 3

Pattern

Body of the traversal loop

Sum

total += a[i];

Count

if (rule) count++;

Maximum

if (a[i] > a[pos]) pos = i;

Search

if (a[i] == key) { pos = i; break; }

6. Common Mistakes When Tracing Array Loops

None of these is caught by the compiler — they are logic errors or undefined behaviour, found only by tracing and testing. (Slide L18-S13)

Mistake

Result

Fix

Loop to MAX instead of n

uses empty (garbage) boxes

i < n

Loop to n inclusive (i <= n)

reads a[n] — out of bounds

i < n

Max starts at 0

wrong for all-negative data

start at a[0]

'Not found' inside the loop

message printed many times

decide after the loop

Integer average total / n

73 instead of 73.4

(double) total / n

Test cases for array programs

One element (n = 1) · all values equal · all values negative · key at the first and last position · key missing.

7. Word Bank (Key Terms)

Word

Simple meaning

Traverse

Visit every element once, in order

Partly-filled array

An array declared for MAX elements but using only the first n

Key

The value we are searching for

Linear search

Checking elements one by one from the start

Position (index) of max

Where the largest value is, e.g. which day

Two-pass

Visiting the same array twice: once to collect, once to use

8. Self-Check Questions

1. For a = {14, 9, 27, 3, 27, 11}, what are the value and index of the maximum (test >)? What changes with >=?

2. How many values in a are greater than 10?

3. Searching a for 3: which index, and how many comparisons?

4. Why must the marks be stored to count the marks above average?

5. Why is int highest = 0; wrong for night temperatures?

6. Where must 'Not found' be printed, and why?

Answers: 27 at index 2; with >= index 4. 4. Index 3, 4 comparisons. The average is known only after all marks are read (§2). All values are below 0, so 0 stays the maximum (§4.1). After the loop (§3.1). Homework is on Slide L18-S15.

← All CS-307 material