编程 Programming for iGCSE Computer Science.
在这一章中,你将学习如何使用计算机程序来完成任务。你将学习编程的基本概念,包括变量、常量、输入和输出、顺序、选择、循环等。
In this chapter, you will learn how to use computer programs to accomplish tasks. You will learn basic programming concepts, including variables, constants, input and output, sequencing, selection, loops, and more.
变量 (Variables): 程序中用来存储可以改变的值的名称。Names used in programs to store values that can change.
常量 (Constants): 程序中存储固定值的名称,值在程序运行时不会改变。Names used in programs to store fixed values that do not change while the program is running.
输入 (Input): 从键盘输入的数据。Data entered from the keyboard.
输出 (Output): 显示在屏幕上的结果。Results displayed on the screen.
顺序 (Sequence): 任务步骤的顺序。The order of task steps.
选择 (Selection): 根据条件选择程序的执行路径。Selecting the execution path of a program based on conditions.
循环 (Iteration): 重复执行程序中的步骤。Repeating the steps in a program.
整数 (Integer): 正数或负数的整数。A positive or negative integer. eg; 5, 6 etc.
实数 (Real): 带小数部分的数字。Numbers with decimal parts. eg. 35.3 , 99.10 etc.
字符 (Char): 单个字符。A single character. eg: 'S', 'A' etc.
字符串 (String): 由多个字符组成的文本。A text consisting of multiple characters. eg: "America", "Nepal"
布尔值 (Boolean): 只有两个值的变量,TRUE(真)或 FALSE(假)。A variable with only two values, TRUE or FALSE.
在程序中,输入和输出是非常重要的。每个输入都需要一个提示,告诉用户需要输入什么。输出结果时也需要解释结果的消息。 Input and Output
In a program, input and output are very important. Every input needs a prompt to tell the user what to enter. Output also needs a message to explain the result.
顺序结构 (Sequence): 按照特定的顺序执行。
选择结构 (Selection): 使用 IF 语句来决定执行哪个部分。
循环结构 (Iteration): 使用 FOR、WHILE 等语句来重复执行代码。
Control Structure
Sequence: Execute in a specific order.
Selection: Use IF statement to decide which part to execute.
Iteration: Use FOR, WHILE and other statements to execute code repeatedly.
Use of Variables and Constants
Variables are named data stores that can hold values that change during program execution. It's important to give meaningful names to variables for better understanding.
Constants are similar to variables but hold values that do not change during execution. They should also have meaningful names, often highlighted using capital letters or specific naming conventions.
Input and Output
Programs require input from users, often through prompts that specify what data is needed. The output is the information displayed back to the user, which should include messages explaining the results.
Sequence
Sequence refers to the specific order in which instructions are executed. The correct sequence is crucial, as an incorrect order can lead to errors and unexpected results.
Selection (Including Nesting)
Selection allows the program to choose different paths of execution based on conditions. This is often implemented using IF statements. Nesting occurs when an IF statement is placed inside another IF statement, allowing for more complex decision-making.
Iteration
Iteration enables the repetition of a set of instructions. There are different types of loops:
Count-controlled loops (like FOR loops) run a specific number of times.
Condition-controlled loops (like WHILE loops) run as long as a given condition is true.
Totalling and Counting
Totalling involves summing a series of values, while counting tracks the number of occurrences of a specific event or value. These are standard methods used in programming to process data efficiently.
String Handling
String handling involves managing text data. Common operations include finding the length of a string, extracting substrings, and converting strings to either uppercase or lowercase.
Operators (Arithmetic, Logical, and Boolean)
Arithmetic operators perform mathematical calculations (e.g., addition, subtraction).
Logical operators evaluate conditions and return true or false (e.g., AND, OR).
Boolean operators work with Boolean values, helping in decision-making processes.
Procedures and Functions
Procedures are blocks of code that perform specific tasks and can be reused throughout the program. They may take parameters, which are inputs provided to the procedure.
Functions are similar but specifically return a value after execution.
Understanding the difference between local variables (which are accessible only within a procedure or function) and global variables (which can be accessed throughout the program) is essential.
Library routines are pre-written code snippets or functions that can be used to perform common tasks, saving time and effort.
Creating a Maintainable Program
Writing maintainable code involves organizing and documenting your program well. This helps others (and yourself) to understand, modify, and debug the code in the future. Good practices include using meaningful variable names, commenting on complex sections, and structuring the code logically.
Integer
An integer is a data type that represents whole numbers, which can be positive or negative. It is used for counting and mathematical calculations.
Real
Real numbers include both whole numbers and numbers with fractional parts (decimals). This data type is useful for precise calculations that require decimal values.
Char
A character (Char) is a data type that represents a single character, such as a letter or a symbol. It is often used for storing individual characters in strings.
String
A string is a data type that represents a sequence of characters. Strings can include letters, digits, and other symbols and are used to handle textual data.
Boolean
The Boolean data type can hold one of two values: TRUE or FALSE. It is commonly used in decision-making processes within programs.
Writing Algorithms and Programs for Input and Output
Input and output statements are crucial for interacting with users. Programs must be designed to take input from users (like numbers or text) and provide output (results or messages) back to them.
Prompting the User for Input
To ensure users know what data to provide, prompts are used. These are messages displayed to the user before input is requested, guiding them on what to enter.
Displaying Output with Messages
When displaying results, it is important to provide context. This means including messages that explain what the output represents, making it clear and understandable for the user.
One-Dimensional and Two-Dimensional Arrays
One-Dimensional Arrays: These are simple lists that store a collection of values of the same type. Each value can be accessed using a single index. For example, an array could hold a list of test scores.
Two-Dimensional Arrays: These are more complex structures that can be thought of as a table with rows and columns. Each value in a two-dimensional array requires two indexes to access. For instance, a two-dimensional array could be used to store a grid of student grades across different subjects.
Use of Indexes
Indexes are numerical values used to identify the position of elements within an array. In most programming languages, array indexing starts at zero. For example, in a one-dimensional array scores, scores[0] accesses the first element, while in a two-dimensional array grades, grades[0][1] accesses the element in the first row and second column.
Iteration for Reading from and Writing to Arrays
Iteration is commonly used to process arrays, allowing programmers to read from or write to each element systematically. For example, a loop can be used to go through each element of a one-dimensional array, performing operations like summing values or modifying them.
In a two-dimensional array, nested loops are often used. The outer loop iterates through each row, while the inner loop iterates through each column within that row. This structure allows for efficient reading and writing of data in a grid format.
数组是一种数据结构,用于存储多个值。可以是一维或二维数组。
An array is a data structure used to store multiple values. It can be one-dimensional or two-dimensional.
A Database of employee attendance records in a two-dimensional array, the first column of the array contains the employee IDs, and the second column contains the total hours worked for the month. Pseudocode allows the user to input the employee ID and hours worked for 20 employees. After all data has been entered, the program should output each employee's ID along with their total hours worked.
// Declare the array to hold student names and grades
DECLARE Students[1:30, 1:2] // Column 1 for names, Column 2 for grades
DECLARE Count : INTEGER
Count = 1
REPEAT
OUTPUT "Enter the name of student ", Count, ": "
INPUT Students[Count, 1] // Input student name
OUTPUT "Enter the grade for ", Students[Count, 1], ": "
INPUT Students[Count, 2] // Input student grade
Count = Count + 1
UNTIL Count > 30
// Output all student names and their grades
FOR Count = 1 TO 30
OUTPUT "Student: ", Students[Count, 1], " - Grade: ", Students[Count, 2]
NEXT Count
Pseudocode to store the details of 20 cars in a two-dimensional array, also display the details
// Declare the array for car details
DECLARE Cars[1:20, 1:2] // Column 1 for car models, Column 2 for rental prices
DECLARE Count : INTEGER
Count = 1
REPEAT
OUTPUT "Enter the car model for car ", Count, ": "
INPUT Cars[Count, 1] // Input car model
OUTPUT "Enter the rental price per day for ", Cars[Count, 1], ": "
INPUT Cars[Count, 2] // Input rental price
Count = Count + 1
UNTIL Count > 20
// Output all car models and their rental prices
FOR Count = 1 TO 20
OUTPUT "Car Model: ", Cars[Count, 1], " - Price per Day: $", Cars[Count, 2]
NEXT Count
Sequence
Sequence refers to the specific order in which instructions in a program are executed. The correct sequence is essential because each step must be performed in a logical order to achieve the desired outcome. A mistake in the sequence can lead to incorrect results or errors.
Selection (IF Statements)
Selection allows a program to choose between different paths based on certain conditions. This is typically implemented using IF statements. An IF statement evaluates a condition and executes a specific block of code if the condition is true. If the condition is false, the program can either skip the block or execute an alternative block of code using an ELSE statement. This enables decision-making within the program.
Iteration (FOR Loops, WHILE Loops)
Iteration involves repeating a set of instructions multiple times. There are different types of loops used for iteration:
FOR loops: These loops are used when the number of iterations is known beforehand. A FOR loop iterates a specific number of times, typically defined by a counter variable.
WHILE loops: These loops continue to execute as long as a specified condition remains true. WHILE loops are useful when the number of iterations is not known in advance and depends on dynamic conditions.
These control structures are fundamental to programming, allowing for organized and efficient code execution, decision-making, and repetition of tasks.
Length of Strings
The length of a string refers to the number of characters it contains. This includes letters, digits, spaces, and punctuation. Knowing the length of a string is important for various operations, such as validation and formatting.
Substring Extraction
Substring extraction involves obtaining a portion of a string. This operation allows programmers to isolate specific segments of a string for further processing or analysis. For instance, extracting a username from an email address.
Converting Strings to Upper and Lower Case
String manipulation often requires changing the case of characters. Converting strings to upper case means transforming all characters in the string to their uppercase versions (e.g., "hello" becomes "HELLO"). Conversely, converting to lower case changes all characters to lowercase (e.g., "HELLO" becomes "hello"). These conversions are useful for standardizing input for comparison or display purposes.
Opening and Closing Files
File handling in programming involves managing the reading and writing of data to files. To work with a file, it must first be opened. This process allocates resources and prepares the file for reading or writing. Once the operations are complete, the file should be closed to free up resources and ensure that all changes are saved properly.
Reading from and Writing to Data and Text Files
Reading from files allows programs to access data stored in files, which can be used for processing or analysis. This involves using specific commands to retrieve the information.
Writing to files enables programs to save data or results generated during execution. This can be done in various formats, including text files, where data is stored in a human-readable format.
处理数据文件,包括打开、关闭、读取和写入文件。Handling data files, including opening, closing, reading, and writing files.
变量 (Variable): 存储可变值的名称。The variable value to store a value which could be changed.
常量 (Constant): 存储固定值的名称。The namespace where you can hold a value which can not change in the program.
输入 (Input): 从用户获取的数据。Data obtained from the user.
输出 (Output): 显示给用户的结果。The results are displayed to the user (as the result of a process) .
顺序 (Sequence): 执行步骤的顺序。The order in which the steps are executed.
选择 (Selection): 决定执行哪个路径的过程。The process of deciding which path to execute.
循环 (Iteration): 重复执行某些代码的过程。The process of repeatedly executing some code.
数组 (Array): 用于存储多个相同类型的值的集合。A collection used to store multiple values of the same type.
文件 (File): 存储数据的地方,用于输入和输出。A place where data is stored in the secondary storage device, used for input and output.
Variable 变量
Constant 常量
Input 输入
Output 输出
Sequence 顺序
Selection 选择
Iteration 循环
Array 数组
File 文件
Below is a summary of the numeric functions, string functions, logical operators, and arithmetic operators used in pseudocode
MOD
Returns the remainder of a division.
返回除法的余数。
MOD(10, 3) returns 1
10 ÷ 3 = 3 with a remainder of 1.
10 ÷ 3 = 3,余数为 1。
DIV
Returns the quotient (whole number part) of a division.
返回除法的整数部分。
DIV(10, 3) returns 3
10 ÷ 3 = 3 (integer part).
10 ÷ 3 = 3(整数部分)。
ROUND
Rounds a number to a specified number of decimal places.
将数字四舍五入到指定的小数位数。
ROUND(6.97354, 2) returns 6.97
Rounds 6.97354 to 2 decimal places.
将 6.97354 四舍五入到小数点后两位。
RANDOM
Generates a random number between 0 and 1.
生成一个介于 0 和 1 之间的随机数。
RANDOM() returns 0.12345
Generates a random number.
生成一个随机数。
Function
Description
Example
Explanation
LENGTH
Returns the number of characters in a string.
返回字符串的长度。
LENGTH("Computer") returns 8
The string "Computer" has 8 characters.
字符串 "Computer" 有 8 个字符。
SUBSTRING
Extracts a portion of a string.
提取字符串的一部分。
SUBSTRING("Computer", 1, 3) returns "Com"
Extracts 3 characters starting from position 1.
从位置 1 开始提取 3 个字符。
UCASE
Converts a string to uppercase.
将字符串转换为大写。
UCASE("Computer") returns "COMPUTER"
Converts all letters to uppercase.
将所有字母转换为大写。
LCASE
Converts a string to lowercase.
将字符串转换为小写。
LCASE("Computer") returns "computer"
Converts all letters to lowercase.
将所有字母转换为小写。
Operator
Description
Example
Explanation
+
Adds two numbers.
加法。
5 + 3 returns 8
Adds 5 and 3.
5 加 3。
-
Subtracts one number from another.
减法。
5 - 3 returns 2
Subtracts 3 from 5.
5 减 3。
*
Multiplies two numbers.
乘法。
5 * 3 returns 15
Multiplies 5 and 3.
5 乘以 3。
/
Divides one number by another.
除法。
10 / 2 returns 5
Divides 10 by 2.
10 除以 2。
^
Raises a number to the power of another.
幂运算。
2 ^ 3 returns 8
2 raised to the power of 3.
2 的 3 次方。
Operator
Description
Example
Explanation
>
Checks if one value is greater than another.
检查一个值是否大于另一个值。
5 > 3 returns TRUE
5 is greater than 3.
5 大于 3。
<
Checks if one value is less than another.
检查一个值是否小于另一个值。
3 < 5 returns TRUE
3 is less than 5.
3 小于 5。
=
Checks if two values are equal.
检查两个值是否相等。
5 = 5 returns TRUE
5 is equal to 5.
5 等于 5。
>=
Checks if one value is greater than or equal to another.
检查一个值是否大于或等于另一个值。
5 >= 5 returns TRUE
5 is greater than or equal to 5.
5 大于或等于 5。
<=
Checks if one value is less than or equal to another.
检查一个值是否小于或等于另一个值。
3 <= 5 returns TRUE
3 is less than or equal to 5.
3 小于或等于 5。
<>
Checks if two values are not equal.
检查两个值是否不相等。
5 <> 3 returns TRUE
5 is not equal to 3.
5 不等于 3。
Operator
Description
Example
Explanation
AND
Returns TRUE if both conditions are true.
如果两个条件都为真,则返回 TRUE。
(5 > 3) AND (2 < 4) returns TRUE
Both conditions are true.
两个条件都为真。
OR
Returns TRUE if at least one condition is true.
如果至少一个条件为真,则返回 TRUE。
(5 > 3) OR (2 > 4) returns TRUE
At least one condition is true.
至少一个条件为真。
NOT
Reverses the logical value.
反转逻辑值。
NOT (5 > 3) returns FALSE
Reverses TRUE to FALSE.
将 TRUE 反转为 FALSE。
Loop Type
Description
Example
Explanation
FOR
Repeats a block of code a fixed number of times.
重复执行代码块固定次数。
FOR Counter ← 1 TO 10
Repeats the loop 10 times.
循环重复 10 次。
REPEAT...UNTIL
Repeats a block of code until a condition is met.
重复执行代码块直到满足条件。
REPEAT ... UNTIL Number = 0
Repeats until Number is 0.
重复直到 Number 为 0。
Statement
Description
Example
Explanation
IF...THEN
Executes a block of code if a condition is true.
如果条件为真,则执行代码块。
IF Age > 17 THEN OUTPUT "Adult"
Outputs "Adult" if Age is greater than 17.
如果 Age 大于 17,则输出 "Adult"。
IF...THEN...ELSE
Executes one block of code if a condition is true, and another if it is false.
如果条件为真,则执行一个代码块,否则执行另一个代码块。
IF Age >= 18 THEN OUTPUT "Adult" ELSE OUTPUT "Child"
Outputs "Adult" if Age is 18 or older, otherwise outputs "Child".
如果 Age 大于或等于 18,则输出 "Adult",否则输出 "Child"。
Type
Description
Example
Explanation
Procedure
A block of code that performs a task but does not return a value.
执行任务但不返回值的代码块。
PROCEDURE PrintStars
Defines a procedure to print stars.
定义一个打印星号的过程。
Function
A block of code that performs a task and returns a value.
执行任务并返回值的代码块。
FUNCTION Square(Number)
Defines a function to return the square of a number.
定义一个返回数字平方的函数。
数值函数:用于处理数字,如取余 (MOD)、取整 (DIV)、四舍五入 (ROUND) 和生成随机数 (RANDOM)。
字符串函数:用于处理字符串,如获取长度 (LENGTH)、提取子字符串 (SUBSTRING)、转换为大写 (UCASE) 和小写 (LCASE)。
算术运算符:用于数学计算,如加法 (+)、减法 (-)、乘法 (*)、除法 (/) 和幂运算 (^)。
逻辑运算符:用于比较值,如大于 (>)、小于 (<)、等于 (=) 和不等于 (<>)。
布尔运算符:用于组合逻辑条件,如与 (AND)、或 (OR) 和非 (NOT)。
迭代:用于重复执行代码块,如 FOR 循环和 REPEAT...UNTIL 循环。
选择:用于根据条件执行不同的代码块,如 IF...THEN 和 IF...THEN...ELSE。
过程和函数:用于封装代码块,过程 (PROCEDURE) 不返回值,函数 (FUNCTION) 返回值。
Pseudocode Examples
Pseudocode for declaring variables and constants with different data types:
DECLARE Age : INTEGER // Integer (whole number)
DECLARE Price : REAL // Real number (decimal)
DECLARE Grade : CHAR // Single character
DECLARE Name : STRING // String (text)
DECLARE IsPassed : BOOLEAN // Boolean (True or False)
CONSTANT PI ← 3.14 // Constant (cannot change)
Count-controlled Loop (FOR Loop)
FOR Counter FROM 1 TO 10
OUTPUT Counter
NEXT Counter
Pre-condition Loop (WHILE Loop)
DECLARE TotalWeight : REAL
TotalWeight ← 0
WHILE TotalWeight < 100
OUTPUT "Enter weight:"
INPUT Weight
TotalWeight ← TotalWeight + Weight
END WHILE
Post-condition Loop (REPEAT...UNTIL Loop)
DECLARE NumberOfItems : INTEGER
NumberOfItems ← 0
REPEAT
NumberOfItems ← NumberOfItems + 1
OUTPUT "Item added."
UNTIL NumberOfItems > 10
IF Statement
DECLARE Age : INTEGER
OUTPUT "Enter your age:"
INPUT Age
IF Age >= 18 THEN
OUTPUT "You are an adult."
ELSE
OUTPUT "You are a child."
END IF
CASE Statement
DECLARE Choice : STRING
OUTPUT "Enter your choice (A, B, C):"
INPUT Choice
CASE OF Choice
"A" : OUTPUT "You chose A."
"B" : OUTPUT "You chose B."
"C" : OUTPUT "You chose C."
OTHERWISE : OUTPUT "Invalid choice."
END CASE
Counting
DECLARE Counter : INTEGER
Counter ← 0
FOR I FROM 1 TO 5
Counter ← Counter + 1
NEXT I
OUTPUT "Total count: ", Counter
Totalling
DECLARE Total, Number : REAL
Total ← 0
FOR I FROM 1 TO 5
OUTPUT "Enter a number:"
INPUT Number
Total ← Total + Number
NEXT I
OUTPUT "Total sum: ", Total
Length of a String
DECLARE Name : STRING
Name ← "Computer Science"
OUTPUT "Length of string: ", LENGTH(Name)
Substring
DECLARE Name : STRING
Name ← "Computer Science"
OUTPUT "Substring: ", SUBSTRING(Name, 10, 7) // Extracts "Science"
Convert to Uppercase
DECLARE Name : STRING
Name ← "Computer Science"
OUTPUT "Uppercase: ", UCASE(Name)
Convert to Lowercase
DECLARE Name : STRING
Name ← "Computer Science"
OUTPUT "Lowercase: ", LCASE(Name)
MOD and DIV
DECLARE Value1, Value2 : INTEGER
Value1 ← 10 MOD 3 // Remainder of 10 divided by 3
Value2 ← 10 DIV 3 // Quotient of 10 divided by 3
OUTPUT "Remainder: ", Value1
OUTPUT "Quotient: ", Value2
ROUND
DECLARE Value : REAL
Value ← ROUND(6.97354, 2) // Rounds to 2 decimal places
OUTPUT "Rounded value: ", Value
RANDOM
DECLARE RandomValue : REAL
RandomValue ← RANDOM() // Generates a random number between 0 and 1
OUTPUT "Random value: ", RandomValue
Function to Convert Celsius to Fahrenheit
FUNCTION CelsiusToFahrenheit(Celsius : REAL) RETURNS REAL
RETURN (Celsius * 1.8) + 32
END FUNCTION
DECLARE Temperature : REAL
Temperature ← CelsiusToFahrenheit(25)
OUTPUT "Temperature in Fahrenheit: ", Temperature
Procedure to Display Stars
PROCEDURE DisplayStars(Number : INTEGER)
FOR I FROM 1 TO Number
OUTPUT "*"
NEXT I
END PROCEDURE
CALL DisplayStars(5) // Displays *****
One-Dimensional Array
DECLARE MyList : ARRAY[0:9] OF INTEGER
FOR I FROM 0 TO 9
OUTPUT "Enter a number:"
INPUT MyList[I]
NEXT I
OUTPUT "First element: ", MyList[0]
Two-Dimensional Array
DECLARE MyTable : ARRAY[0:2, 0:2] OF INTEGER
FOR Row FROM 0 TO 2
FOR Column FROM 0 TO 2
OUTPUT "Enter a number:"
INPUT MyTable[Row, Column]
NEXT Column
NEXT Row
OUTPUT "Element at [1,1]: ", MyTable[1,1]
Write to a File
DECLARE TextLine : STRING
DECLARE MyFile : STRING
MyFile ← "MyText.txt"
OPEN MyFile FOR WRITE
OUTPUT "Enter a line of text:"
INPUT TextLine
WRITEFILE, TextLine
CLOSEFILE(MyFile)
Read from a File
DECLARE TextLine : STRING
DECLARE MyFile : STRING
MyFile ← "MyText.txt"
OPEN MyFile FOR READ
READFILE, TextLine
OUTPUT "File content: ", TextLine
CLOSEFILE(MyFile)
Nested IF and FOR Loop
FOR I FROM 1 TO 10
IF I MOD 2 = 0 THEN
OUTPUT I, " is even."
ELSE
OUTPUT I, " is odd."
END IF
NEXT I
Example of a Maintainable Program
// This program calculates the area of a rectangle
DECLARE Length, Width, Area : REAL
// Function to calculate area
FUNCTION CalculateArea(L : REAL, W : REAL) RETURNS REAL
RETURN L * W
END FUNCTION
// Main program
OUTPUT "Enter length:"
INPUT Length
OUTPUT "Enter width:"
INPUT Width
Area ← CalculateArea(Length, Width)
OUTPUT "Area of rectangle: ", Area
// This program calculates the area of a rectangle
DECLARE Length, Width, Area : REAL
// Function to calculate area
FUNCTION CalculateArea(L : REAL, W : REAL) RETURNS REAL
RETURN L * W
END FUNCTION
// Main program
OUTPUT "Enter length:"
INPUT Length
OUTPUT "Enter width:"
INPUT Width
Area ← CalculateArea(Length, Width)
OUTPUT "Area of rectangle: ", Area
1. 0478/21/M/J/24 - 2024
2. 0478/21/M/J/24
3. 0478/21/M/J/24
3. 0478/21/M/J/24
400. 0478/21/O/N/22
401. 0478/21/O/N/22
500 . 0478/21/O/N/22