Example 1: for + if · Sequential Search
One for loop visits every cell. One if checks each cell.
Example 1: for + if · Sequential Search(循序搜尋)
Learning goals(學習目標)
- Use a for loop to visit every cell, from index 0 to the last one.
- Use an if statement to check whether
data[i]is the target.- Know what to print when the target is not found:
-1.
0. Real-life scene: guess first(生活情境:先猜一猜)
There are 10 lockers. One of them may hold a card with 47. You must open them one by one, starting from locker 0.
Guess: If 47 is in locker 9, how many lockers do you open? If no locker has 47, how many lockers must you open before you can say "not found"?
中文提示:47 在 9 號櫃要開幾個?全部都沒有 47,要開幾個才可以說「找不到」?
1. The task(題目)
The array data holds 10 numbers:
index : 0 1 2 3 4 5 6 7 8 9
data : 35 52 68 12 47 52 36 52 74 27
Read an integer target. Search from index 0. Print the index(位置)of the first match. If there is no match, print -1.
| Sample input / 範例輸入 | Sample output / 範例輸出 | Why / 說明 |
|---|---|---|
47 | 4 | data[4] is 47 |
52 | 1 | 52 appears 3 times; we want the first one |
99 | -1 | None of the 10 cells is 99 |
2. Diagrams(圖解)
2.1 The flow: for walks, if checks
2.2 Trace: searching for 47(追蹤)
We needed 5 comparisons to find 47. If the target is in the last cell, we need 10. Searching from the first cell to the last is called sequential search. The data does not need to be sorted.
3. Code(程式碼)
#include <iostream>
using namespace std;
int main() {
int data[10] = {35, 52, 68, 12, 47, 52, 36, 52, 74, 27};
int target;
cin >> target;
int pos = -1; // assume "not found" first
for (int i = 0; i < 10; i++) { // for: visit each cell
if (data[i] == target) { // if: is this the target?
pos = i;
break; // stop at the first match
}
}
cout << pos << endl;
return 0;
}
4. Key lines(重點逐行看)
| Code / 程式 | What it does / 作用 |
|---|---|
int pos = -1; | Assume "not found" first. If the loop never changes it, the answer is -1. |
for (int i = 0; i < 10; i++) | i goes from 0 to 9, one cell each time. |
if (data[i] == target) | Compare with == (two equal signs). |
break; | Leave the loop at the first match, so 52 gives 1, not 7. |
5. Common mistakes(常見錯誤)
- Writing
=instead of==.data[i] = targetputs a value into the cell. It does not compare.(=是放入,==才是比較) - Printing -1 inside the loop with
else. If the first cell is wrong, it prints -1 at once. You only know "not found" after the loop has finished.(「找不到」要等 for 全部跑完) - Writing
i <= 10.data[10]does not exist. The valid indexes are 0 to 9.
ClassWork 1-1: Pass count(及格人數)
Use for to read each score and if to check it. Add 1 to
countfor each pass.
Task: Read n scores. A score of 60 or more is a pass. Print the number of passes.
中文提示:60 分或以上為及格,輸出及格人數。
Input format(輸入格式)
- Line 1: an integer
n(1 ≤ n ≤ 100) - Line 2:
ninteger scores (0 to 100)
Output format(輸出格式): one integer, the number of passes.
Sample 1
Input:
6
45 60 72 59 88 60
Output:
4
Sample 2
Input:
4
10 20 30 40
Output:
0
Hints(提示)
- Put
int count = 0;outside the loop. - "60 or more" is
>= 60, so 60 is a pass.
ClassWork 1-2: Maximum and its position(最大值與位置)
Use for to walk through the array once. Use if to update "the largest so far".
Task: Read n integers. Print the maximum and its index (starting from 0). If the maximum appears more than once, print the first index.
中文提示:最大值出現多次,輸出第一次出現的位置。
Input format(輸入格式)
- Line 1: an integer
n(1 ≤ n ≤ 100) - Line 2:
nintegers
Output format(輸出格式): one line with the maximum and its index, separated by one space.
Sample 1
Input:
10
35 52 68 12 47 52 36 52 74 27
Output:
74 8
Sample 2
Input:
5
7 9 3 9 1
Output:
9 1
Hints(提示)
- Start by assuming cell 0 is the largest:
maxValue = data[0]andmaxIndex = 0. - Should you compare with
>or>=? Look at Sample 2: which 9 should you keep?
Self-check(自我檢查)
- Why does
posstart at -1 and not 0? - If you remove
break;and input 52, what is printed? Why? - With 10 numbers, what is the largest and the smallest number of comparisons?
Learning notes: Excerpt and Comment → Note Card(學習筆記:節錄評論法 → 卡片盒)
Reading is not the same as learning. Use Excerpt and Comment(節錄評論法): copy one key sentence, then add your own experience and ideas. Write the result as a note card(卡片盒筆記). Each card holds one idea, so you can link cards together later.
Step 1: Excerpt one key sentence(節錄一句重點)
"If you find it, you can
breakat once. If you don't, you only know after the loop has checked every cell."
Step 2: Answer the guiding questions(回答引導提問)
Choose one option, then add one or two sentences of your own.
Question 1 · Experience link(經驗連結): What experience of your own does this sentence remind you of?
- A. Looking for something at home or at school and saying "it's lost" too early
- B. Jumping to a conclusion in a test before reading the whole question
- C. Printing a wrong
-1in your own program - D. Something else (tell us)
Question 2 · Future use(未來應用): Where could you use for + if later?
- A. Checking whether a name is on a list (for example, taking attendance)
- B. Counting how many items meet a condition (for example, the number of passes)
- C. Checking things one by one in a game or in daily life
- D. Something else (tell us)
Step 3: Write your card(寫成你的卡片)
Write three parts in this order: Viewpoint → Case → Conclusion(觀點 → 案例 → 總結). Use your own words, about 100 to 180 words.
Card title (8 to 15 words; state your conclusion; not a question):
Viewpoint (2 to 3 sentences): Your first sentence states what you learned.
Case (3 to 5 sentences): Your own experience. You may add a question or
something you do not agree with.
Conclusion (1 to 2 sentences): One small action for this week,
for example "This week, when I code, I will ...".
🔗 Related notes to write next (2 to 3 directions):
→ Topic: "Title"
→ Topic: "Title"
Check: Can the title be understood on its own? Is the case your own experience, not copied from these notes? Does the conclusion give a concrete action for this week?
中文提示:卡片可以用中文寫(約 150 到 250 字);標題直接講結論,案例要有自己的經驗。
Sample card(示範卡)
Card | You can only say "not found" after checking every cell
Sequential search taught me one thing: before I say "not found", I must check every cell. In the program,
posstarts at -1, and I cannot print -1 until the for loop has finished. If I find the target, I can break. If I don't, I only know at the very end.Last week I looked for my student card at home. It was not in the first pocket of my school bag, so I told my mum I had lost it. It was in the last pocket. I made the same mistake in my first program: I put the
elsethat prints -1 inside the for loop, so it printed -1 as soon as the first cell was wrong. I also wonder: with ten thousand lockers, searching from the start every time seems slow. There must be a faster way.This week, before I run a search program, I will check that the line printing -1 is outside the for loop.
🔗 Related notes:
→ Search methods: "Sorted data can be searched faster with binary search"
→ Debugging habits: "Trace small data by hand before trusting the output"
→ Daily life: "Decide a search order first so you never check the same place twice"