Algorithm Design (I)

Master the fundamentals of algorithmic thinking and problem-solving

算法設計 (一)

掌握算法思維和問題解決的基礎知識

Learning Objectives

  • Dry run a set of steps to grasp its purpose and output
  • Define the meaning of algorithm, and represent algorithms in pseudocode and program flowchart
  • Define and use simple data types in solving a problem
  • Use various data types such as integer, real, character and Boolean
  • Understand Boolean logic (AND, OR, NOT) and use truth tables
  • Select different data types to solve various problems and understand the merits of each data type
  • Design and construct standard algorithms related to basic control structures
  • Grasp how to use basic control structures such as sequence, selection (binary-way and multi-way) and iteration

學習目標

  • 演練一組步驟以掌握其目的和輸出
  • 定義算法的含義,並用偽代碼和程序流程圖表示算法
  • 定義和使用簡單的數據類型來解決問題
  • 使用各種數據類型,如整數、實數、字符和布爾值
  • 理解布爾邏輯(AND、OR、NOT)並使用真值表
  • 選擇不同的數據類型來解決各種問題,並了解每種數據類型的優點
  • 設計和構建與基本控制結構相關的標準算法
  • 掌握如何使用基本控制結構,如序列、選擇(二路和多路)和迭代

Table of Contents

目錄

Algorithm Basics

Learn what algorithms are, how to represent them, and practice dry running

算法基礎

學習什麼是算法,如何表示它們,以及練習演練

Variables

Understand variables, naming rules, and assignment operations

變量

理解變量、命名規則和賦值操作

Data Types

Explore different data types and how to choose the right one

數據類型

探索不同的數據類型以及如何選擇合適的類型

Control Structures

Master sequence, selection, and iteration control structures

控制結構

掌握序列、選擇和迭代控制結構

Selection

Learn about conditional statements and decision-making

選擇

學習條件語句和決策制定

Interactive Quiz

Test your knowledge with 15 comprehensive questions

互動測驗

通過15個綜合問題測試您的知識

Algorithm Basics

What is an Algorithm?

An algorithm is a set of steps for solving a problem in the specified order. We can deduce from an algorithm its use and output step-by-step. This process is called dry running or tracing.

Representing Algorithms

Algorithms can be represented in two main ways:

1. Pseudocode

Pseudocode uses plain language and simple notation to describe the logic of an algorithm without worrying about specific programming syntax.

Algorithm: Calculate BMI
Input: weight (in kg), height (in m)
Output: BMI value

1. Start
2. Read weight
3. Read height
4. BMI ← weight / (height × height)
5. Display BMI
6. End

2. Flowchart

A flowchart uses standardized symbols to represent the flow of an algorithm visually.

Start
↓
Input weight, height
↓
BMI ← weight / (height × height)
↓
Output BMI
↓
End

Common Flowchart Symbols

Symbol Name Purpose
Oval Terminal Start or End of algorithm
Parallelogram Input/Output Read data or display results
Rectangle Process Perform calculations or operations
Diamond Decision Make a choice based on a condition
Arrow Flow line Show direction of flow

Interactive BMI Calculator

算法基礎

什麼是算法?

算法是一組按指定順序解決問題的步驟。我們可以從算法中逐步推斷其用途和輸出。這個過程稱為演練或追蹤。

表示算法

算法可以用兩種主要方式表示:

1. 偽代碼

偽代碼使用簡單的語言和符號來描述算法的邏輯,而不必擔心特定的編程語法。

算法:計算BMI
輸入:體重(公斤),身高(米)
輸出:BMI值

1. 開始
2. 讀取體重
3. 讀取身高
4. BMI ← 體重 / (身高 × 身高)
5. 顯示BMI
6. 結束

2. 流程圖

流程圖使用標準化符號來可視化表示算法的流程。

開始
↓
輸入體重、身高
↓
BMI ← 體重 / (身高 × 身高)
↓
輸出BMI
↓
結束

常見流程圖符號

符號 名稱 用途
橢圓形 終端 算法的開始或結束
平行四邊形 輸入/輸出 讀取數據或顯示結果
矩形 處理 執行計算或操作
菱形 決策 根據條件做出選擇
箭頭 流線 顯示流程方向

互動BMI計算器

Try the BMI Calculator

試用BMI計算器

Variables

What is a Variable?

A variable is a named storage location in computer memory that can hold a value. Think of it as a labeled box where you can store and retrieve data.

Variable Naming Rules

  • Must start with a letter or underscore (_)
  • Can contain letters, numbers, and underscores
  • Cannot use reserved keywords (e.g., if, then, else)
  • Should be descriptive and meaningful
  • Case-sensitive (age and Age are different)

Assignment Statement

The assignment operator (←) assigns a value to a variable:

variable ← value

Examples:
age ← 15
name ← "John"
total ← price × quantity
counter ← counter + 1

Arithmetic Operators

Operator Operation Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
× Multiplication 5 × 3 15
/ Division 6 / 3 2
MOD Modulus (remainder) 7 MOD 3 1
DIV Integer division 7 DIV 3 2

Variable Swapping Algorithm

To swap the values of two variables, we need a temporary variable:

Algorithm: Swap two variables

1. temp ← a
2. a ← b
3. b ← temp

變量

什麼是變量?

變量是計算機內存中的命名存儲位置,可以保存值。把它想像成一個標有標籤的盒子,您可以在其中存儲和檢索數據。

變量命名規則

  • 必須以字母或下劃線(_)開頭
  • 可以包含字母、數字和下劃線
  • 不能使用保留關鍵字(例如,if、then、else)
  • 應該具有描述性和意義
  • 區分大小寫(age和Age是不同的)

賦值語句

賦值運算符(←)將值分配給變量:

變量 ← 值

示例:
年齡 ← 15
名字 ← "John"
總計 ← 價格 × 數量
計數器 ← 計數器 + 1

算術運算符

運算符 操作 示例 結果
+ 加法 5 + 3 8
- 減法 5 - 3 2
× 乘法 5 × 3 15
/ 除法 6 / 3 2
MOD 取模(餘數) 7 MOD 3 1
DIV 整數除法 7 DIV 3 2

變量交換算法

要交換兩個變量的值,我們需要一個臨時變量:

算法:交換兩個變量

1. 臨時 ← a
2. a ← b
3. b ← 臨時

Variable Swapping Simulator

變量交換模擬器

Data Types

What are Data Types?

A data type defines the kind of data a variable can store and the operations that can be performed on it.

Common Data Types

數據類型

什麼是數據類型?

數據類型定義了變量可以存儲的數據類型以及可以對其執行的操作。

常見數據類型

Integer

Whole Numbers

Examples: -5, 0, 42, 1000

Use for: Counting, indexing, quantities

Range: Typically -2,147,483,648 to 2,147,483,647

整數

整數

示例:-5, 0, 42, 1000

用於:計數、索引、數量

範圍:通常為-2,147,483,648至2,147,483,647

Real / Float

Decimal Numbers

Examples: 3.14, -0.5, 2.718

Use for: Measurements, scientific calculations, currency

Precision: Approximately 6-7 decimal places

實數 / 浮點數

小數

示例:3.14, -0.5, 2.718

用於:測量、科學計算、貨幣

精度:大約6-7位小數

Character

Single Character

Examples: 'A', 'z', '5', '@'

Use for: Single letters, symbols, digits

Storage: 1 byte (ASCII) or 2 bytes (Unicode)

字符

單個字符

示例:'A', 'z', '5', '@'

用於:單個字母、符號、數字

存儲:1字節(ASCII)或2字節(Unicode)

String

Text Data

Examples: "Hello", "John Smith", "12345"

Use for: Names, addresses, text messages

Note: Sequence of characters

字符串

文本數據

示例:"Hello", "John Smith", "12345"

用於:姓名、地址、文本消息

注意:字符序列

Boolean

True or False

Values: True, False

Use for: Flags, conditions, logical operations

Storage: 1 bit (but usually 1 byte)

布爾值

真或假

值:True, False

用於:標誌、條件、邏輯操作

存儲:1位(但通常為1字節)

Choosing the Right Data Type

Selecting the appropriate data type is crucial for:

  • Memory efficiency: Use the smallest type that fits your needs
  • Accuracy: Use Real for precise calculations
  • Functionality: Some operations only work with specific types
  • Readability: Makes code easier to understand

Variable Analysis Table

Example: Student Management System

Variable Data Type Reason Example Value
studentID Integer Unique whole number identifier 20231001
studentName String Text data for full name "Chan Tai Man"
grade Character Single letter grade 'A'
gpa Real Decimal precision needed 3.75
isPassed Boolean True/False status True

選擇正確的數據類型

選擇適當的數據類型對於以下方面至關重要:

  • 內存效率:使用適合您需求的最小類型
  • 準確性:使用實數進行精確計算
  • 功能性:某些操作僅適用於特定類型
  • 可讀性:使代碼更易於理解

變量分析表

示例:學生管理系統

變量 數據類型 原因 示例值
學生ID 整數 唯一的整數標識符 20231001
學生姓名 字符串 全名的文本數據 "陳大文"
等級 字符 單個字母等級 'A'
平均績點 實數 需要小數精度 3.75
是否通過 布爾值 真/假狀態 True

Basic Control Structures

Three Types of Control Structures

Computer algorithms use three fundamental control structures:

1. Sequence

Instructions are executed one after another in order.

Step 1
↓
Step 2
↓
Step 3

2. Selection

Choose different paths based on a condition.

if condition then
    do action A
else
    do action B
end if

3. Iteration (Repetition)

Repeat a set of instructions multiple times.

while condition do
    repeat these actions
end while

The IPO Cycle

Most algorithms follow the Input-Process-Output pattern:

Input Data
↓
Process Data
↓
Output Results

Example: Calculate Average of Three Numbers

Algorithm: Calculate Average

1. Input num1, num2, num3
2. sum ← num1 + num2 + num3
3. average ← sum / 3
4. Output average

基本控制結構

三種類型的控制結構

計算機算法使用三種基本控制結構:

1. 序列

指令按順序一個接一個地執行。

步驟1
↓
步驟2
↓
步驟3

2. 選擇

根據條件選擇不同的路徑。

如果 條件 那麼
    執行操作A
否則
    執行操作B
結束如果

3. 迭代(重複)

多次重複一組指令。

當 條件 時執行
    重複這些操作
結束當

IPO循環

大多數算法遵循輸入-處理-輸出模式:

輸入數據
↓
處理數據
↓
輸出結果

示例:計算三個數字的平均值

算法:計算平均值

1. 輸入 數字1, 數字2, 數字3
2. 總和 ← 數字1 + 數字2 + 數字3
3. 平均值 ← 總和 / 3
4. 輸出 平均值

Average Calculator

平均值計算器

Selection Control Structure

Boolean Expressions

Selection uses Boolean expressions that evaluate to True or False.

Relational Operators

Operator Meaning Example Result
= Equal to 5 = 5 True
≠ Not equal to 5 ≠ 3 True
< Less than 3 < 5 True
> Greater than 5 > 3 True
≤ Less than or equal 5 ≤ 5 True
≥ Greater than or equal 5 ≥ 3 True

Binary-Way Selection

if...then Statement

if score ≥ 60 then
    display "Pass"
end if

if...then...else Statement

if score ≥ 60 then
    display "Pass"
else
    display "Fail"
end if

Multi-Way Selection

Nested if Statements

if score ≥ 90 then
    grade ← 'A'
else
    if score ≥ 80 then
        grade ← 'B'
    else
        if score ≥ 70 then
            grade ← 'C'
        else
            grade ← 'F'
        end if
    end if
end if

if...elseif Statement

if score ≥ 90 then
    grade ← 'A'
elseif score ≥ 80 then
    grade ← 'B'
elseif score ≥ 70 then
    grade ← 'C'
else
    grade ← 'F'
end if

Boolean Logic

Operator Description Example
AND Both conditions must be true (age ≥ 18) AND (hasLicense = True)
OR At least one condition must be true (day = "Saturday") OR (day = "Sunday")
NOT Reverses the condition NOT (isRaining = True)

Importance of Indentation

Proper indentation makes code structure clear and prevents logic errors. Each nested level should be indented consistently (usually 4 spaces).

選擇控制結構

布爾表達式

選擇使用布爾表達式,其結果為True或False。

關係運算符

運算符 含義 示例 結果
= 等於 5 = 5 True
≠ 不等於 5 ≠ 3 True
< 小於 3 < 5 True
> 大於 5 > 3 True
≤ 小於或等於 5 ≤ 5 True
≥ 大於或等於 5 ≥ 3 True

二路選擇

if...then語句

如果 分數 ≥ 60 那麼
    顯示 "及格"
結束如果

if...then...else語句

如果 分數 ≥ 60 那麼
    顯示 "及格"
否則
    顯示 "不及格"
結束如果

多路選擇

嵌套if語句

如果 分數 ≥ 90 那麼
    等級 ← 'A'
否則
    如果 分數 ≥ 80 那麼
        等級 ← 'B'
    否則
        如果 分數 ≥ 70 那麼
            等級 ← 'C'
        否則
            等級 ← 'F'
        結束如果
    結束如果
結束如果

if...elseif語句

如果 分數 ≥ 90 那麼
    等級 ← 'A'
否則如果 分數 ≥ 80 那麼
    等級 ← 'B'
否則如果 分數 ≥ 70 那麼
    等級 ← 'C'
否則
    等級 ← 'F'
結束如果

布爾邏輯

運算符 描述 示例
AND 兩個條件都必須為真 (年齡 ≥ 18) AND (有駕照 = True)
OR 至少一個條件必須為真 (日期 = "星期六") OR (日期 = "星期日")
NOT 反轉條件 NOT (下雨 = True)

縮進的重要性

正確的縮進使代碼結構清晰,並防止邏輯錯誤。每個嵌套級別都應該一致地縮進(通常為4個空格)。

Grade Calculator

成績計算器

Interactive Quiz

Test your understanding of Algorithm Design concepts!

互動測驗

測試您對算法設計概念的理解!

Flashcards

Click on any card to flip it and reveal the definition!

閃卡

點擊任何卡片以翻轉並顯示定義!

made with 由以下製作