Solidify Your Programming Foundations and Sprint into Competitions!
To steadily score in programming competitions, a clear understanding of fundamental concepts is absolutely essential!
Hello, CSP-J competitors! Today, we will thoroughly cover the core introductory knowledge of C++ programming, from identifiers to the compilation process. Each concept is marked by its importance, accompanied by example code to help you understand and apply it accurately and flexibly.
Core Knowledge Checklist (Marked by Importance)
1. The “Basic Building Blocks” of the Programming World
🔴 High-Frequency Basic Concepts (Must Know! High-Frequency Competition Points)
Identifier: The “exclusive name” given to programming elements such as variables, functions, classes, and arrays in a program.
Naming Rules:
- 1. Composed of letters (A-Z/a-z), digits (0-9), and underscores (_).
- 2. Cannot start with a digit.
- 3. Case-sensitive (for example,
<span>age</span>,<span>Age</span>, and<span>AGE</span>are three different identifiers). - 4. Cannot have the same name as C++ keywords.
- 5. Suggested length is moderate, avoid being overly lengthy.
✅ Valid Examples: <span>student_name</span>, <span>score1</span>, <span>max_value</span>, <span>_temp</span>
❌ Invalid Examples: <span>123num</span> (starts with a digit), <span>a-b</span> (contains illegal character <span>-</span>), <span>int</span> (same as keyword), <span>my name</span> (contains space).
Keyword: Special words predefined and reserved in the C++ language, with fixed syntax meanings and usages.
Common Core Keywords (High Frequency in CSP-J):
- • Related to Data Types:
<span>int</span>,<span>char</span>,<span>double</span>,<span>bool</span>,<span>void</span> - • Related to Control Statements:
<span>if</span>,<span>else</span>,<span>for</span>,<span>while</span>,<span>break</span>,<span>continue</span>,<span>return</span> - • Other Commonly Used:
<span>const</span>,<span>using</span>,<span>namespace</span>,<span>class</span>
Note: All keywords are in lowercase, for example, <span>Int</span> and <span>IF</span> are not keywords and can be used as identifiers (but not recommended, as they can cause confusion).
Constant: A value that remains fixed and unchanging during the program’s execution.
Classification and Definition Methods:
- 1. Literals (written directly):
- • Integer Constants:
<span>10</span>,<span>012</span>(octal),<span>0xA</span>(hexadecimal). - • Floating-Point Constants:
<span>3.14</span>,<span>6.28e2</span>(scientific notation). - • Character Constants:
<span>'A'</span>,<span>'5'</span>,<span>'+'</span> - • String Constants:
<span>"CSP-J"</span>,<span>"Hello World"</span> - • Boolean Constants:
<span>true</span>,<span>false</span>
const int MAX_N = 1000; // Define integer constant
const double PI = 3.1415926; // Define floating-point constant
const char DEFAULT_CHAR = '0'; // Define character constant
#define MIN_SCORE 60
#define MAX_ARRAY_SIZE 10000
Purpose:
- • Avoid “magic numbers” and improve code readability.
- • Facilitate code modification.
- • Ensure data security.
Competition Suggestion: Prefer using <span>const</span> to define constants, as it is type-safe and more syntactically correct.
Variable: A quantity whose value can be dynamically modified during the program’s execution.
Definition and Initialization:
int age; // Define integer variable age, uninitialized
int score = 0; // Define integer variable score, initial value 0
double height = 1.75; // Define double precision floating variable
char gender = 'M'; // Define character variable
bool isPass = true; // Define boolean variable
int a = 10, b = 20, c; // Define multiple variables simultaneously
Variable Usage:
int x = 5, y = 3;
x = 10; // Assignment: change the value of x to 10
int z = x + y; // Participate in calculation: z's value is 13
y = z * 2; // Assignment: change the value of y to 26
String: A sequence of characters consisting of zero or more characters.
Two Representation Methods:
- 1. C-style Strings:
#include <cstring> char str1[] = "Hello"; // Automatically adds '\0' at the end char str2[10] = "CSP-J"; // Array length is 10 char str3[] = {'H', 'i', '\0'}; // Must manually add '\0' - 2. C++ Standard Strings:
#include <string> using namespace std; string s1; // Define empty string string s2 = "CSP-J 2025"; // Initialize string string s3 = s2 + " 加油"; // String concatenation int len = s3.size(); // Get string length s1 = "Hello"; // Direct assignment
Competition Note: <span>string</span> class usage is more concise, recommended to use it preferentially.
Expression: A formula composed of constants, variables, operators, etc.
Classification and Examples:
- 1. Arithmetic Expressions:
<span>3 + 5 * 2</span>,<span>(a + b) / 2</span>,<span>x % 3</span>,<span>++count</span> - 2. Relational Expressions:
<span>score > 90</span>,<span>x == y</span>,<span>a != b</span>,<span>age >= 18</span> - 3. Logical Expressions:
<span>(score > 90) && (age < 20)</span>,<span>(a == 0) || (b == 0)</span>,<span>!isPass</span> - 4. Assignment Expressions:
<span>x = 5</span>,<span>a = b = 3</span> - 5. Function Call Expressions:
<span>sqrt(16)</span>,<span>max(3,5)</span>
Precedence: Arithmetic Operators > Relational Operators > Logical Operators > Assignment Operators.
int a = 3, b = 5, c = 2;
bool res1 = a + b > c * 3; // 8 > 6 → true
bool res2 = a > b || c < a; // false || true → true
int res3 = (a + b) * c; // Parentheses change precedence, result is 16
🔴 Core Differences Between Constants and Variables (Common Confusion)
| Feature | Constant | Variable |
|---|---|---|
| Value Mutability | Cannot be modified during program execution. | Can be modified during program execution. |
| Definition Method | <span>const type name=value</span> or <span>#define name value</span> |
<span>type name</span> or <span>type name=value</span> |
| Data Type | <span>const</span> constants have a defined type. |
Have a defined data type. |
| Competition Role | Store fixed parameters, avoid magic numbers. | Store dynamic data, calculate intermediate results. |
2. The “Execution Foundation” of C++ Programs
🔴 Header Files and Namespaces (Must Understand! Prerequisite for Program Compilation)
Header Files: “Basic tool” files that contain function declarations, class definitions, etc.
Common System Header Files Used in Competitions:
- •
<span><iostream></span>: Standard input/output stream (<span>cin</span>,<span>cout</span>). - •
<span><cstdio></span>: C-style input/output (<span>scanf</span>,<span>printf</span>). - •
<span><string></span>: C++<span>string</span>class. - •
<span><cstring></span>: C-style string handling. - •
<span><cmath></span>: Mathematical functions. - •
<span><vector></span>: Dynamic array container. - •
<span><algorithm></span>: Common algorithms.
Example Code:
#include <iostream> // Using cout, cin
#include <cstdio> // Using scanf, printf
#include <string> // Using string class
#include <cmath> // Using sqrt
using namespace std;
int main() {
string s = "CSP-J";
cout << s << endl;
int x;
scanf("%d", &x);
double y = sqrt(x);
printf("sqrt(%d) = %.2f\n", x, y);
return 0;
}
Namespace: A mechanism to resolve identifier name conflicts.
Usage Methods:
- 1. Direct Specification:
std::string s = "Hello"; std::cout << s << std::endl; - 2. Global Declaration (Commonly Used in Competitions):
using namespace std; string s = "Hello"; // Direct usage cout << s << endl; - 3. Declare Specific Identifiers:
using std::cout; using std::endl; cout << "Hello" << endl;
🔴 The “Birth Process” of a Program: Edit → Compile → Link → Run
Edit: Write C++ source code (<span>.cpp</span> file).
Compile: Translate source code into machine language, generating object files.
g++ -c test.cpp -o test.o
Link: Merge object files with library files to generate executable files.
g++ test.o -o test.exe
Run: Execute the executable file and output results.
Compiled vs Interpreted:
| Feature | Compiled (C++) | Interpreted (Python) |
|---|---|---|
| Execution Prerequisite | Must compile to generate an executable file. | Directly run source code. |
| Execution Speed | Fast. | Slow. |
| Cross-Platform Compatibility | Must compile for different systems. | Source code can run directly across platforms. |
🔴 Debugging: A Key Step in Identifying Program Errors
Common Error Types:
- 1. Syntax Errors: Errors reported during compilation, such as missing semicolons or mismatched parentheses.
- 2. Linking Errors: Errors reported during linking, such as undefined references.
- 3. Logical Errors: Results that do not meet expectations during execution.
Debugging Methods:
// Requirement: Calculate the sum from 1 to 10, expected result 55
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i < 10; i++) { // Logical error: i<10 should be i<=10
sum += i;
cout << "i=" << i << ", sum=" << sum << endl; // Print intermediate results
}
cout << "Final sum:" << sum << endl; // Incorrect result 45
return 0;
}
CSP-J Preparation Tips 💡
- 1. Identifier Naming: Follow the principle of “name indicates meaning”, it is recommended to use English words.
- 2. Constants and Variables: Prefer using
<span>const</span>to define constants, and ensure variables are initialized. - 3. Header Files: Include as needed, directly use
<span>using namespace std;</span>in competitions. - 4. Expressions: Remember operator precedence, it is recommended to use the
<span>string</span>class for strings. - 5. Debugging: Check line numbers and hints for compilation errors, use
<span>cout</span>to print intermediate variables for logical errors.
Upcoming Updates Announcement 📢
The next article will explain “Data Types, Operators, and Expression Precedence”, which are fundamental points for CSP-J multiple-choice and programming questions. Stay tuned!
If this article has been helpful to you, feel free to like and bookmark it. Don’t get lost in preparing for CSP-J! If you have any questions, please leave a comment below!
Tags: #CSP-J #Programming Basics #Competition Preparation