GESP C++ Level 1 Study Guide for Scoring Above 90

On September 27, children will face the GESP C++ Level 1 exam. Here, we summarize common exam points and common mistakes for this level, allowing students to identify gaps in their knowledge and strive for a score of 90 or above. The explanation is quite detailed, so please read patiently. In this era of short videos, it is quite rare for children to maintain the ability to focus on reading long texts.

GESP C++ Level 1 Study Guide for Scoring Above 90

If you need a PDF version of this long article, please contact me at the bottom.

Computer Basics and Programming Environment

This is basic knowledge that needs to be understood, and it is also an area where points can easily be lost. Many children who are just learning C++ are not very familiar with computers. Core knowledge points include:

Hardware Components: The five main components of computer hardware include the arithmetic logic unit, control unit, memory, input devices, and output devices. The arithmetic logic unit and control unit are collectively referred to as the Central Processing Unit (CPU); memory includes RAM; common input devices are keyboards and mice, while output devices include monitors and printers.

Storage Concepts: Understand that memory (Memory/RAM) is used for temporarily storing data and programs, which are lost when power is off; external storage (such as hard drives and USB drives) is used for permanently storing data; and Read-Only Memory (ROM) stores firmware programs. Common storage units include bits (bit), bytes (Byte, 1 Byte = 8 bits), kilobytes (KB, 1024 B), megabytes (MB), and gigabytes (GB), and unit conversions may be involved in the exam.

Operating Systems: Computers need to install operating systems (such as Windows, Linux, macOS, etc.) to manage hardware and software resources. Mobile operating systems should also be understood (such as Android, iOS, HarmonyOS). Basic operations (such as creating, copying, deleting files, opening and closing software, etc.) and common terms (such as desktop, folder, process, etc.) should also be understood.

Programming Environment: Familiarity with the use of Integrated Development Environments (IDEs), such as Dev-C++. Master basic operations: creating new projects or files, editing code, saving, compiling (translating source code into executable programs), and running and debugging programs. Understand the difference between compiling and running—compiling translates source code into machine code, while running executes the compiled program; debugging is the process of checking and correcting program errors during execution.

Detailed Explanation and Examples:

Computers are composed of both hardware and software. Hardware provides computing power and storage space, while software (including operating systems and applications) provides command and coordination. The CPU is the brain of the computer, responsible for executing instructions and calculations; memory is like a work desk, storing currently used data and instructions, fast but relatively small in capacity; external storage like hard drives is like a filing cabinet, large in capacity but slower in read/write speed.

Modern computers generally adopt the stored-program concept, which means that program instructions and data are stored together in memory, and the controller retrieves and executes them in order. This idea originates from the von Neumann architecture. The operating system plays the role of a manager in the computer, loading applications into memory for execution and controlling hardware devices to coordinate work. For example, when we press the “run” button in the IDE, the IDE calls the compiler to compile the code into machine code, and the operating system allocates memory and CPU time for the program to run, ultimately presenting the results through devices like monitors.

In terms of programming environments, taking Dev-C++ as an example, the typical steps are: start the IDE, create a C++ source file, write code, and click “compile” to convert it into an executable file. If there are syntax errors, the compiler will provide error messages; after successful compilation, click “run” to execute the program. If the program’s output does not meet expectations, debugging features can be used, such as setting breakpoints (single-step) to execute line by line and observe variable value changes to locate logical errors.

Typical Exam Question Example:

Determine which of the following devices is not an output device of a computer:

A. Monitor B. Printer C. Keyboard D. Speaker

Analysis: The keyboard is an input device, while the others are output devices, so the correct answer is C.

In the basic knowledge section, children can easily confuse the concepts of memory and storage devices. For example, memory (RAM) is temporary storage, and data disappears when power is off; while hard drives and USB drives are external storage, and data remains when power is off. Exam questions may appear to test this distinction, such as “Data in RAM will be permanently saved after power off” should be judged as false.

History of Computer Development

The development of computers can be divided into several major stages, with each generation of computers showing significant changes in components, performance, and applications.

Von Neumann Architecture: The foundational theory of modern electronic computers, proposed by John von Neumann in the 1940s. Its core ideas include:

Five-component structure: A computer consists of an arithmetic logic unit, control unit, memory, input, and output.

Stored program: Program instructions and data are uniformly represented in binary and stored in memory, with the computer retrieving and executing instructions in address order.

Binary operations: Using binary for data and instruction encoding. The von Neumann structure enables computers to have programmability and general computing capabilities, and it remains the foundation of mainstream computer architecture today.

First Generation Computers (1940s-1950s, Vacuum Tube Era)

Used vacuum tubes as the main logic element. They were huge (occupying entire rooms), consumed a lot of power, and generated significant heat, but they achieved electronic automatic computation for the first time. Representative machines include the ENIAC from 1946 (the world’s first electronic computer, using about 18,000 vacuum tubes). This generation of computers was mainly used for numerical calculations, such as ballistic trajectory calculations. Programming required using machine language or very primitive assembly language through circuit connections or punched tape input.

Second Generation Computers (1950s-1960s, Transistor Era)

The invention of the transistor ushered in the second generation of computers. Transistors are smaller, consume less power, and are more reliable than vacuum tubes, significantly improving computer performance and reducing costs. Computers began using magnetic core memory as the main memory. During this period, high-level programming languages (such as Fortran and COBOL) compilers emerged, improving software development efficiency. China’s first large-scale general-purpose electronic computer was born during this period (such as the “103 machine” in 1958, which used vacuum tubes; and the “119 machine” in 1964, which used transistors), indicating that China also entered the electronic computer era.

Third Generation Computers (1960s-1970s, Integrated Circuit Era)

Used medium and small-scale integrated circuits (ICs) to replace discrete transistors, further reducing the size of computers and improving speed and reliability. Multiple components integrated on a silicon chip greatly increased the speed of calculations per second. This generation saw the emergence of multiprogramming techniques and the early forms of operating systems, allowing for simultaneous processing of multiple tasks. Computers began to leave the laboratory, with mini-computers and small computers used for business processing.

Fourth Generation Computers (1970s-Present, Large Scale Integration/Microprocessor Era)

In 1971, the first single-chip microprocessor was introduced (Intel 4004), marking the possibility of integrating the CPU onto a single chip. Subsequently, large-scale and ultra-large-scale integrated circuits ushered computers into the microcomputer era, with personal computers (PCs) rising and becoming popular in the 1980s. Fourth-generation computers are small in size, affordable, and have rapidly improved performance, with parallel processing, multimedia, and network technologies developing rapidly. Modern computers (i.e., electronic computers) are all based on the von Neumann architecture and use microprocessor technology. With the development of mobile devices and the Internet of Things in recent years, the forms of computers have become more diverse.

Modern computers are characterized by: computing speeds measured in billions of operations per second, storage capacities measured in GB/TB, and compact size with low power consumption. The applications of computers have expanded from scientific research and military to all aspects of social life. Understanding the historical development helps to appreciate the hard-won nature of current technologies and their basic principles. For example, exam questions may ask, “What architecture is modern computers based on?” The answer is the von Neumann architecture.

Typical Exam Question Example:

The logic component used in China’s first large-scale general-purpose electronic computer is ( ).

A. Integrated Circuit B. Large Scale Integrated Circuit C. Transistor D. Vacuum Tube

Analysis: China’s first large-scale general-purpose electronic computer was born in the 1950s-60s, when integrated circuits had not yet appeared, and it used first-generation vacuum tube components, so the answer is D.

C++ Basic Syntax

Although simple, many areas can still be confused or misremembered by children who are just starting to learn C++. It still needs to be taken seriously.

Identifiers, Keywords, and Variables

An identifier refers to a user-defined name in a program, such as variable names and function names. Naming rules: must consist of letters, numbers, and underscores, and cannot start with a number, and is case-sensitive. For example, Score and score are two different identifiers. Identifiers cannot be C++ keywords (reserved words), such as int, while, return, etc. Keywords have special meanings in the compiler and cannot be used as user-defined names.

Children often confuse cout, cin, endl, scanf, printf, thinking they are system keywords because they are frequently used, but they are not; they are functions from the iostream library, not system-provided keywords. Therefore, when the exam asks whether cout, cin, endl, scanf, printf can be used as variable names, remember that they can.

A variable is a memory unit with a name used to store data. In C++, a variable must be declared with its type and optionally initialized. Variable names should be meaningful, such as using sum to represent a sum, index to represent an index, etc. The declaration format is: type variable_name = initial_value; For example:

int count = 0; // Initialize integer variable count to 0
char letter = 'A'; // Initialize character variable letter to character 'A'

If a variable is not initialized, it will contain an unknown garbage value (especially for local variables of basic types), which is one of the common causes of errors.

A constant is a value that does not change during program execution. It can be a literal value (such as the number 100, character ‘A’, string “Hello”, etc.) or a symbolic constant defined using the const keyword, such as:

const double PI = 3.14159; // Define constant PI to represent the value of pi

Once defined, the value of PI cannot be modified. Proper use of constants can improve code readability.

Note: C++ variable names cannot start with a number and cannot contain spaces or symbols (except for underscores _). For example, 5star is not a valid identifier, and one should avoid using C++ case sensitivity to cause confusion, such as not defining both Total and total as two variables.

Typical Exam Question Example:

Select the option that cannot be a valid C++ variable name:

A. FiveStar B. fiveStar C. 5Star D. Star5

Analysis: Identifiers cannot start with a number, option C starts with the number 5, which is invalid. Therefore, the answer is C.

Basic Data Types

C++ provides various basic data types to store different types of values:

Integer: For example, int represents standard integers, generally occupying 4 bytes (32 bits), representing integer values in the range of approximately -2^31 to 2^31-1. There are also extended integer types like long long that can represent larger integer ranges (generally 8 bytes). Integers are used in scenarios that do not contain decimals, such as counting and indexing.

Floating-point: For example, float (single precision, 4 bytes) and double (double precision, 8 bytes) are used to represent values with decimals. Double is the default floating-point type in C++. Floating-point numbers may have rounding errors in calculations, so caution is needed when comparing. For example, 1.0 + 0.3 == 1.3 returns false.

Character: Occupies 1 byte and is used to represent a single character. Character constants are enclosed in single quotes, such as ‘A’. In fact, the value of char corresponds to the underlying ASCII code integer (e.g., ‘A’ corresponds to 65). Characters can participate in integer calculations (calculated by their encoded values).

It is important to remember the ASCII codes for several key characters:

The ASCII code for ‘A’ is 65

The ASCII code for ‘a’ is 97

The ASCII code for ‘0’ is 48

The ASCII code for ‘ ‘ (space) is 32

Boolean: Has only two values: true (true) and false (false), commonly used for logical judgments. Boolean values can essentially be represented by 1 (true) and 0 (false).

Examples of variable definition and initialization:

int age = 20; // Define integer variable age, initial value 20

double price = 9.99; // Define double precision floating-point variable price, initial value 9.99

char grade = 'A'; // Define character variable grade, value 'A'

bool flag = true; // Define boolean variable isPassed, value true

Type Conversion: Automatic type conversion occurs during mixed-type operations. For example, integer and floating-point operations will promote the integer to a floating-point type. The cast operator can be used to convert a value to a specified type, such as (int)3.7 yielding 3.

Common Mistakes: Character and integer types often convert to each other; char in arithmetic expressions will automatically convert to the corresponding ASCII integer value. For example, char c = ‘A’; cout << c + 1; will output 66 instead of the character because ‘A’ (65) plus 1 yields the integer 66. If you want to output the character B, you need to convert it back: cout << char(c + 1);.

Typical Exam Question Example:

The following statement about C++ basic types is incorrect:

A. The size of a double type variable is variable

B. A bool type variable occupies 1 byte of memory

C. The value range of an int type variable is not infinite

D. A char type variable has 256 possible values

Analysis: The memory occupied by the double type is fixed (generally 8 bytes), so option A is incorrect. B, C, and D are correct statements: bool usually occupies 1 byte, int has a limited range, and char has 256 possible values (ASCII code). Therefore, the answer is A.

Arithmetic and Expressions

Arithmetic Operators: C++ provides basic mathematical operators: addition +, subtraction -, multiplication *, division /, and modulus %. Their precedence from high to low is: multiplication, division, modulus > addition, subtraction (parentheses can change the precedence). The modulus % is used to calculate the remainder of integer division and can only be used with integer types. For example, 7 % 3 equals 1. Integer division truncates the decimal part; for example, 7 / 3 results in 2 (the decimal is truncated). If a floating-point result is desired, at least one floating-point number must be involved in the operation, such as 7.0/3 yielding 2.3333….

Increment and Decrement Operators: ++ indicates increment by 1, — indicates decrement by 1. They can be used for quick addition and subtraction of variables, such as x++ is equivalent to x = x + 1. There are two forms: prefix (++x) and postfix (x++); the prefix adds first and then uses the expression, while the postfix takes the value first and then adds. Generally, using them as independent statements yields the same effect, but in complex expressions, the order differs, so it is best to avoid mixing them in a complex expression to reduce confusion.

b = a++; // Equivalent to b=a; a=a+1;
b=++a; // Equivalent to a=a+1; b=a;

Assignment Operator: = is used for assignment, storing the value of the right-side expression into the left-side variable. Note the distinction between assignment = and the mathematical equality concept; assignment is “assigning the right value to the left variable”. For example, a = b + 5; calculates b + 5 and stores the result in a. C++ supports compound assignment operators, such as +=, -=, *=, /=, %=, etc., to simplify updating variable values. For example, x += 3; is equivalent to x = x + 3.

Expressions and Evaluation: An expression is formed by combining constants and variables through operators. Evaluating an expression yields a value. For example, (a + b) * 2 is an expression. If an expression contains different types, implicit type conversion occurs: for example, integers are promoted to floating-point types during operations. A cast can be used to control the conversion, such as (double)sum / n converts sum to double before dividing by n to obtain a floating average.

Example: Suppose int a = 5, b = 2; then:

a / b results in 2 (integer division 5/2 is truncated).

(double)a / b results in 2.5 (a is converted to double before division).

a % b results in 1 (5 divided by 2 leaves a remainder of 1).

a++ after execution makes a equal to 6 (post-increment).

a += 10 after execution increases a’s value by 10.

Operator Precedence: Multiplication and division take precedence over addition and subtraction, logical NOT ! takes precedence over AND &&, AND takes precedence over OR ||, etc. If uncertain, parentheses can be used to clarify the order of operations.

Common Mistakes: Integer division and modulus operations are only valid for integers. If a modulus is taken on floating-point numbers, it will lead to a compilation error. Similarly, dividing two integers will truncate the decimal part rather than round it. If the average is required, special attention should be paid to using floating-point operations. Another common trap is confusing assignment and comparison: the assignment symbol = will return the value after assignment, which is non-zero and thus true in conditions, so if(x = 5) not only incorrectly uses assignment but also assigns x to 5 and then evaluates to true. The correct should be if(x == 5).

Relational and Logical Operations

Relational Operators: Used to compare the size or equality of two values, including: greater than >, less than <, greater than or equal to >=, less than or equal to <=, equal to == (note that it is two =, not one =), not equal to !=. The result of relational operations is a boolean value true or false. For example, 5 > 3 is true (true), while a == b indicates whether a is equal to b. Note: Use == for equality checks, do not mistakenly use a single =.

Logical Operators: Used to connect or negate the truth of boolean values, mainly including: logical AND &&, logical OR ||, and logical NOT !. A && B is true if and only if both A and B are true; otherwise, it is false. A || B is true if at least one of A or B is true; it is only false when both are false. !A is true if A is true, and false if A is false (negation).

Logical operators are commonly used in multiple condition judgments, such as determining whether a year is a leap year requires the compound condition of “divisible by 4 and not divisible by 100, or divisible by 400”. In C++, this can be expressed as:

bool isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

Logical expressions also have precedence: ! has the highest precedence, && is next, and || has the lowest. In most cases, it is recommended to use parentheses to clarify logic.

Short-circuit Evaluation: C++ logical AND and OR have the “short-circuit” property: in the expression A && B, if A is false, the entire result must be false, and B is not evaluated; in A || B, if A is true, the result is already true, and B is not evaluated. This mechanism can avoid unnecessary calculations and can even be used to prevent errors. For example:

if(b != 0 && a/b > 2) { … }

If b is 0, then the left side (b != 0) is false, and the entire AND expression short-circuits to false, and the right side a/b will not execute, thus avoiding a division by zero error. This point can be utilized when writing conditions, but care should be taken to avoid relying on side effects that lead to logical confusion.

Example: Suppose int score = 85; then: (score >= 60) && (score < 90) checks whether the score is passing and not excellent, resulting in true (85 meets the condition). !(score < 60) checks whether it is not failing, i.e., whether it is passing, and the result is also true. (score >= 90) || (score < 60) checks whether the score is either excellent or failing, resulting in false.

Typical Exam Question Example 1:

If both a and b are int type variables, which of the following expressions can correctly determine “a equals 0 or b equals 0”?

A. (!a) || (!b)

B. (a == b == 0)

C. (a == 0) && (b == 0)

D. (a == 0) – (b == 0) == 0

Analysis: Option A utilizes the truth property of integers in C/C++: !a is true if and only if a is 0, and similarly for !b, so (!a) || (!b) correctly determines if at least one is 0. Option B’s syntax does not conform to logic (the chained equality from left to right is equivalent to (a == b) == 0, which is not the intended meaning); C checks if both a and b are 0; D is valid if a=5, b=5, but does not indicate whether a equals 0 or b equals 0. Therefore, the answer is A.

Common Mistakes: The result of logical operations in C++ is also a numerical value (type bool, convertible to 0 or 1). For example, the expression (2 * 3) || (2 + 5) evaluates to true, and the logical OR result is true, which converts to a numerical value of 1, rather than performing a bitwise OR on 6 and 7 to yield 7, or concatenating them into 67! Do not confuse logical operations with arithmetic operations.

Typical Exam Question Example 2:

Using the above knowledge, consider a complete expression evaluation example:

int a = 5, b = 0;
bool result = (b != 0 && a/b > 2) || (a == 5);
cout << result;

Analysis: First, b != 0 is false (because b=0), and according to the short-circuit rule, (b != 0 && a/b > 2) is false and does not compute a/b (avoiding division by zero). Then the left side is false, and the right side (a == 5) is true, so false || true results in true, and result is assigned true. When outputting, cout will convert bool to 1 or 0, so the above code will output 1 indicating that the result is true.

This example illustrates the impact of C++ expression evaluation order and short-circuit rules. When writing complex condition judgments, it is recommended to use parentheses to group logically as needed, and to place potentially error-causing parts on the right side of short-circuit checks, as in the above example where b!=0 is placed first to ensure safety.

Input and Output Statements

C++ provides various ways to perform input and output. The most commonly used in exams are the standard input and output libraries iostream’s cin/cout, and C standard library’s cstdio’s scanf/printf. Children should master the basic usage of both methods.

Output (cout)

cout << fixed << setprecision(2) can retain 2 decimal places, while cout << setprecision(2) retains 2 significant digits, so be careful to distinguish between them.

Input (cin)

cin automatically skips whitespace characters (spaces, newlines, tabs) when reading. To read multiple values consecutively, multiple >> can be used.

Note: cin corresponds to user input character by character, and when reading characters (such as char c; cin >> c; ) or strings, it uses whitespace as a delimiter—this means that cin >> str; can only read a single word (it stops at spaces).

printf/scanf are standard input and output functions from the C language, also commonly used in competitions and certain scenarios. They read and write data through formatted strings and format specifiers, which are closer to the underlying level and usually slightly faster.

Formatted Output (printf)printf() accepts a format string and a variable number of parameters, formatting the output of the parameters. In the format string, format specifiers preceded by % indicate the position and format of the corresponding parameters.

For example:

%d outputs an integer (int)

%lld outputs a long long integer (long long)

%f outputs a floating-point number (float/double) (default 6 decimal places)

%.1f outputs a floating-point number retaining 1 decimal place (precision can be adjusted)

%c outputs a single character

Example:

#include <cstdio>

int main() {

  int age = 12;

  double score = 95.5;

  printf("Age: %d, Score: %.1f\n", age, score);

  return 0;

}

Output: Age: 12, Score: 95.5, where %d is replaced by age’s value 12, and %.1f formats score to retain 1 decimal place as 95.5. \n indicates a newline. When using printf, it is essential to ensure that the provided parameter types and quantities match the format specifiers; otherwise, it may output incorrect results or even cause severe errors.

Formatted Input (scanf)

scanf() reads data from standard input according to the format string. Its usage is similar to printf, but it requires providing the variable address to store the input value—this is achieved through the address operator & (except for character arrays and strings, which can represent addresses themselves).

For example:

%d reads an integer (int), requiring an int parameter, such as scanf(“%d”, &x).

%lld reads a long long integer (long long), corresponding to long long.

%f reads a floating-point number (float, requires passing float). Note: to read double, use %lf, corresponding to double).

%c reads a single character, parameter for char.

#include <cstdio>

int main() {

  int num;

  scanf("%d", &num); // Read string and integer in sequence

  printf("Number: %d", num);

  return 0;

}

If the input is: 123, scanf will read 123 into num (note that reading an integer requires writing &num).

The output will correspond to printing Number: 123.

When using scanf/printf, note that scanf stops reading the current string or character sequence when it encounters whitespace (spaces, newlines) but skips previous whitespace to find the next valid input.

When to use printf/scanf: Generally, printf is more convenient when formatted output is needed (such as retaining decimal places), while scanf is sometimes slightly faster when reading large amounts of data. However, in Level 1 exams, both methods are accepted, and candidates can choose whichever they are more proficient with. It is important to note that cin and scanf should not be mixed. Therefore, it is recommended to use one input method consistently throughout a program.

Common Mistakes: Beginners often overlook the address operator when using scanf. For example, writing scanf(“%d”, num) will compile but run incorrectly. It should be scanf(“%d”, &num) to assign the read value to variable num.

Additionally, printf’s format specifiers must match the variable types; for example, use %lf for double instead of %f. Careless details can lead to incorrect outputs or even program crashes.

Input and Output Format Requirements

Regardless of which I/O method is used, strictly following the format specified in the problem statement is key to scoring points. Exams usually provide input and output examples, and children should ensure that the program output matches the example format exactly, including spaces, newlines, punctuation, and even letter case. For example, if the problem requires outputting Yes or No, it cannot output the lowercase yes, nor can it output any extra information.

Some programming problems may require outputting several groups of data, each occupying a line or separated by specific delimiters. For example, “output two space-separated real numbers” means there should be one space between each pair of numbers, neither more nor less. At the same time, when using printf, pay attention to the position of the newline character \n; when using cout, it is common to use endl or “\n” to indicate a newline.

If the program needs to repeatedly read until the end of the file (EOF), a loop can be used in conjunction with the input function’s return status, such as while(cin>>a). However, in Level 1 exams, most scenarios will specify the number of inputs, so EOF reading does not need to be considered.

Summary: Develop good I/O habits: prompt before input (if the problem has special prompt requirements), output in the specified format, and do not mix in debugging information.

Flow Control

Flow control statements determine the route of program execution, including branches (conditional judgments) and loops (repeated execution). Mastering the usage of if/else, switch, and for, while, do…while statements is a basic requirement for programming.

Branch Structure: if and switch

if (condition expression) {

    // Statements executed when the condition is true

}

You can add an else part to handle the case when the condition is false:

if (condition expression) {

    // True branch

} else {

    // False branch

}

If multiple conditions need to be judged, you can use multiple else if:

if (condition1) {

    ... 

} else if (condition2) {

    ... 

} else {

    ...

}

Note: The condition expression should be enclosed in parentheses. A single statement in the true/false branch can omit curly braces {}, but it is recommended to always use curly braces to avoid omissions that lead to logical errors (especially with multiple nested levels).

Example: Determine whether a number is positive, negative, or zero:

if (num > 0) {

    cout << "Positive";

} else if (num < 0) {

    cout << "Negative";

} else {

    cout << "Zero";

}

Depending on the value of num, the above code will execute one of the three options.

Switch multi-branch selection: When you need to classify and handle multiple possible values of an integer (or a type convertible to int, such as char), the switch statement is more intuitive. Format:

switch (expression) {

    case constant1:

        statement group 1;

        break;

    case constant2:

        statement group 2;

        break;

    ...

    default:

        default statement group;

}

Working Principle: The value of the expression in the parentheses of switch is calculated, and then it sequentially matches each case label. If matched, it starts executing subsequent statements from that point until it encounters a break or the end of the switch. Break is used to exit the switch; otherwise, the program will “fall through” and execute the statements of the following cases (unless this fall-through effect is logically needed). Default is optional and is used to handle all cases that do not match the above cases, equivalent to a final “otherwise”.

Example: Simple menu selection:

int choice = 2;
switch(choice) {

    case 1:

        cout << "Start Game";

        break;

    case 2:

        cout << "Load Save";

        break;

    default:

        cout << "Invalid Option";

}

In the above code, if choice is 2, it will execute the second case and output “Load Save”, then encounter break and exit. If choice is another value (not 1 or 2), it will execute the default branch and output “Invalid Option”.

Switch Notes: The expression type must be an integer or a type convertible to an integer (such as char, enum, etc.). It cannot directly use string, float, etc. Each case label generally ends with a break; otherwise, the next case’s statements will continue to execute (this is called “fall-through”). In some cases, fall-through can be used to handle multiple values the same way, for example:

switch(ch) {

  case 'A':

  case 'a':

      cout << "Letter A"; break;

  ...

}

Here, both ‘A’ and ‘a’ fall through to the common handling statement without a break, achieving case-insensitive handling. Default can be omitted; if omitted and no matching case exists, the entire switch does nothing.

Conditional operator (ternary operator): This is a concise replacement for if-else, formatted as: condition ? expression1 : expression2. If the condition is true, the entire operation result is the value of expression1; otherwise, it is the value of expression2.

For example:

int max = (a > b) ? a : b;

This assigns the larger value to max. This is useful when you need to quickly obtain a value based on a condition. However, it is not recommended to put complex logic into the ternary operator, as it reduces readability.

Typical Exam Question Example:

To find the larger of integers a and b, which program structure is usually used?

A. Sequential Structure B. Loop Structure C. Branch Structure D. Jump Structure

Analysis: To compare the sizes of two numbers, conditional branching (if judgment) should be used, so the answer is C. “Sequential” refers to executing the program in order without needing judgment, “loop” refers to repeated execution, and “jump” generally refers to goto, which is not the logic needed here.

Common Mistakes: Beginners sometimes mistakenly use the assignment operator in if judgments, such as writing if(x = 0), which will assign 0 to x and the condition will be false (0). The correct should be if(x == 0) to check if x is 0. Another common issue is omitting curly braces, leading to logical errors: in C++, if only affects the first statement immediately following it; if you forget to enclose multiple statements in braces, only the first statement will be controlled by the condition. Indentation in C++ does not have syntactical significance (only for readability) and cannot replace {}. Be careful with this.

Loop Structures: for, while, do…while

Loops are used to repeatedly execute a block of code until a stopping condition is met. C++ has three basic loop statements:

For loop: Suitable for loops with a determined number of iterations.

Syntax:

for (initialization; loop condition; loop update) { loop body }

Execution order: First, initialization is executed once, then at the start of each loop, the loop condition is checked; if true, the loop body is executed, and after executing the loop body, the “loop update” statement is executed, then the condition is checked again, and so on; if the condition is false, the loop exits.

Example:

for(int i = 1; i <= 5; i++) { cout << i; }

This will output 1 2 3 4 5 sequentially.

i starts from 1, and increments by 1 after each loop until i <= 5 is no longer satisfied.

While loop: Suitable for condition-driven loops.

Syntax:

while (condition) {

    loop body;

}

During execution, the condition is checked first; if true, the loop body is executed, and then the condition is checked again, and so on, until the condition is false, at which point the loop exits. If the condition is false from the start, the loop body will not execute at all.

Example:

while(x > 0) { x--; }

This will end the loop when x is reduced to 0.

Do…while loop: Executes the loop body at least once before checking the condition to decide whether to continue.

Syntax:

do {

    loop body;

} while (condition);

Example:

int num;
do {

    cout << "Please enter a positive number:";

    cin >> num;

} while(num <= 0);

The above example will prompt and input at least once; if the input num is not greater than 0, it will continue to require input until a positive number is entered.

Loop Selection Recommendations: When you “know the exact number of iterations” or have a clear iterative variable change, use for for clarity; when the number of iterations is uncertain and depends on runtime conditions, use while; when the loop body needs to execute at least once, use do…while. In practice, any for loop can be equivalently replaced with while, but the for syntax centralizes the initialization, increment, and condition in one place, making it more readable and maintainable.

Loop Control Statements:Within loops, break and continue can be used for fine-grained control of flow:

Break: Immediately exits the current loop (terminating the loop body) and executes the statements following the loop. It is commonly used to end a loop early, such as exiting a search loop when the target is found.

Continue: Immediately skips the remaining part of the current loop and directly starts the next loop condition check. It is commonly used to skip cases that do not need processing.

Example, using break and continue:

// Find the first multiple of 3 between 1 and 10
for(int i = 1; i <= 10; i++) {

    if(i % 3 == 0) {

        cout << "Found: " << i;

        break;  // Exit the entire loop after finding

    }
}

// Output even numbers between 1 and 5
for(int j = 1; j <= 5; j++) {

    if(j % 2 != 0) 

        continue;     // Skip odd numbers, directly enter the next loop

    cout << j << " "; // Only output even numbers
}

The first loop will output “Found: 3” and then stop, not checking 4…10. The second loop uses continue to skip odd numbers, only outputting 2 and 4.

Nested Loops: A loop that contains another loop structure inside it. Typical cases include outputting two-dimensional tables, traversing matrices, etc. A classic case is the multiplication table:

for(int i = 1; i <= 9; i++) {

    for(int j = 1; j <= i; j++) {

        cout << j << "×" << i << "=" << i*j << "\t";

    }

    cout << endl;
}

The inner loop outputs each item from 1×i to i×i in the i-th row, while the outer loop moves to the next line, ultimately printing the complete multiplication table. The total execution count of nested loops is the product of the inner and outer loop counts, so efficiency should be considered, but in Level 1 exams, this is usually not an issue.

Common Mistakes: Be cautious of infinite loops. If the loop condition is always true, or the loop variable does not change as expected, the loop may never end. For example:

int i = 1;
while(i <= 10) {

    // No statement modifying i

}

This will lead to an infinite loop. When writing loops, ensure that the loop variable is appropriately updated within the loop body so that the condition will eventually become false. Another trap is the boundary issue in for loops, especially when using < or <=. Be clear about the number of times the loop executes. For example, for(int i=0; i<5; ++i) executes 5 times, while using i<=5 executes 6 times, so choose the correct condition based on the problem statement. This is often tested in exams, so learning to judge loop outputs or counts is essential.

Common Types of Programming Questions

Based on past exam questions, Level 1 programming questions usually focus on simple algorithms and basic logic implementation. The following lists common question types and key points for solving them:

Simple Input and Output Processing

Reading several data points according to specified formats and outputting results is the most basic and easiest type. For example:

Sum/Average: Input n and n numbers, calculate their sum or average. Key points: correctly accumulate, pay attention to data types and format output when retaining decimal places for averages.

Unit Conversion: Such as converting Celsius to Fahrenheit, currency conversion, etc., calculate and output according to given formulas. Pay attention to using floating-point numbers and controlling output precision formats.

Mathematical Calculation Types

Given an integer or range, require mathematical judgment or operations.

Odd/Even Statistics: Input n integers, count the number of odd and even numbers among them. Traverse and judge num % 2.

Factor (Divisor) Calculation: Input an integer N, output all factors of N (can use a loop from 1 to N to check N % i == 0).

Prime Number Judgment: Determine whether a number is prime. A common method is trial division, checking from 2 up to √N. Note that special cases where N<2 are not prime. A boolean flag can be used or directly judged in the loop.

Special Number Judgment: Such as narcissistic numbers, palindromic numbers, etc., extract digit positions or combine mathematical conditions for judgment based on the problem statement.

Simple Mathematical Algorithms: Such as calculating the greatest common divisor (GCD) and least common multiple (LCM). The Euclidean algorithm can be used to find GCD.

For example:

int a, b;
int x = a, y = b;
while(y != 0) {
    int r = x % y;
    x = y;
    y = r;
}
// x is the greatest common divisor

Then LCM = a*b / GCD. Level 1 may not directly test algorithm code, but understanding this classic algorithm helps in writing correct programs.

Conditional Logic Types

Require comprehensive use of multiple judgments to solve problems.

Range Classification: Output different results based on the size of input values. For example, grading: A for above 90, B for 80-89, …

Combined Judgments: Multiple conditions combined, such as leap year calculations, determining whether three sides can form a triangle, etc. Writing the correct compound condition is key.

Simulating Simple Decisions: Such as a simple menu program, executing different branches based on user input options (this may appear in exam questions as a text description that needs code implementation).

Loops and Accumulation

Using loops to solve slightly more complex problems.

Factorial and Accumulation: Calculate n! or accumulate some numbers. Be cautious of data scale (factorials grow quickly, watch for overflow, use long integers if necessary).

Variations of Accumulated Sums: Such as calculating the sum of 1^2 + 2^2 + … + n^2, or the sum of factorials 1! + 2! + … + n!. These can be accumulated directly in a loop or based on formulas.

Generating Sequences with Loops: Such as outputting the first n terms of the Fibonacci sequence. This requires calculating previous and next terms.

Recommendations: During preparation, practice coding implementations of various typical problems, such as comparing sizes, sorting, digit extraction, time conversion, etc. You can write code on a computer and design test cases to verify that the output meets the requirements exactly. Through practice, you can deepen your understanding of syntax and accumulate some code templates, making you more confident in the exam.

Common Errors and Traps

Confusion Between Assignment and Comparison: Use == for comparison judgment, not =. For example, if(x == 0) rather than if(x = 0). The latter assigns 0 to x, making the condition always false, which is likely not the intention.

Curly Brace Matching Errors: Forgetting to use curly braces in if/else or loops leads to logic only affecting one line. Always ensure paired {}, and develop good indentation styles to help check matching.

Semicolon Misuse: Accidentally adding a semicolon at the end of for or if statements prematurely terminates logic. For example, if(condition); { … } makes the if statement effectively empty, and the subsequent block will execute unconditionally. This type of error is not easy to detect but can have serious consequences.

Uninitialized Variables: Local variables used without being assigned an initial value have uncertain values. For example, an accumulation variable int sum; used directly as sum += x; will lead to incorrect results. Always initialize variables.

Input and Output Format Errors: Outputting too many or too few spaces or newlines is a common mistake for beginners. In final output, compare character by character with the problem requirements. For example, when outputting multiple numbers, there should not be extra spaces between them.

Precision Issues: Floating-point accumulation errors may lead to abnormal comparison results. A typical example: 0.1 + 0.2 == 0.3 may return false due to the imprecision of floating-point representation. Avoid directly using == to compare floating points; set an error range instead. However, in Level 1 exams, strict comparisons of non-integers are generally not required, and decimal operations are mostly about format output requirements.

Logical Short-circuiting and Side Effects: When utilizing && or || short-circuit properties, be cautious about whether there are operations modifying variables in the condition expressions, as they may not execute due to short-circuiting.

Omitting Break in Switch: Forgetting break can cause unintended fall-through (unless it is intentional). Fall-through will cause multiple case statements to execute, which is often not the expected behavior.

Debugging Techniques: When program results do not meet expectations, you can use output statements to print intermediate variables for troubleshooting. For example, when debugging loops, print the index and variable changes during each iteration.

Common errors often stem from small details that are overlooked, so carefully reviewing key parts (loop boundaries, condition judgments, I/O formats) after coding can prevent most issues.

OK, that’s it. Those who have read this far are excellent and will definitely score above 90. Keep it up. Lastly, a reminder: do not spend too long on one question during the exam; if you cannot solve it, mark it and come back to it after finishing the programming questions for review.

If you need a PDF version, contact me:

GESP C++ Level 1 Study Guide for Scoring Above 90

Leave a Comment