Skip to content · ⁨본문 바로가기⁩
Subjects · ⁨과목⁩
  • 1 Style and layout · ⁨스타일 및 레이아웃⁩
    1.1

    키워드와 대문자/소문자

    English

    Pseudocode 伪代码 is the language Cambridge writes algorithms 算法 in. It is not a real programming language — no computer runs it — but the exam marks it as if it were, so the form matters.

    Every keyword 关键字 is written in upper case: IF, REPEAT, PROCEDURE, OUTPUT.

    • Write IF, never if or If.
    • A keyword can never be used as a name of your own: you may not call a variable FOR.

    Common mistakes

    • Lower-case keywords. The mark scheme expects upper case.
    • Inventing keywords. Only the words in this handout are in the syllabus.
    한국어

    가상 언어(pseudocode)는 케임브리지에서 알고리즘을 쓰는 언어입니다. 이는 실제 프로그래밍 언어가 아닙니다 — 어떤 컴퓨터도 이를 실행하지 않습니다 — 하지만 시험에서는 실제로 사용하는 것처럼 점수를 부여하므로, 표기 형식이 중요합니다.

    모든 키워드는 대문자로 적습니다: IF, REPEAT, PROCEDURE, OUTPUT.

    DECLARE Count : INTEGER
    Count ← 3
    IF Count > 0
      THEN
        OUTPUT "Ready"
    ENDIF
    
    • IF를 쓰십시오. if나 If는 절대 쓰지 마십시오.
    • 키워드는 자신의 이름으로 절대 사용할 수 없습니다: 변수를 FOR라고 부를 수 없습니다.

    Common mistakes

    • 소문자 키워드. 채점 기준은 대문자를 기대합니다.
    • 임의로 만든 키워드. 이 워크시트에 있는 단어만 교정 과정에 포함됩니다.
    1.2

    식별자(Identifier)

    English

    An identifier 标识符 is the name you give a variable 变量, a constant 常量, a procedure 过程 or a function 函数.

    Four rules, all from the syllabus:

    • It must start with a capital letter: Count, not count.
    • It may hold only letters and digits — no spaces, no punctuation.
    • It is not case-sensitive 不区分大小写, so Count and COUNT are the same name. Pick one spelling and keep it.
    • Make it mean something. NumberOfPlayers earns the reader's time; N does not.

    Common mistakes

    • count ← 0 — a lower-case start. 0478 requires the capital.
    • Number of players — spaces are not allowed inside a name.
    한국어

    식별자는 변수, 상수, 프로시저 또는 함수에 붙이는 이름입니다. 또는 함수.

    DECLARE NumberOfPlayers : INTEGER
    NumberOfPlayers ← 4
    OUTPUT NumberOfPlayers
    

    네 가지 규칙, 모두 교육과정에서 유래했습니다:

    • 대문자로 시작해야 합니다: Count, count가 아닙니다.
    • 알파벳과 숫자만 포함될 수 있습니다—공백이나 문장 부호는 불가합니다.
    • 의미를 갖도록 하십시오. Count는 독자의 시간을 아껴주지만, COUNT는 그렇지 않습니다. 철자를 하나만 선택하여 일관되게 사용하세요.
    • 의미를 부여하십시오. NumberOfPlayers은 독자의 시간을 얻지만, N은 그렇지 않습니다.

    Common mistakes

    • count ← 0 — 소문자 시작입니다. 0478은 대문자를 요구합니다.
    • Number of players — 이름 내부에 공백을 허용하지 않습니다.
    1.3

    주석 및 줄바꿈

    English

    A comment 注释 starts with // and runs to the end of the line. It is for the human reader; the algorithm ignores it.

    Indentation 缩进 shows which statements are inside a structure. The syllabus asks for four spaces per level, with one exception you must know:

    • THEN and ELSE are indented two spaces from their IF.
    • The statements under them are indented four.
    • ENDIF lines up with its own IF.

    Common mistakes

    • Putting THEN on the IF line. That is the A-Level 9618 layout — see topic 11.
    • No indentation at all. A marker has to see the structure to award the structure marks.
    한국어

    주석은 //으로 시작하여该行의 끝까지 이어집니다. 이는 인간 독자를 위한 것이며, 알고리즘은 이를 무시합니다.

    // Swap the values of X and Y
    DECLARE X, Y, Temp : INTEGER
    X ← 1
    Y ← 2
    Temp ← X   // temporarily store X
    X ← Y
    Y ← Temp
    OUTPUT X, " ", Y
    

    줄바꿈은 어떤 문장이 구조 내부에 있는지를 나타냅니다. 과목 요건은 각 단계마다 네 개의 공백을 사용하도록 요구하며, 반드시 알아야 할 예외가 하나 있습니다:

    DECLARE X, Y : INTEGER
    X ← 7
    Y ← 3
    IF X > Y
      THEN
        OUTPUT "X is bigger"
      ELSE
        OUTPUT "Y is bigger or equal"
    ENDIF
    
    • THEN과 ELSE은 their IF로부터 두 개의 공백으로 줄바꿈됩니다.
    • 그 아래에 있는 문장들은 네 개의 공백으로 줄바꿈됩니다.
    • ENDIF 줄은 자체 IF와 정렬됩니다.

    Common mistakes

    • THEN을 IF 줄에 배치함. 이것이 A-Level 9618 레이아웃입니다 — 주제 11을 참조하십시오.
    • 줄바꿈이 전혀 없습니다. 채점자는 구조를 볼 수 있어야만 구조 점수를 부여할 수 있습니다.
  • 2 Variables, constants and types · ⁨변수, 상수 및 타입⁩
    2.1

    다섯 가지 데이터 유형

    English

    0478 pseudocode has exactly five data types 数据类型. Learn the list — naming a type that is not on it loses the mark.

    Type Holds Example
    INTEGER a whole number 整数 42, -7
    REAL a number with a decimal part 小数 3.14, -0.5
    CHAR a single character 单个字符 'A'
    STRING a sequence of characters 字符串 "Hello"
    BOOLEAN TRUE or FALSE 布尔值 TRUE
    • A STRING is written in double quotes, a CHAR in single quotes.
    • TRUE and FALSE are keywords, so they are upper case and carry no quotes.

    Common mistakes

    • Writing FLOAT, DOUBLE or BOOL. Those are real languages, not this syllabus.
    • 'Hello' for a string — single quotes hold one character only.
    한국어

    0478 가짜 코드는 정확히 다섯 가지 데이터 타입을 가집니다. 목록을 외우십시오 — 해당 목록에 없는类型을 언급하면 점수가 박탈됩니다. 그 위에 없는 것은 점수를 잃습니다.

    유형 보유 값 예시
    INTEGER 정수 42, -7
    REAL 소수 부분이 있는 수 3.14, -0.5
    CHAR 단일 문자 'A'
    STRING 문자열 "Hello"
    BOOLEAN TRUE 또는 FALSE TRUE
    DECLARE Age : INTEGER
    DECLARE Price : REAL
    DECLARE Grade : CHAR
    DECLARE Name : STRING
    DECLARE Passed : BOOLEAN
    Age ← 17
    Price ← 2.50
    Grade ← 'A'
    Name ← "Mei"
    Passed ← TRUE
    OUTPUT Name, " is ", Age, " and passed: ", Passed
    
    • STRING는 이중 따옴표로, CHAR은 단일 따옴표로 표기합니다.
    • TRUE와 FALSE은 키워드이므로 대문자로 표기하며, 따옴표를 붙이지 않습니다.

    Common mistakes

    • FLOAT, DOUBLE 또는 BOOL을 작성하는 경우: 이들은 실제 프로그래밍 언어이며, 본 과목의 수료 요건에 포함되지 않습니다.
    • 문자열에는 'Hello'를 사용하며, 단일 따옴표는 한 문자만 저장할 수 있습니다.
    2.2

    DECLARE(선언)

    English

    DECLARE names a variable 变量 and fixes its type before you use it.

    Several names of one type go on a single line, separated by commas:

    • Declare a variable before its first use, near the top of the algorithm.
    • A variable keeps its type for the whole algorithm — an INTEGER never holds "Mei".

    Common mistakes

    • Leaving out the colon: DECLARE Counter INTEGER.
    • Using a variable that was never declared. The exam expects the declaration.
    한국어

    DECLARE는 변수를 명시하고 사용 전에 그 유형을 고정합니다.

    DECLARE <identifier> : <data type>
    
    DECLARE Counter : INTEGER
    DECLARE TotalToPay : REAL
    Counter ← 1
    TotalToPay ← 19.99
    OUTPUT "Item ", Counter, " costs ", TotalToPay
    

    동일한 유형의 여러 변수를 하나의 줄에 나열하며, 쉼표로 구분합니다:

    DECLARE Length, Width, Area : INTEGER
    Length ← 6
    Width ← 4
    Area ← Length * Width
    OUTPUT "Area = ", Area
    
    • 변수는 첫 번째 사용 전에, 알고리즘 상단에 선언하십시오.
    • 변수는 전체 알고리즘 동안 동일한 유형을 유지하므로, INTEGER가 "Mei"을 저장할 수는 없습니다.

    Common mistakes

    • 값은 반드시 리터럴이어야 합니다 — 숫자, 문자열, DECLARE Counter INTEGER — 절대 계산 결과나 다른 변수가 될 수 없습니다.
    • 상수는 나중에 새로운 값을 부여받을 수 없습니다. 그것이 상수의 존재 이유입니다.
    2.3

    CONSTANT(상수)

    English

    A constant 常量 is a value that is fixed for the whole algorithm — a tax rate, π, the size of a class. Naming it once means a change is made in one place.

    • In 0478 the arrow is used, exactly as for an assignment.
    • The value must be a literal 字面量 — a number, a string, TRUE — never a calculation and never another variable.
    • A constant can never be given a new value later. That is the whole point of it.

    Common mistakes

    • CONSTANT TaxRate = 0.20. The = form is the A-Level 9618 spelling — see topic 11.
    • Assigning to a constant further down the algorithm.
    한국어

    상수는 알고리즘 전체에 걸쳐 값이 고정되는 것—세금율, 원주율 π, 교실 인원 등. 한 번만 명명하면 변경 시 한 곳에서만 수정하면 됩니다.

    CONSTANT <identifier> ← <value>
    
    CONSTANT TaxRate ← 0.20
    DECLARE Price, Tax : REAL
    Price ← 50.00
    Tax ← Price * TaxRate
    OUTPUT "Tax to pay: ", Tax
    
    • 0478에서는 화살표가 사용되며, 이는 대입 연산자와 동일합니다.
    • 값은 리터럴이어야 합니다—숫자, 문자열, TRUE 등—수식일 수 없습니다. 현재 상자에 들어있는 값으로 오른쪽을 계산한 후 결과를 다시 저장하십시오.
    • 상수는 나중에 새로운 값을 할당받을 수 없습니다. 이것이 상수의 핵심 목적입니다.

    Common mistakes

    • CONSTANT TaxRate = 0.20. = 형식은 A-Level 9618 표기법입니다—주제 11을 참고하십시오.
    • 알고리즘 하단에서 상수에 값을 할당하는 것은 허용되지 않습니다.
  • 3 Assignment, input and output · ⁨할당, 입력 및 출력⁩
    3.1

    대입 화살표

    English

    The assignment 赋值 operator is ←, a left-pointing arrow. It means take the value on the right and put it in the box on the left.

    Counter ← Counter + 1 looks impossible as mathematics and is ordinary as an instruction: work out the right-hand side with the value the box holds now, then store the result back.

    • If you cannot type ←, write <-. Both are accepted, here and in the exam.
    • The left side must be a single identifier or one array element. Never a calculation.

    Common mistakes

    • Counter = 0. In pseudocode = is a comparison, not an assignment — and confusing the two is the single commonest syntax error in this paper.
    • Counter + 1 ← Counter. The arrow points at the thing being changed.
    한국어

    대입 연산자는 ←이며, 왼쪽을 향하는 화살표입니다. 오른쪽의 값을 가져와 왼쪽의 상자에放入라는 의미입니다. 오른쪽으로 가져와 왼쪽 상자의 안에 넣으십시오*.

    <identifier> ← <value>
    
    DECLARE Counter : INTEGER
    Counter ← 0
    Counter ← Counter + 1
    Counter ← Counter + 1
    OUTPUT Counter
    

    Counter ← Counter + 1은 수학적으로 불가능해 보이지만, 지시문으로는 일반적입니다: 상자(변수)에 현재 저장된 값을 사용하여 우변을 계산한 후, 그 결과를 다시 저장합니다.

    • ←를 입력할 수 없는 경우, <-을 작성하십시오. 여기 및 시험에서 두 가지 모두 허용됩니다.
    • 좌변은 단일 식별자 또는 배열의 한 요소여야 합니다. 절대 계산식이 될 수 없습니다.

    Common mistakes

    • Counter = 0. 가짜코드에서 =은 할당이 아닌 비교이며, 혼동하기 쉽습니다. 이 두 가지를 혼동하는 것은 이 과목 시험에서 가장 흔한 구문 오류입니다.
    • Counter + 1 ← Counter. 화살표는 변경되는 대상을 가리킵니다.
    3.2

    입력 및 출력

    English

    INPUT reads a value from the user into a variable. OUTPUT displays one or more values.

    • INPUT takes exactly one variable, and that variable must already be declared.
    • OUTPUT takes any number of items separated by commas; they are printed one after another with nothing between them.
    • A literal 字面量 string in an OUTPUT goes in double quotes; a variable does not.

    Prompting the user

    An INPUT on its own shows nothing on screen, so a well-written algorithm prints a prompt 提示 first:

    Common mistakes

    • INPUT "Enter a number", X — the prompt is a separate OUTPUT statement.
    • OUTPUT "Total: " + Total. 0478 joins output items with a comma; + is arithmetic and & belongs to A-Level 9618 (topic 11).
    • Forgetting the quotes: OUTPUT Hello looks for a variable called Hello.
    한국어

    INPUT는 사용자로부터 값을 받아 변수에 저장합니다. OUTPUT은 하나 이상의 값을 표시합니다.

    DECLARE Name : STRING
    DECLARE Age : INTEGER
    INPUT Name
    INPUT Age
    OUTPUT "Hello ", Name
    OUTPUT "Next year you will be ", Age + 1
    
    • INPUT는 정확히 하나의 변수를 필요로 하며, 해당 변수는 이미 선언되어 있어야 합니다.
    • OUTPUT는 콤마로 구분된 여러 항목을受け取을 수 있으며,它们是依次打印,中间没有空格。 서로 사이에 아무것도 없게 순서대로 출력됩니다.
    • OUTPUT의 리터럴 문자열은 이중 인용부호로 감쌌으며, 변수는 그렇지 않습니다.

    사용자 프롬프트

    단독으로 있는 INPUT은 화면에 아무것도 표시하지 않으므로, 잘 작성된 알고리즘은 먼저 프롬프트를 출력합니다. first:

    DECLARE Radius : REAL
    OUTPUT "Enter the radius: "
    INPUT Radius
    OUTPUT "The diameter is ", Radius * 2
    

    Common mistakes

    • INPUT "Enter a number", X — 프롬프트는 별도의 OUTPUT 문장입니다.
    • OUTPUT "Total: " + Total. 0478은 출력 항목들을 쉼표로 연결하며; +은 산술 연산이고, &은 A-Level 9618(주제 11)에 속합니다.
    • 인용부호를 누락한 경우: OUTPUT Hello은 변수 Hello을 찾습니다.
  • 4 Arithmetic and logic · ⁨산술 및 논리⁩
    4.1

    산술 연산자

    English

    Five arithmetic 算术 operators, in the order a calculator uses them.

    Operator Meaning A is 7, B is 2
    + add 加 A + B is 9
    - subtract 减 A - B is 5
    * multiply 乘 A * B is 14
    / divide 除 A / B is 3.5
    ^ raise to a power 幂 A ^ B is 49

    Brackets come first, then ^, then * and /, then + and - — the usual precedence 优先级. Use brackets whenever the reader would have to stop and think.

    Common mistakes

    • Expecting / to give a whole number. 7 / 2 is 3.5, not 3; for a whole number use DIV.
    • Writing A x B or A ÷ B. Use * and /.
    한국어

    연산자가 사용되는 순서대로 5가지 산술 연산자입니다.

    연산자 의미 A이 7일 때, B이 2일 때
    + 더하기 A + B이 9
    - 빼기 A - B이 5
    * 곱하기 A * B이 14
    / 나누기 A / B이 3.5
    ^ 지수 A ^ B이 49
    DECLARE A, B : INTEGER
    A ← 7
    B ← 2
    OUTPUT "Sum: ", A + B
    OUTPUT "Product: ", A * B
    OUTPUT "Quotient: ", A / B
    OUTPUT "Power: ", A ^ B
    

    괄호가 가장 먼저, 그 다음에 ^, 그리고 *과 /,最后是 +과 - — 일반적인 우선순위입니다. . 읽는 사람이 멈춰서 생각해야 할 때마다 괄호를 사용합니다.

    DECLARE Total : REAL
    Total ← (12 + 18) / 2
    OUTPUT "Mean: ", Total
    

    Common mistakes

    • /이 정수를 반환할 것으로 예상함. 7 / 2은 3.5이며, 3가 아님; 정수를 얻으려면 DIV.
    • A x B 또는 A ÷ B을 작성함. *과 /을 사용해야 함.
    4.2

    DIV와 MOD

    English

    Integer division 整数除法 answers two different questions, and 0478 writes each of them as a function 函数, with the two values in brackets.

    • DIV(a, b) — how many whole times b goes into a, the quotient 商.
    • MOD(a, b) — what is left over, the remainder 余数.

    Both take integers, and both return an integer.

    What they are for

    MOD is the standard test for divides exactly, which makes it the way to ask whether a number is even 偶数:

    DIV converts a total into whole units — seconds into minutes, pence into pounds:

    Common mistakes

    • 10 MOD 3. That is the A-Level 9618 form; 0478 uses the function form MOD(10, 3).
    • Mixing the two up. DIV gives the whole part; MOD gives what does not fit.
    한국어

    정수 나눈 결과는 두 가지 다른 질문에 대한 답이며, 0478은 각각 이를 함수 형태로 작성하고, 두 값을 괄호 안에 넣습니다.

    • DIV(a, b) — b이 a을 몇 번 완전하게 나누는지, 즉 **상수(할당값)**입니다.
    • MOD(a, b) — 나머지는 무엇인가, 즉 나머지입니다.
    OUTPUT DIV(10, 3)
    OUTPUT MOD(10, 3)
    OUTPUT DIV(17, 5)
    OUTPUT MOD(17, 5)
    

    두 함수 모두 정수를 입력받으며, 정수를 반환합니다.

    용도

    MOD은 완전 분배 가능 여부를 테스트하는 표준 방식이므로, 이는 한 숫자가 짝수인지 묻는 방법이 됩니다:

    DECLARE Number : INTEGER
    Number ← 12
    IF MOD(Number, 2) = 0
      THEN
        OUTPUT Number, " is even"
      ELSE
        OUTPUT Number, " is odd"
    ENDIF
    

    DIV은 총량을 완전한 단위로 변환합니다 — 초를 분으로, 펜스를 파운드로:

    DECLARE Seconds : INTEGER
    Seconds ← 200
    OUTPUT DIV(Seconds, 60), " minutes and ", MOD(Seconds, 60), " seconds"
    

    Common mistakes

    • 10 MOD 3. 이것이 A-Level 9618의 형식이며; 0478은 함수 형식 MOD(10, 3)을 사용합니다.
    • 두 가지를 혼동함. DIV은 정수 부분을给出; MOD은 맞지 않는 부분을给出.
    4.3

    관계 연산자와 논리 연산자

    English

    A relational operator 关系运算符 compares two values and produces TRUE or FALSE.

    Operator Means
    = is equal to 等于
    <> is not equal to 不等于
    > is greater than 大于
    < is less than 小于
    >= is greater than or equal to 大于等于
    <= is less than or equal to 小于等于

    The three logic operators 逻辑运算符 join conditions:

    • AND — both sides must be TRUE.
    • OR — at least one side must be TRUE.
    • NOT — turns TRUE into FALSE and back.

    Common mistakes

    • <> is the not equal sign here — not !=, which belongs to other languages.
    • IF Age >= 15 AND <= 18. Each side of AND needs its own complete comparison: Age >= 15 AND Age <= 18.
    • Calling these comparison operators in an answer. The syllabus term is relational.
    한국어

    관계 연산자는 두 값을 비교하여 TRUE 또는 FALSE을 생성합니다.

    연산자 의미
    = 은 다음과 같습니다
    <> 다르다 (≠)
    > 보다는 큽니다
    < 보다는 작습니다
    >= 이상입니다
    <= 이하입니다
    DECLARE Mark : INTEGER
    Mark ← 55
    OUTPUT "Pass: ", Mark >= 50
    OUTPUT "Perfect: ", Mark = 100
    OUTPUT "Not zero: ", Mark <> 0
    

    세 가지 논리 연산자는 조건을 결합합니다:

    • AND — 양쪽 모두 TRUE이어야 합니다.
    • OR — 적어도 한 쪽이 TRUE이어야 합니다.
    • NOT — TRUE을 FALSE으로 바꾸고 다시 원래대로 돌립니다.
    DECLARE Age : INTEGER
    DECLARE HasTicket : BOOLEAN
    Age ← 16
    HasTicket ← TRUE
    IF Age >= 15 AND HasTicket = TRUE
      THEN
        OUTPUT "Admitted"
    ENDIF
    IF NOT (Age > 18)
      THEN
        OUTPUT "Still a student rate"
    ENDIF
    

    Common mistakes

    • <>은 여기에서 不等于 부호입니다 — !=이 아닙니다. 이는 다른 언어에 속합니다.
    • IF Age >= 15 AND <= 18. AND의 각 변은 자체 완전한 비교가 필요합니다: Age >= 15 AND Age <= 18.
    • 답변에서 이들을 비교 연산자라고 부름. 과목 명칭은 관계입니다.
  • 5 String operations · ⁨문자열 연산⁩
    5.1

    LENGTH, UCASE 및 LCASE

    English

    0478 publishes four string 字符串 routines and no others. Three of them are here.

    LENGTH(<identifier>) returns how many characters 字符 a string holds — spaces included.

    UCASE(<identifier>) returns the string in upper case 大写, LCASE(<identifier>) in lower case 小写. Neither changes the original 原值 — each hands back a new value.

    That last line still prints Happy: to keep the change you must assign it back.

    Comparing without worrying about case

    UCASE on both sides is the standard way to accept an answer however it was typed:

    Common mistakes

    • Expecting UCASE(Name) to change Name. Assign the result back.
    • LENGTH counts characters, not words. LENGTH("Happy Days") is 10.
    한국어

    0478은 네 가지 문자열 routine만 제공하며, 그 중 세 가지가 여기에 있습니다.

    LENGTH(<identifier>)은 문자열이 포함하는 문자 수를 반환합니다 — 공백 포함.

    OUTPUT LENGTH("Happy Days")
    OUTPUT LENGTH("")
    

    UCASE(<identifier>)은 대문자로 된 문자열을 반환하고, LCASE(<identifier>)은 소문자로 반환합니다. 원본은 변경되지 않으며, 각각 새로운 값을 반환합니다.

    DECLARE Name : STRING
    Name ← "Happy"
    OUTPUT UCASE(Name)
    OUTPUT LCASE(Name)
    OUTPUT Name
    

    마지막 줄은 여전히 Happy을 출력합니다: 변경 사항을 유지하려면 다시 할당해야 합니다.

    DECLARE Name : STRING
    Name ← "Happy"
    Name ← UCASE(Name)
    OUTPUT Name
    

    대소문자를 고려하지 않고 비교하기

    양쪽에 UCASE을 사용하는 것이, 어떻게 입력되었든 답을 수용하는 표준 방법입니다:

    DECLARE Answer : STRING
    Answer ← "yes"
    IF UCASE(Answer) = "YES"
      THEN
        OUTPUT "Accepted"
    ENDIF
    

    Common mistakes

    • UCASE(Name)이 Name을 변경할 것으로 예상함. 결과를 다시 할당해야 함.
    • LENGTH은 단어를 세는 것이 아니라 문자를 세는 것임. LENGTH("Happy Days")은 10입니다.
    5.2

    SUBSTRING

    English

    SUBSTRING(<identifier>, <start>, <length>) pulls a piece out of a string — starting at position start, taking length characters.

    ⚠️ Counting starts at 1, not 0. The first character of "Happy Days" is at position 1.

    Taking one character, and the rest

    LENGTH inside SUBSTRING is what makes the last two lines work for a word of any size — hard-coding 8 would break the moment the word changed.

    Reading a string one character at a time

    Common mistakes

    • Starting at 0. Position 1 is the first character.
    • Reading the third argument as an end position. It is a count — SUBSTRING(W, 2, 3) takes three characters beginning at the second.
    • Asking for more characters than the string has.
    한국어

    SUBSTRING(<identifier>, <start>, <length>)은 문자열에서 일부분을 추출합니다 — 시작 위치는 위치 start, 추출할 문자 수는 length입니다.

    OUTPUT SUBSTRING("Happy Days", 1, 5)
    OUTPUT SUBSTRING("Happy Days", 7, 4)
    

    ⚠️ 카운팅은 1부터 시작하며, 0이 아닙니다. "Happy Days"의 첫 번째 문자는 위치 1에 있습니다.

    한 문자와 나머지 부분 추출하기

    DECLARE Word : STRING
    Word ← "Computer"
    OUTPUT "First letter: ", SUBSTRING(Word, 1, 1)
    OUTPUT "Last letter: ", SUBSTRING(Word, LENGTH(Word), 1)
    OUTPUT "Without the first: ", SUBSTRING(Word, 2, LENGTH(Word) - 1)
    

    LENGTH가 SUBSTRING 내부에 있는 것이 임의의 길이의 단어에 대해 마지막 두 줄이 작동하게 하는 이유입니다— 8을 하드코딩하면 단어가 바뀔 순간 오류가 발생합니다.

    문자를 하나씩 읽기

    DECLARE Word : STRING
    DECLARE Index : INTEGER
    Word ← "Cat"
    FOR Index ← 1 TO LENGTH(Word)
        OUTPUT SUBSTRING(Word, Index, 1)
    NEXT Index
    

    Common mistakes

    • 0부터 시작함. 위치 1이 첫 번째 문자입니다.
    • 세 번째 인자를 종료 위치로 읽음. 이는 카운트입니다 — SUBSTRING(W, 2, 3) 두 번째 위치부터 세 개의 문자를 가져옵니다.
    • 문자열보다 더 많은 문자를 요청함.
  • 6 Selection · ⁨선택(Selection)⁩
    6.1

    IF, THEN, ELSE, ENDIF

    English

    Selection 选择 runs one group of statements or another, depending on a condition 条件.

    Add ELSE for the other case. Exactly one of the two branches 分支 runs — never both, never neither.

    The layout is the one part students lose marks on, so learn it as a shape:

    • IF and its condition on one line, nothing after the condition.
    • THEN and ELSE on their own lines, indented two spaces.
    • The statements indented four.
    • ENDIF back at the column of its IF.

    Nesting 嵌套

    An IF inside an IF handles more than two outcomes. Each one needs its own ENDIF.

    Common mistakes

    • Forgetting ENDIF. Every IF closes, and a missing one is a syntax error 语法错误 the marker will see at a glance.
    • IF Mark >= 50 THEN OUTPUT "Pass" on one line. No such form exists in either syllabus; write the three lines.
    • IF Mark = 50 THEN written as IF Mark ← 50. The arrow assigns; = compares.
    한국어

    Selection 选择 runs one group of statements or another, depending on a condition 条件.

    IF <condition>
      THEN
        <statements>
    ENDIF
    
    DECLARE Mark : INTEGER
    Mark ← 72
    IF Mark >= 50
      THEN
        OUTPUT "Pass"
    ENDIF
    

    Add ELSE for the other case. Exactly one of the two branches 分支 runs — never both, never neither.

    DECLARE Mark : INTEGER
    Mark ← 41
    IF Mark >= 50
      THEN
        OUTPUT "Pass"
      ELSE
        OUTPUT "Fail"
    ENDIF
    

    The layout is the one part students lose marks on, so learn it as a shape:

    • IF and its condition on one line, nothing after the condition.
    • THEN and ELSE on their own lines, indented two spaces.
    • The statements indented four.
    • ENDIF back at the column of its IF.

    Nesting 嵌套

    An IF inside an IF handles more than two outcomes. Each one needs its own ENDIF.

    DECLARE Mark : INTEGER
    Mark ← 85
    IF Mark >= 80
      THEN
        OUTPUT "Distinction"
      ELSE
        IF Mark >= 50
          THEN
            OUTPUT "Pass"
          ELSE
            OUTPUT "Fail"
        ENDIF
    ENDIF
    

    Common mistakes

    • Forgetting ENDIF. Every IF closes, and a missing one is a syntax error 语法错误 the marker will see at a glance.
    • IF Mark >= 50 THEN OUTPUT "Pass" on one line. No such form exists in either syllabus; write the three lines.
    • IF Mark = 50 THEN written as IF Mark ← 50. The arrow assigns; = compares.
    6.2

    CASE OF

    When one variable is tested against several single values, CASE OF says it far more clearly than a stack of nested IFs.

    CASE OF <identifier>
        <value 1> : <statement>
        <value 2> : <statement>
        OTHERWISE <statement>
    ENDCASE
    
    DECLARE Choice : INTEGER
    Choice ← 2
    CASE OF Choice
        1 : OUTPUT "You chose north"
        2 : OUTPUT "You chose south"
        3 : OUTPUT "You chose east"
        4 : OUTPUT "You chose west"
        OTHERWISE OUTPUT "That is not a direction"
    ENDCASE
    
    • Each branch is a value, a colon, then what to do.
    • OTHERWISE catches everything the listed values missed. It is optional, and writing one is good practice — it is what happens when the user types something unexpected.
    • The first matching branch runs, and the rest are skipped.

    A range, and a character

    DECLARE Grade : CHAR
    Grade ← 'B'
    CASE OF Grade
        'A' : OUTPUT "Excellent"
        'B' : OUTPUT "Good"
        'C' : OUTPUT "Satisfactory"
        OTHERWISE OUTPUT "Unclassified"
    ENDCASE
    

    Common mistakes

    • Using CASE OF for a condition. It tests one variable against values; Mark >= 50 needs an IF.
    • Forgetting ENDCASE.
    • Leaving out OTHERWISE and then wondering why an unexpected value does nothing at all.
  • 7 Iteration · ⁨반복(Iteration)⁩
    7.1

    FOR, the counted loop

    English

    Iteration 迭代 repeats statements. Use a FOR loop when you know before you start how many times — a count-controlled 计数控制 loop.

    The counter 计数器 starts at the first value, and the loop runs once for every value up to and including the second. 1 TO 5 runs five times.

    STEP

    STEP changes the size of each jump. A negative step counts down.

    Running totals

    The commonest use: a variable outside the loop that the loop adds to.

    Total ← 0 must sit before the loop. Inside, it would reset on every pass.

    Common mistakes

    • NEXT naming the wrong counter. Nested loops must close in the reverse order they opened: the inner NEXT first.
    • Assuming 1 TO 5 runs four times. Both ends are included.
    • Changing the counter inside the loop. Let FOR own it.
    한국어

    Iteration 迭代 repeats statements. Use a FOR loop when you know before you start how many times — a count-controlled 计数控制 loop.

    FOR <identifier> ← <value1> TO <value2>
        <statements>
    NEXT <identifier>
    
    DECLARE Index : INTEGER
    FOR Index ← 1 TO 5
        OUTPUT "Line ", Index
    NEXT Index
    

    The counter 计数器 starts at the first value, and the loop runs once for every value up to and including the second. 1 TO 5 runs five times.

    STEP

    STEP changes the size of each jump. A negative step counts down.

    DECLARE Index : INTEGER
    FOR Index ← 2 TO 10 STEP 2
        OUTPUT Index
    NEXT Index
    FOR Index ← 3 TO 1 STEP -1
        OUTPUT "Countdown ", Index
    NEXT Index
    

    Running totals

    The commonest use: a variable outside the loop that the loop adds to.

    DECLARE Index, Total : INTEGER
    Total ← 0
    FOR Index ← 1 TO 10
        Total ← Total + Index
    NEXT Index
    OUTPUT "Sum of 1 to 10 is ", Total
    

    Total ← 0 must sit before the loop. Inside, it would reset on every pass.

    Common mistakes

    • NEXT naming the wrong counter. Nested loops must close in the reverse order they opened: the inner NEXT first.
    • Assuming 1 TO 5 runs four times. Both ends are included.
    • Changing the counter inside the loop. Let FOR own it.
    7.2

    WHILE, the pre-condition loop

    English

    A WHILE loop tests before each pass, so it can run zero times. Use it when the number of repeats depends on something that happens while the loop runs.

    Something inside the loop must eventually make the condition false, or the loop never ends — an infinite loop 无限循环.

    Common mistakes

    • Forgetting to change the variable the condition tests, giving an infinite loop.
    • Leaving out DO or ENDWHILE.
    • Using WHILE where the count is known. A FOR says what you mean in one line.
    한국어

    A WHILE loop tests before each pass, so it can run zero times. Use it when the number of repeats depends on something that happens while the loop runs.

    WHILE <condition> DO
        <statements>
    ENDWHILE
    
    DECLARE Total : INTEGER
    Total ← 1
    WHILE Total < 100 DO
        Total ← Total * 2
    ENDWHILE
    OUTPUT "First power of two past 100: ", Total
    

    Something inside the loop must eventually make the condition false, or the loop never ends — an infinite loop 无限循环.

    DECLARE Count : INTEGER
    Count ← 5
    WHILE Count > 0 DO
        OUTPUT Count
        Count ← Count - 1
    ENDWHILE
    OUTPUT "Lift off"
    

    Common mistakes

    • Forgetting to change the variable the condition tests, giving an infinite loop.
    • Leaving out DO or ENDWHILE.
    • Using WHILE where the count is known. A FOR says what you mean in one line.
    7.3

    REPEAT, the post-condition loop

    English

    A REPEAT loop tests after each pass, so it always runs at least once.

    That "at least once" is the reason to choose it: validating 验证 input, where you must ask before you can judge the answer.

    ⚠️ UNTIL states the condition that stops the loop; WHILE states the one that keeps it going. They are opposites, and swapping them is the classic error.

    Tests Runs at least once? Condition means
    FOR a counter no (an empty range runs zero times) —
    WHILE before no keep going while this is true
    REPEAT after yes stop when this becomes true

    Common mistakes

    • Writing UNTIL Number < 100 when you mean UNTIL Number >= 100.
    • Using REPEAT where the body must be able to run zero times.
    • Forgetting that UNTIL ends the structure — there is no ENDREPEAT.
    한국어

    A REPEAT loop tests after each pass, so it always runs at least once.

    REPEAT
        <statements>
    UNTIL <condition>
    

    That "at least once" is the reason to choose it: validating 验证 input, where you must ask before you can judge the answer.

    DECLARE Number : INTEGER
    Number ← 0
    REPEAT
        Number ← Number + 25
        OUTPUT "Trying ", Number
    UNTIL Number >= 100
    OUTPUT "Reached ", Number
    

    ⚠️ UNTIL states the condition that stops the loop; WHILE states the one that keeps it going. They are opposites, and swapping them is the classic error.

    Tests Runs at least once? Condition means
    FOR a counter no (an empty range runs zero times) —
    WHILE before no keep going while this is true
    REPEAT after yes stop when this becomes true

    Common mistakes

    • Writing UNTIL Number < 100 when you mean UNTIL Number >= 100.
    • Using REPEAT where the body must be able to run zero times.
    • Forgetting that UNTIL ends the structure — there is no ENDREPEAT.
  • 8 Arrays · ⁨배열(Data arrays)⁩
    8.1

    One-dimensional arrays

    English

    An array 数组 holds many values of one type under one name. Each value sits at an index 下标.

    • The bounds 边界 are written lower:upper, and both are included — [1:3] has three elements 元素.
    • Cambridge arrays normally start at 1, not 0.
    • Every element has the same type, fixed by OF.

    Filling and reading with a FOR loop

    An array and a counted loop belong together: the counter is the index.

    Finding the largest

    Start Largest at the first element, never at 0 — with negative data, 0 would win and the answer would be wrong.

    Common mistakes

    • Reading Scores[6] from an array declared [1:5]. That is out of bounds 越界.
    • Writing Scores(3). Arrays use square brackets; round brackets call a function.
    • Declaring [1:5] and then looping 0 TO 4.
    한국어

    An array 数组 holds many values of one type under one name. Each value sits at an index 下标.

    DECLARE <identifier> : ARRAY[<lower>:<upper>] OF <data type>
    
    DECLARE Names : ARRAY[1:3] OF STRING
    Names[1] ← "Mei"
    Names[2] ← "Sam"
    Names[3] ← "Ana"
    OUTPUT Names[2]
    
    • The bounds 边界 are written lower:upper, and both are included — [1:3] has three elements 元素.
    • Cambridge arrays normally start at 1, not 0.
    • Every element has the same type, fixed by OF.

    Filling and reading with a FOR loop

    An array and a counted loop belong together: the counter is the index.

    DECLARE Scores : ARRAY[1:5] OF INTEGER
    DECLARE Index, Total : INTEGER
    FOR Index ← 1 TO 5
        Scores[Index] ← Index * 10
    NEXT Index
    Total ← 0
    FOR Index ← 1 TO 5
        Total ← Total + Scores[Index]
    NEXT Index
    OUTPUT "Total: ", Total
    OUTPUT "Mean: ", Total / 5
    

    Finding the largest

    DECLARE Scores : ARRAY[1:5] OF INTEGER
    DECLARE Index, Largest : INTEGER
    Scores[1] ← 42
    Scores[2] ← 17
    Scores[3] ← 93
    Scores[4] ← 8
    Scores[5] ← 55
    Largest ← Scores[1]
    FOR Index ← 2 TO 5
        IF Scores[Index] > Largest
          THEN
            Largest ← Scores[Index]
        ENDIF
    NEXT Index
    OUTPUT "Largest: ", Largest
    

    Start Largest at the first element, never at 0 — with negative data, 0 would win and the answer would be wrong.

    Common mistakes

    • Reading Scores[6] from an array declared [1:5]. That is out of bounds 越界.
    • Writing Scores(3). Arrays use square brackets; round brackets call a function.
    • Declaring [1:5] and then looping 0 TO 4.
    8.2

    Two-dimensional arrays

    English

    A 2-D array 二维数组 is a table: rows and columns, two indexes.

    The first index is the row 行, the second the column 列.

    Nested loops walk a table

    One loop per dimension 维度. The inner loop finishes a whole row before the outer moves on.

    ⚠️ The inner NEXT closes the inner counter. NEXT Row before NEXT Col crosses the loops over and is nonsense — a marker spots it instantly.

    Common mistakes

    • Swapping row and column. Grid[2,3] is row 2, column 3.
    • Grid[Row][Col]. Cambridge writes one pair of brackets with a comma inside.
    • Crossing the NEXT lines over, as above.
    한국어

    A 2-D array 二维数组 is a table: rows and columns, two indexes.

    DECLARE <identifier> : ARRAY[<lower1>:<upper1>, <lower2>:<upper2>] OF <data type>
    
    DECLARE Grid : ARRAY[1:2, 1:3] OF INTEGER
    Grid[1,1] ← 1
    Grid[1,2] ← 2
    Grid[1,3] ← 3
    Grid[2,1] ← 4
    Grid[2,2] ← 5
    Grid[2,3] ← 6
    OUTPUT Grid[2,3]
    

    The first index is the row 行, the second the column 列.

    Nested loops walk a table

    One loop per dimension 维度. The inner loop finishes a whole row before the outer moves on.

    DECLARE Grid : ARRAY[1:2, 1:3] OF INTEGER
    DECLARE Row, Col : INTEGER
    FOR Row ← 1 TO 2
        FOR Col ← 1 TO 3
            Grid[Row, Col] ← Row * Col
        NEXT Col
    NEXT Row
    FOR Row ← 1 TO 2
        FOR Col ← 1 TO 3
            OUTPUT "Grid[", Row, ",", Col, "] = ", Grid[Row, Col]
        NEXT Col
    NEXT Row
    

    ⚠️ The inner NEXT closes the inner counter. NEXT Row before NEXT Col crosses the loops over and is nonsense — a marker spots it instantly.

    Common mistakes

    • Swapping row and column. Grid[2,3] is row 2, column 3.
    • Grid[Row][Col]. Cambridge writes one pair of brackets with a comma inside.
    • Crossing the NEXT lines over, as above.
  • 9 Procedures and functions · ⁨절차 및 함수⁩
    9.1

    PROCEDURE 및 CALL

    English

    A procedure 过程 is a named block of statements. Writing one once and calling it from several places is decomposition 分解 — the idea the whole of paper 2 rests on.

    A procedure is called by name, with the keyword CALL:

    • The definition 定义 does nothing on its own. Only CALL runs it.
    • Control returns to the line after the CALL when the procedure ends.
    • A procedure does not give a value back. If you need one, you want a function.

    Common mistakes

    • Writing DefaultLine on its own to run it. 0478 requires CALL.
    • Leaving out ENDPROCEDURE.
    • Expecting the procedure's own variables to exist outside it.
    한국어

    절차(procedure) 는 이름이 붙은 명령어 블록입니다. 한 번 작성하여 여러 곳에서 호출하는 것은 분해(decomposition) 입니다 — 이는 전체 2 문서의 기반이 되는 개념입니다.

    PROCEDURE <identifier>
        <statements>
    ENDPROCEDURE
    

    절程序는 키워드 CALL를 사용하여 이름으로 호출됩니다:

    PROCEDURE DefaultLine
        OUTPUT "------------------------------"
    ENDPROCEDURE
    
    CALL DefaultLine
    OUTPUT "Report"
    CALL DefaultLine
    
    • 정의만으로는 아무런 작용을 하지 않습니다. 오직 CALL이 실행할 수 있습니다.
    • CALL를 누락함。
    • 프로시저 자체의 변수가 외부에 존재할 것으로 기대함。

    Common mistakes

    • DefaultLine만 작성하여 실행합니다. 0478은 CALL을 필요로 합니다.
    • ENDPROCEDURE을 생략함.
    • 프로시저 내부의 변수가 외부에 존재한다고 가정함.
    9.2

    함수 FUNCTION 및 리턴 RETURN

    English

    A function 函数 is a procedure that hands a value back. It is written where that value is needed — inside an OUTPUT, on the right of an assignment, inside a condition.

    • RETURNS <data type> on the header says what type comes back. It is not optional.
    • RETURN ends the function immediately — nothing after it runs.
    • A function is never called with CALL; it is used wherever its value belongs.

    A function inside a condition

    Common mistakes

    • CALL SumSquare(10, 20) — that throws the answer away.
    • A function with no RETURN on some path. Every route out must return a value.
    • Leaving RETURNS INTEGER off the header.
    한국어

    함수는 값을 반환하는 프로시저입니다. 해당 값이 필요한 곳에 서술됩니다 — OUTPUT 내부, 대입 식의 우변, 조건식 내부 등.

    FUNCTION <identifier>(<parameters>) RETURNS <data type>
        <statements>
        RETURN <value>
    ENDFUNCTION
    
    FUNCTION SumSquare(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER
        RETURN Number1 * Number1 + Number2 * Number2
    ENDFUNCTION
    
    OUTPUT "Sum of squares = ", SumSquare(10, 20)
    
    • RETURNS <data type> — 답변을 버림。
    • 어떤 경로에서는 RETURN가 없는 함수。모든 출구 경로/value가返回值。
    • 헤더에서 CALL를 누락함。

    조건식 내의 함수

    FUNCTION IsEven(Number : INTEGER) RETURNS BOOLEAN
        RETURN MOD(Number, 2) = 0
    ENDFUNCTION
    
    DECLARE Index : INTEGER
    FOR Index ← 1 TO 6
        IF IsEven(Index)
          THEN
            OUTPUT Index, " is even"
        ENDIF
    NEXT Index
    

    Common mistakes

    • CALL SumSquare(10, 20) — 결과를 버림.
    • 어떤 경로에서나 RETURN이 없는 함수. 모든 출구에서는 반드시 값을 반환해야 함.
    • 헤더에 RETURNS INTEGER을 명시하지 않음.
    9.3

    매개변수 Parameters

    English

    A parameter 参数 is a value a procedure or function is given when it is called. Each one carries its own type.

    Several parameters are separated by commas, and the order at the call must match the order in the definition:

    ⚠️ In 0478 every parameter is passed by value 传值: the procedure works on a copy, so changing it inside changes nothing outside. To get a value back, use a FUNCTION and RETURN it. (A-Level 9618 adds BYREF for the other behaviour — topic 11.)

    Common mistakes

    • PROCEDURE Line(Size) with no type.
    • Calling with the arguments in the wrong order — Greet(2, "Mei") is a type error.
    • Expecting a procedure to change the variable you passed in. In 0478 it cannot.
    한국어

    매개변수는 프로시저 또는 함수가 호출될 때 전달되는 값입니다. 각 매개변수는 고유의 타입을 가집니다.

    PROCEDURE Line(Size : INTEGER)
        DECLARE Index : INTEGER
        FOR Index ← 1 TO Size
            OUTPUT "-"
        NEXT Index
    ENDPROCEDURE
    
    CALL Line(5)
    CALL Line(20)
    

    여러 매개변수는 쉼표로 구분하며, 호출 시 순서는 정의 시 순서와 일치해야 함: 정의 내에서:

    PROCEDURE Greet(Name : STRING, Times : INTEGER)
        DECLARE Index : INTEGER
        FOR Index ← 1 TO Times
            OUTPUT "Hello ", Name
        NEXT Index
    ENDPROCEDURE
    
    CALL Greet("Mei", 2)
    CALL Greet("Sam", 1)
    

    내부에서 변경해도 외부에는 영향을 주지 않음. 값을 다시 얻으려면 0478을 사용함. 일반적으로 줄 수를 알 수 없으므로 파일 끝까지 읽음 — 이것이 FUNCTION 함수가 보고하는 내용임. RETURN 이다. (A-Level 9618는 다른 행동에 BYREF를 추가함 — 주제 11.)

    FUNCTION Doubled(Number : INTEGER) RETURNS INTEGER
        RETURN Number * 2
    ENDFUNCTION
    
    DECLARE Value : INTEGER
    Value ← 7
    Value ← Doubled(Value)
    OUTPUT Value
    

    Common mistakes

    • PROCEDURE Line(Size)는 타입이 없음.
    • 인수의 순서를 잘못 지정하여 호출 — Greet(2, "Mei")는 타입 오류임.
    • Procedure가 전달한 변수를 변경할 것으로 예상함. 0478에서는 불가능함.
  • 10 File handling · ⁨파일 처리⁩
    10.1

    파일에 쓰기

    English

    A file 文件 keeps data after the program ends. 0478 uses four commands, and every one names the file it works on.

    Three file modes 文件模式:

    Mode What it does
    WRITE start a new file — anything already there is lost
    APPEND add to the end of what is there 追加
    READ read from the start
    • One WRITEFILE writes one line.
    • CLOSEFILE is not optional. An unclosed file can lose the data still waiting to be written, and that is a stock exam answer.

    Common mistakes

    • FOR WRITE when you meant FOR APPEND, which silently destroys the old contents.
    • Forgetting CLOSEFILE.
    • Opening a file that is already open.
    한국어

    파일은 프로그램 종료 후에도 데이터를 유지함. 0478은 네 가지 명령어를 사용하며, 모든 명령어가 작업하는 파일의 이름을 명시함.

    OPENFILE <file identifier> FOR WRITE
    WRITEFILE <file identifier>, <data>
    CLOSEFILE <file identifier>
    
    OPENFILE "names.txt" FOR WRITE
    WRITEFILE "names.txt", "Mei"
    WRITEFILE "names.txt", "Sam"
    CLOSEFILE "names.txt"
    OUTPUT "Saved"
    

    세 가지 파일 모드:

    모드 기능
    WRITE 새 파일 시작 — 기존 데이터는 모두 삭제됨
    APPEND 기존 데이터 끝에 추가
    READ 시작 지점에서 읽기
    OPENFILE "log.txt" FOR WRITE
    WRITEFILE "log.txt", "first"
    CLOSEFILE "log.txt"
    OPENFILE "log.txt" FOR APPEND
    WRITEFILE "log.txt", "second"
    CLOSEFILE "log.txt"
    OUTPUT "Both lines saved"
    
    • 하나의 WRITEFILE는 한 줄만 작성함.
    • CLOSEFILE는 선택 사항이 아님. 닫지 않은 파일은 아직 쓰기 대기 중인 데이터를 잃을 수 있으며, 이는 표준 시험 답안임. 쓰여야 함, 그리고 그것은 표준 시험 답안임.

    Common mistakes

    • FOR WRITE를 FOR APPEND 대신 사용할 때, 이는 구내 용역을 조용히 파괴함.
    • CLOSEFILE를 누락하는 것.
    • 이미 열려 있는 파일을 다시 열기.
    10.2

    파일 끝까지 읽기

    English

    READFILE takes one line into a variable. The variable must be declared first.

    Normally you do not know how many lines there are, so you read until the end of the file — which is what the EOF function reports.

    EOF("names.txt") is TRUE once every line has been read, so WHILE NOT EOF(...) means while there is still something to read.

    Counting while reading

    Common mistakes

    • A WHILE EOF(...) loop — that runs only when there is nothing left. You want NOT.
    • Reading past the end because the loop has no EOF guard.
    • Opening FOR READ a file that was never written.
    한국어

    READFILE는 한 줄을 변수에 저장함. 변수는 먼저 선언되어야 함.

    OPENFILE <file identifier> FOR READ
    READFILE <file identifier>, <variable>
    CLOSEFILE <file identifier>
    

    일반적으로 줄의 개수를 알 수 없으므로, 파일 끝까지 읽습니다. file — 즉, EOF 함수가 보고하는 내용입니다.

    OPENFILE "names.txt" FOR WRITE
    WRITEFILE "names.txt", "Mei"
    WRITEFILE "names.txt", "Sam"
    WRITEFILE "names.txt", "Ana"
    CLOSEFILE "names.txt"
    
    DECLARE Line : STRING
    OPENFILE "names.txt" FOR READ
    WHILE NOT EOF("names.txt") DO
        READFILE "names.txt", Line
        OUTPUT Line
    ENDWHILE
    CLOSEFILE "names.txt"
    

    EOF("names.txt")은 모든 줄이读完될 때마다 TRUE 한 번씩 증가하므로, WHILE NOT EOF(...)은 다음을 의미합니다. 아직 읽을 내용이 남아 있을 때입니다.

    읽기 중 세기

    OPENFILE "marks.txt" FOR WRITE
    WRITEFILE "marks.txt", 40
    WRITEFILE "marks.txt", 65
    WRITEFILE "marks.txt", 88
    CLOSEFILE "marks.txt"
    
    DECLARE Mark, Count, Total : INTEGER
    Count ← 0
    Total ← 0
    OPENFILE "marks.txt" FOR READ
    WHILE NOT EOF("marks.txt") DO
        READFILE "marks.txt", Mark
        Count ← Count + 1
        Total ← Total + Mark
    ENDWHILE
    CLOSEFILE "marks.txt"
    OUTPUT Count, " marks, mean ", Total / Count
    

    Common mistakes

    • ⟨WHILE EOF(...)⟩ 루프 — 남은 것이 없을 때만 실행됩니다. NOT이 필요합니다.
    • 루프에 EOF 보호 장치가 없어 끝을 넘어 읽음.
    • 절대 쓰인 적 없는 FOR READ 파일을 열림.
  • 11 A-Level 9618: what changes · ⁨A-Level 9618: 변경 사항⁩
    11.1

    Layout and operators

    English

    Cambridge publishes two pseudocode specifications, and they disagree. Everything in topics 1-10 is IGCSE 0478. A-Level 9618 changes the details below — and a student who studies both loses marks by writing one in the other's paper.

    IGCSE 0478 A-Level 9618
    THEN on its own line, indented 2 on the IF line
    constants CONSTANT Pi ← 3.142 CONSTANT Pi = 3.142
    DIV / MOD functions: DIV(10, 3) operators: 10 DIV 3
    joining strings commas in OUTPUT the & operator
    identifiers must start with a capital mixed case allowed 混合大小写
    NEXT must name its counter good practice
    ROUND, RANDOM() both published neither exists

    This is the 0478 form, and it runs here:

    The 9618 form of the same algorithm is written like this — note THEN on the IF line, = in the CONSTANT, and MOD between its two values:

    ⚠️ Which one is right depends only on which paper you are sitting. Neither is a mistake; each is a mistake in the other's exam. The playground on this page runs the 0478 rules, so a 9618 construct is refused with a message naming the syllabus it belongs to — which is a quick way to check your own habits.

    Common mistakes

    • Writing THEN on the IF line in an 0478 answer, because that is what a textbook or a website showed. It is the single commonest cross-syllabus slip.
    • 10 MOD 3 in 0478. There it is MOD(10, 3).
    • ROUND(3.14159, 2) in a 9618 answer. 9618 has no ROUND at all.
    한국어

    Cambridge publishes two pseudocode specifications, and they disagree. Everything in topics 1-10 is IGCSE 0478. A-Level 9618 changes the details below — and a student who studies both loses marks by writing one in the other's paper.

    IGCSE 0478 A-Level 9618
    THEN on its own line, indented 2 on the IF line
    constants CONSTANT Pi ← 3.142 CONSTANT Pi = 3.142
    DIV / MOD functions: DIV(10, 3) operators: 10 DIV 3
    joining strings commas in OUTPUT the & operator
    identifiers must start with a capital mixed case allowed 混合大小写
    NEXT must name its counter good practice
    ROUND, RANDOM() both published neither exists

    This is the 0478 form, and it runs here:

    DECLARE Total : REAL
    CONSTANT Rate ← 0.5
    Total ← 10
    IF MOD(7, 2) = 1
      THEN
        OUTPUT "Odd, half rate ", Total * Rate
    ENDIF
    

    The 9618 form of the same algorithm is written like this — note THEN on the IF line, = in the CONSTANT, and MOD between its two values:

    DECLARE Total : REAL
    CONSTANT Rate = 0.5
    Total ← 10
    IF 7 MOD 2 = 1 THEN
        OUTPUT "Odd, half rate " & STR(Total * Rate)
    ENDIF
    

    ⚠️ Which one is right depends only on which paper you are sitting. Neither is a mistake; each is a mistake in the other's exam. The playground on this page runs the 0478 rules, so a 9618 construct is refused with a message naming the syllabus it belongs to — which is a quick way to check your own habits.

    Common mistakes

    • Writing THEN on the IF line in an 0478 answer, because that is what a textbook or a website showed. It is the single commonest cross-syllabus slip.
    • 10 MOD 3 in 0478. There it is MOD(10, 3).
    • ROUND(3.14159, 2) in a 9618 answer. 9618 has no ROUND at all.
    11.2

    Parameters: BYVAL and BYREF

    English

    0478 passes every parameter by value 传值 (topic 9). 9618 lets you choose, and says so in the header.

    • BYVAL — the procedure gets a copy. Changing it changes nothing outside. This is the default when neither word is written.
    • BYREF — the procedure works on the caller's own variable 引用, so a change is visible after the call.

    This is 9618 only. It does not run here, and it is not accepted in an 0478 answer:

    The 0478 way to get a value back

    Use a FUNCTION and assign what it returns. This is the whole of the 0478 answer, and it runs:

    Common mistakes

    • Writing BYREF in an 0478 answer. The keyword is not in that syllabus.
    • Expecting a plain 9618 parameter to behave like BYREF. Without the word it is BYVAL.
    한국어

    0478 passes every parameter by value 传值 (topic 9). 9618 lets you choose, and says so in the header.

    • BYVAL — the procedure gets a copy. Changing it changes nothing outside. This is the default when neither word is written.
    • BYREF — the procedure works on the caller's own variable 引用, so a change is visible after the call.

    This is 9618 only. It does not run here, and it is not accepted in an 0478 answer:

    PROCEDURE Increase(BYREF Value : INTEGER)
        Value ← Value + 1
    ENDPROCEDURE
    
    DECLARE Count : INTEGER
    Count ← 5
    CALL Increase(Count)
    OUTPUT Count      // prints 6
    

    The 0478 way to get a value back

    Use a FUNCTION and assign what it returns. This is the whole of the 0478 answer, and it runs:

    FUNCTION Increased(Value : INTEGER) RETURNS INTEGER
        RETURN Value + 1
    ENDFUNCTION
    
    DECLARE Count : INTEGER
    Count ← 5
    Count ← Increased(Count)
    OUTPUT Count
    

    Common mistakes

    • Writing BYREF in an 0478 answer. The keyword is not in that syllabus.
    • Expecting a plain 9618 parameter to behave like BYREF. Without the word it is BYVAL.
    11.3

    Records and other types

    English

    9618 has data structures 数据结构 that 0478 does not. You will meet them only at A-Level, and none of them runs under the 0478 rules of this page.

    A record 记录 groups fields of different types under one name (9618 section 4):

    An enumerated type 枚举类型 lists the only values a variable may take:

    9618 also adds a DATE data type, random-access files (OPENFILE … FOR RANDOM), pointers, and classes with CLASS … ENDCLASS for its object-oriented paper.

    ⚠️ 0478 has five data types and arrays, and nothing else (topic 2). A 0478 answer that declares a record is answering a different syllabus.

    Common mistakes

    • Using a record in an 0478 answer. Use parallel arrays instead — one array per field, sharing an index.
    • Thinking TYPE means the same as DECLARE. TYPE defines a new type; DECLARE creates a variable of an existing one.
    한국어

    9618 has data structures 数据结构 that 0478 does not. You will meet them only at A-Level, and none of them runs under the 0478 rules of this page.

    A record 记录 groups fields of different types under one name (9618 section 4):

    TYPE Student
        DECLARE Name : STRING
        DECLARE Mark : INTEGER
    ENDTYPE
    
    DECLARE Candidate : Student
    Candidate.Name ← "Mei"
    Candidate.Mark ← 91
    OUTPUT Candidate.Name, " scored ", Candidate.Mark
    

    An enumerated type 枚举类型 lists the only values a variable may take:

    TYPE Vehicle = (Car, Bus, Taxi)
    DECLARE MyRide : Vehicle
    MyRide ← Taxi
    

    9618 also adds a DATE data type, random-access files (OPENFILE … FOR RANDOM), pointers, and classes with CLASS … ENDCLASS for its object-oriented paper.

    ⚠️ 0478 has five data types and arrays, and nothing else (topic 2). A 0478 answer that declares a record is answering a different syllabus.

    Common mistakes

    • Using a record in an 0478 answer. Use parallel arrays instead — one array per field, sharing an index.
    • Thinking TYPE means the same as DECLARE. TYPE defines a new type; DECLARE creates a variable of an existing one.

Log in or create account · ⁨로그인 또는 계정 만들기⁩

IGCSE, A-Level & AP