Example 1: for + if · Sequential Search(循序搜尋)

Learning goals(學習目標)

  1. Use a for loop to visit every cell, from index 0 to the last one.
  2. Use an if statement to check whether data[i] is the target.
  3. Know what to print when the target is not found: -1.

0. Real-life scene: guess first(生活情境:先猜一猜)

Real-life scene: ten lockers numbered 0 to 9. A student opens them one by one from locker 0. 35, 52, 68 and 12 are not 47. Locker 4 holds 47, so the student stops. Lockers 5 to 9 stay closed.

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 / 說明
474data[4] is 47
52152 appears 3 times; we want the first one
99-1None of the 10 cells is 99

2. Diagrams(圖解)

2.1 The flow: for walks, if checks

Flowchart: pos starts at -1 and i at 0. While i is less than 10, check whether data[i] equals target. If yes, set pos to i and break. If no, i++ and check the next cell. If all 10 cells are checked, pos is still -1. Finally print pos.

2.2 Trace: searching for 47(追蹤)

Trace of sequential search for 47: at i = 0 to 3 the values 35, 52, 68 and 12 are not 47; at i = 4 the value is 47, so pos = 4.

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] = target puts 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 count for 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: n integer 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: n integers

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] and maxIndex = 0.
  • Should you compare with > or >=? Look at Sample 2: which 9 should you keep?

Self-check(自我檢查)

  1. Why does pos start at -1 and not 0?
  2. If you remove break; and input 52, what is printed? Why?
  3. 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 break at 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 -1 in 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, pos starts 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 else that 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"

Built with LogoFlowershow