Iteration and Lists

AP Computer Science Principles · Unit 3 — Algorithms and Programming

Three loops and how they stop

Iteration repeats a block of statements. The exam pseudocode has three forms.

REPEAT n TIMES
{
   <block of statements>
}

REPEAT UNTIL(condition)
{
   <block of statements>
}

FOR EACH item IN aList
{
   <block of statements>
}

REPEAT n TIMES runs the block exactly n times. REPEAT UNTIL(condition) checks the condition before each pass and stops as soon as it is true; if the condition is true at the start the block runs zero times, and if it never becomes true the loop never ends — an infinite loop. A condition written with = is fragile: a variable that jumps past the target value (by steps of 2, say) never equals it.

FOR EACH item IN aList assigns item the value of each element of the list in order, from the first to the last. The variable item holds a copy of the value: assigning a new value to item inside the loop does not change the list. To change elements, loop over the indices and assign to aList[i].

To trace any loop, make a table with one column per variable and one row per pass, and write the values at the end of each pass. Count the passes from the loop rule, not from what the code was meant to do.

Lists: indices start at 1

A list is an ordered sequence of elements; using a list lets one name stand for many values, which is data abstraction. The operations on the reference sheet:

Removing while traversing forward is a classic trap. After REMOVE(aList, i), the element that was at i + 1 is now at i; if the loop then increases i, that element is never examined. Two equal values next to each other will leave one behind. Safe fixes: increase i only when nothing was removed, traverse from the end toward the start, or build a new list containing the elements to keep.

Standard list algorithms — sum, average, count, maximum or minimum, filter into a new list, linear search — are all a loop with an accumulator or a new list initialised before the loop.

L ← [10, 20, 30]101202303INSERT(L, 2, 15)101152203304APPEND(L, 45)101152203304455REMOVE(L, 1)15120230345420 và 30 lùi sang chỉ số 3, 4mọi phần tử tiến lên một chỉ số
Chỉ số từ 1 và hiệu ứng dời chỗ. INSERT và REMOVE làm đổi chỉ số của mọi phần tử phía sau. Một chỉ số tính trước khi INSERT/REMOVE có thể trỏ sang phần tử khác sau đó — gốc của lỗi “xoá sót” khi duyệt xuôi.

Worked example: Truy vết vòng lặp vừa duyệt vừa xoá

The segment below is intended to remove every 4 from list.

list ← [4, 4, 7, 4, 9]
i ← 1
REPEAT UNTIL(i > LENGTH(list))
{
   IF(list[i] = 4)
   {
      REMOVE(list, i)
   }
   i ← i + 1
}
DISPLAY(list)

Trace the segment, state what is displayed, and give a one-line change that makes it correct.

Solution

Lượt i = 1: list[1] = 4, xoá → list = [4, 7, 4, 9]; i = 2. Lượt i = 2: list[2] = 7, không xoá; i = 3. Lượt i = 3: list[3] = 4, xoá → list = [4, 7, 9]; i = 4. Kiểm điều kiện: 4 > 3 đúng, dừng. Màn hình hiện [4, 7, 9] — số 4 thứ hai bị “nhảy cóc” vì sau lần xoá đầu nó trượt về chỉ số 1 trong khi i đã sang 2.

Sửa một dòng: đặt i ← i + 1 vào nhánh ELSE của lệnh IF, tức chỉ tăng i khi không xoá. Truy vết lại: i = 1 xoá → [4, 7, 4, 9], i vẫn 1; xoá → [7, 4, 9]; i = 1 là 7, i = 2; i = 2 là 4, xoá → [7, 9]; i = 2 là 9, i = 3; dừng. Kết quả [7, 9].

Common mistake

Bẫy chỉ số 0 và bẫy FOR EACH. Học viên quen Python/Java hay đọc list[1] thành phần tử thứ hai; trong pseudocode AP CSP, list[1] là phần tử đầu tiên và list[0] là lỗi. Bẫy thứ hai: tưởng FOR EACH x IN nums { x ← x * 10 } nhân mọi phần tử lên 10 — danh sách không đổi. Bẫy thứ ba: REPEAT UNTIL với điều kiện đúng ngay từ đầu thì thân vòng chạy 0 lần.

Key takeaway

Chốt: REPEAT n TIMES chạy đúng n lần; REPEAT UNTIL kiểm trước mỗi lượt, có thể chạy 0 lần hoặc vô hạn; FOR EACH cho bản sao giá trị từng phần tử. Danh sách đánh chỉ số từ 1 tới LENGTH, ngoài khoảng đó là lỗi. INSERT dời phải, REMOVE dồn trái — vừa duyệt xuôi vừa xoá sẽ bỏ sót phần tử.

← Variables, Expressions, Boolean Logic and Selection · All AP Computer Science Principles lessons · Practice AP Computer Science Principles questions (free, instant scoring) · Procedures, Abstraction, Libraries and Simulations →