C++ Preliminary Exam Preparation Guide

4. C++ Basic Syntax (Core Exam Points)

(1) Variables and Data Types

The basic data types are high-frequency exam points in the preliminary exam, and we must remember their ranges to avoid overflow issues.

In a 32-bit system, the situations for each basic data type are as follows:

int: occupies 4 bytes, with a value range of -2^{31} to 2^{31}-1 (approximately ±2 billion), suitable for storing integers, such as population counts, scores, etc.

long long: occupies 8 bytes, with a value range of -2^{63} to 2^{63}-1 (approximately ±9e18), used for storing large integers, such as factorials and large sums.

char: occupies 1 byte, with a value range of -128 to 127 or 0 to 255 (unsigned), mainly used for storing single characters, such as ‘A’ or ‘5’.

float: occupies 4 bytes, approximately ±3.4e38 (precision of 6-7 significant digits), suitable for storing small decimals with low precision requirements.

double: occupies 8 bytes, approximately ±1.7e308 (precision of 15-16 significant digits), used for storing decimals with high precision requirements.

Variable definition and initialization also have corresponding rules:

The definition format is “data type variable name;”, for example, int a; long long sum;.

Initialization refers to assigning a value at the time of definition, which can avoid uninitialized local variables (random values leading to calculation errors), for example, int b = 5; double pi = 3.14159;.

Constant definitions must be modified with const (value cannot be changed), such as const int MAXN = 1000; (often used when defining array sizes).

(2) Operators and Expressions

The operator precedence from high to low needs to be memorized, with the specific order as follows:

1.Parentheses: ()

2.Unary operators: ++ (increment), — (decrement), ! (logical NOT), ~ (bitwise NOT)

3.Arithmetic operators: * (multiply), / (divide), % (modulus); + (add), – (subtract)

4.Shift operators: << (left shift), >> (right shift)

5.Relational operators: >, <, >=, <=; == (equal), != (not equal)

6.Bitwise operators: & (bitwise AND); ^ (bitwise XOR); | (bitwise OR)

7.Logical operators: && (logical AND); || (logical OR)

8.Assignment operators: =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=

9.Comma operator: , (lowest precedence)

When using operators, there are some common pitfalls to be aware of:

The result of 1 + 2 * 3 is 7 (multiplication before addition).

a == b is a comparison, a = b is an assignment (a common confusion in multiple-choice questions).

i++ uses i first and then increments, while ++i increments first and then uses (a frequent point in reading program questions).

Expressions and type conversions are divided into automatic type conversion and explicit type conversion:

Automatic type conversion: low precision to high precision conversion (e.g., int + double results in double); high precision to low precision conversion will lose precision (e.g., converting double to int truncates the decimal part, such as (int) 3.9 results in 3).

Explicit type conversion: the format is (target type) expression, such as (long long) a * b (to avoid overflow when multiplying ints, first convert a to long long).

(3) Control Statements

Branch statements include if-else and switch:

The format of if-else is as follows:

if (condition expression) { // Execute when condition is true

} else if (condition expression 2) { // Execute when condition 1 is false and condition 2 is true

} else { // Execute when all conditions are false

}

The common pitfalls are: the condition expression must be enclosed in parentheses; if the code block contains only one statement, the braces can be omitted, but it is recommended to keep them (to avoid logical errors); else matches the nearest if (to avoid the “dangling else” problem).

The format of switch is:

switch (expression) {

case constant 1:

// Execute when expression equals constant 1

break; // Exit switch, if not written, continue to execute the next case

case constant 2:

// Execute when expression equals constant 2

break;

default:

// Execute when expression does not equal any case constant

break;

}

It is important to note that: the expression must be of integer type (int, char, etc.); case must be a constant; break cannot be omitted (otherwise it will “fall through” to the next case).

Loop statements include for loops, while loops, and do-while loops:

The format of the for loop is: for (initialization; condition; update), for example:

for (int i = 1; i <= 10; i++) { // Loop 10 times, i from 1 to 10

}

Common pitfalls: loop condition judgment (e.g., i <= n is n times loop, i < n is n-1 times loop); initialization can define loop variables (local variables, valid only within the loop); update statements can be written as i += 2 (step size of 2, traversing odd/even numbers).

The format of the while loop is: while (condition) { loop body }, first judge the condition, if true, execute the loop body. For example:

int i = 1;

while (i <= 10) { // Loop 10 times

i++; // Must manually update the loop variable, otherwise it will lead to an infinite loop

}

The format of the do-while loop is: do {loop body} while (condition);, first execute the loop body once, then judge the condition (at least executed once).

In loop control, break is used to exit the current loop; continue is used to skip the remaining part of the current loop and enter the next loop.

The definition format of a function is: return type function name (parameter list) { function body; return return value; }, for example:

int add(int a, int b) { // Returns int type, parameters are two ints

return a + b; // Returns the sum of the two numbers

}

The way to call a function is: function name (actual parameters), such as int sum = add (3, 5); (sum value is 8).

Function declaration: if the function is defined after it is called, it must be declared first (to inform the compiler of the function’s return type, name, and parameters), such as int add (int a, int b); (declaration can be written before the main function).

A recursive function is a function that calls itself, and it must have a termination condition (to avoid infinite recursion), such as calculating the factorial of n:

int factorial(int n) {

if (n == 1) return 1; // Termination condition

return n * factorial(n – 1); // Recursive call

}

Reading program questions in the preliminary exam often tests recursive logic, requiring manual simulation of the recursive process (e.g., calculating factorial (5): 5×4×3×2×1=120).

(4) Arrays

The definition format of a one-dimensional array is: data type array name [array size];, such as int a [10]; (defines an array of 10 int elements, with indices 0-9).

Its initialization methods include: int a [5] = {1, 2, 3}; (the first 3 elements are 1, 2, 3, and the last 2 are 0); int a [] = {1, 2, 3, 4}; (the array size is automatically set to 4).

Accessing a one-dimensional array is done through the index array name [index], such as a [0] (the first element), a [4] (the fifth element).

Common pitfalls with one-dimensional arrays: array indices start from 0, accessing a [10] (when defined as a [10]) will go out of bounds (accessing illegal memory, leading to program errors); array size must be a constant (e.g., const int n=5; int a [n]; is valid, int n=5; int a [n]; is invalid, C++ does not support variable-length arrays).

The definition format of a two-dimensional array is: data type array name [row count][column count];, such as int a [3][4]; (3 rows and 4 columns, totaling 12 elements).

Two-dimensional array initialization: int a [2][3] = {{1,2},{3}}; (the first row is 1, 2, 0, the second row is 3, 0, 0); int a [][3] = {1,2,3,4,5}; (the row count is automatically set to 2, the first row is 1, 2, 3, the second row is 4, 5, 0).

Accessing a two-dimensional array uses a [i][j] (the element in the i-th row and j-th column, where i starts from 0 and j starts from 0), such as a [1][2] is the element in the second row and third column.

5. Problem-Solving Techniques for the Preliminary Exam (Must-Know Practical Methods)

(1) Multiple Choice Question Solving Techniques

Substitution Method: For complete program multiple-choice questions, substitute the options into the code to verify the logic (e.g., judging the loop variable options, see if all elements can be traversed after substitution).

Exclusion Method: For calculation and concept questions, first eliminate obviously incorrect options (e.g., logically contradictory options) to narrow the selection range.

Keyword Positioning Method: When encountering concept questions (e.g., computer history, protocol types), grasp the keywords (e.g., “Turing Award”, “HTTP”), and associate them with corresponding knowledge points.

(2) Reading Program Question Solving Techniques

Manual Simulation Method: Use draft paper to record the initial values of variables and simulate the code execution line by line (especially in loops and recursion scenarios), avoiding “assuming”.

Proof by Contradiction: When judging “Is the program correct?” or “Is the output XX?”, construct special data (e.g., 0, maximum value, empty data) to verify whether the result contradicts the conclusion.

Focus on Core Logic: Ignore code details (e.g., variable names, comments), focus on the “purpose of loops/recursion” (e.g., traversing arrays to sum, recursively finding the greatest common divisor), quickly judge the program’s purpose.

(3) Completing Program Question Solving Techniques

Context Inference Method: Based on the logic of the code before and after the blank (e.g., if a max variable is defined before, and there is a statement outputting max after, the blank is likely to be traversing the array), infer the functionality that needs to be completed.

Template Matching Method: Memorize common code templates (e.g., for loop traversing arrays, sorting algorithm frameworks), if the blank matches the template structure, directly fill it in.

Syntax Verification Method: After completing, check whether the syntax is correct (e.g., matching parentheses, semicolon positions, variable type matching), to avoid low-level syntax errors.

(4) Time Management Techniques

Easy First, Hard Later: Prioritize completing multiple-choice questions (basic concept questions), simple reading program questions, and tackle difficult problems (e.g., complex recursion, nested loop questions) last.

Time Allocation: Strictly allocate time as “30 minutes for multiple-choice questions → 40 minutes for reading programs → 20 minutes for completing programs → 10 minutes for checking”, to avoid spending too much time on one type of question.

Check Focus: In the last 10 minutes, prioritize checking “high-risk questions”—such as questions about data type ranges in multiple-choice questions (e.g., distinguishing between int and long long), loop boundary calculations in reading program questions (e.g., whether i starts from 0 or 1), and syntax details in completing program questions (e.g., whether semicolons or parentheses are missing), as these are the most likely to lose points due to negligence.

6. Summary of Common Pitfalls (Avoidance Guide)

(1) Syntax-Related Pitfalls

Uninitialized Variables: Local variables without assigned values have random values, participating in calculations will lead to incorrect results; global variables are initialized to 0 by default, but it is recommended to manually assign values to all variable definitions (e.g., int sum=0;).

Array Index Out of Bounds: For example, defining int a [5]; (indices 0-4) but accessing a [5]; when looping through the array, writing the condition as i<=5 (the correct should be i<5 or i<=4) will lead to out-of-bounds access to illegal memory.

Operator Confusion: Writing “==” (comparison) as “=” (assignment), such as if (a=5) (actually assigns 5 to a, condition is always true); writing “&&” (logical AND) as “&” (bitwise AND), “||” (logical OR) as “|” (bitwise OR), leading to logical judgment errors.

Missing Semicolons and Parentheses: Missing semicolon after for loop condition (e.g., for (int i=1;i<=10 i++)); missing braces for if and loop statements, causing subsequent statements not to participate in branches/loops (e.g., if (a>5) cout<

Recursive Functions Without Termination Conditions: For example, when recursively calculating the Fibonacci sequence, if if (n==1||n==2) return 1; is not written, it will lead to infinite recursion and program crash.

(2) Logic-Related Pitfalls

Loop Boundary Calculation Errors: For example, “calculating the sum from 1 to 10”, writing the for loop as for (int i=0; i<10;i++) (i from 0 to 9, missing 10); writing the while loop condition as while (x>=1) (if x is initially 1, the loop executes once, correct; if x is initially 0, it does not execute, but must confirm whether it meets the requirements).

Branch Condition Order Reversal: For example, judging the range of x (x>10 outputs A, 5 <x<=10 outputs b, x<=5 outputs c), if first writing if (x>5), then if (x>10), it will lead to x>10 first entering the x>5 branch, unable to correctly output A. The correct order should first judge the smaller condition (first x>10, then 5 <x<=10, finally x<=5).

Ignoring Special Cases: For example, when “finding the maximum value in an array”, not considering the case where the array has only one element; when “calculating the average”, not considering the denominator being 0 (e.g., when the number of input data is 0); these special scenarios, if not handled, will lead to incomplete program logic.

Bitwise Operation Misunderstanding: Thinking that a>>1 (right shift by 1 bit) is completely equivalent to a/2 (the result is the same for positive numbers, but right shifting negative numbers may lead to different results due to sign bit filling 1, such as -3>>1=-2, while -3/2=-1); confusing the direction of left and right shifts (a<<1 is multiplied by 2, a>>1 is divided by 2, reversing this will lead to calculation errors).

(3) Concept-Related Pitfalls

Storage Unit Conversion Errors: Mistaking 1KB=1000B as decimal conversion (the actual is 2^10=1024B), for example, when calculating “how many KB is 1GB”, incorrectly concluding 1GB=1000×1000KB, the correct should be 1024×1024KB.

Confusing ASCII Codes: Mistaking the difference in ASCII codes between uppercase and lowercase letters (the correct difference is 32, such as ‘A’ is 65, ‘a’ is 97, 97-65=32); mistaking the ASCII code of ‘0’ as 0 (the correct is 48), leading to errors in character and number conversion (e.g., char c=’5′; int num=c-0; is incorrect, the correct should be num=c-‘0’;).

Confusing Sorting Algorithm Characteristics: Confusing the stability of sorting (e.g., thinking quicksort is stable, but it is actually unstable), time complexity (e.g., thinking bubble sort’s best time complexity is O(n²), but after optimization (adding a flag to check if already sorted) it is O(n)).

Confusing Computer System Concepts: Confusing the characteristics of RAM and ROM (RAM loses data when power is off, ROM retains data when power is off); confusing system software and application software (e.g., thinking Office is system software, but it is actually application software; Windows is system software).

C++ Preliminary Exam Preparation Guide

Leave a Comment