注意:这篇文章上次更新于1830天前,文章内容可能已经过时。
This article was last updated1830 days ago, the content may be outdated.
C++初识
第一个C++程序
编写一个C++程序总共分为4个步骤
- 创建项目
- 创建文件
- 编写代码
- 运行程序
创建项目
Visual Studio是我们用来编写C++程序的主要工具,我们先将它打开


创建文件
右键源文件,选择添加->新建项

给C++文件起个名称,然后点击添加即可。

编写代码
Getting Started with C++
Your First C++ Program
Writing a C++ program involves 4 steps in total
- Create a project
- Create a file
- Write the code
- Run the program
Creating a Project
Visual Studio is the main tool we use to write C++ programs, so let’s open it first


Creating a File
Right-click the Source Files, choose Add -> New Item

Give the C++ file a name, then click Add.

Writing the Code
1 |
|
注释
作用:在代码中加一些说明和解释,方便自己或其他程序员程序员阅读代码
两种格式
- 单行注释:
// 描述信息- 通常放在一行代码的上方,或者一条语句的末尾,对该行代码说明
- 多行注释:
/* 描述信息 */- 通常放在一段代码的上方,对该段代码做整体说明
提示:编译器在编译代码时,会忽略注释的内容
Comments
Purpose: add some notes and explanations to the code, making it easier for yourself or other programmers to read
Two formats
- Single-line comment:
// description- Usually placed above a line of code, or at the end of a statement, to explain that line of code
- Multi-line comment:
/* description */- Usually placed above a block of code, to give an overall explanation of that block of code
Tip: the compiler ignores comments when compiling code
Variables
Purpose: give a name to a specified block of memory so it is easier to operate on that memory
Syntax: data type variable name = initial value;
Example:
1 |
|
注意:C++在创建变量时,必须给变量一个初始值,否则会报错
常量
作用:用于记录程序中不可更改的数据
C++定义常量两种方式
-
#define 宏常量:
#define 常量名 常量值- 通常在文件上方定义,表示一个常量
-
const修饰的变量
const 数据类型 常量名 = 常量值- 通常在变量定义前加关键字const,修饰该变量为常量,不可修改
示例:
Note: when creating a variable in C++, you must give it an initial value, otherwise an error will occur
Constants
Purpose: used to record data that cannot be changed in the program
There are two ways to define constants in C++
-
#define macro constant:
#define constant name constant value- Usually defined at the top of the file, representing a constant
-
const-modified variable
const data type constant name = constant value- Usually add the keyword const before the variable definition, modifying the variable into a constant that cannot be changed
Example:
1 | //1、宏常量 |
关键字
**作用:**关键字是C++中预先保留的单词(标识符)
- 在定义变量或者常量时候,不要用关键字
C++关键字如下:
| asm | do | if | return | typedef |
|---|---|---|---|---|
| auto | double | inline | short | typeid |
| bool | dynamic_cast | int | signed | typename |
| break | else | long | sizeof | union |
| case | enum | mutable | static | unsigned |
| catch | explicit | namespace | static_cast | using |
| char | export | new | struct | virtual |
| class | extern | operator | switch | void |
| const | false | private | template | volatile |
| const_cast | float | protected | this | wchar_t |
| continue | for | public | throw | while |
| default | friend | register | true | |
| delete | goto | reinterpret_cast | try |
提示:在给变量或者常量起名称时候,不要用C++得关键字,否则会产生歧义。
Keywords
Purpose: keywords are words (identifiers) pre-reserved in C++
- Do not use keywords when defining variables or constants
The C++ keywords are as follows:
| asm | do | if | return | typedef |
|---|---|---|---|---|
| auto | double | inline | short | typeid |
| bool | dynamic_cast | int | signed | typename |
| break | else | long | sizeof | union |
| case | enum | mutable | static | unsigned |
| catch | explicit | namespace | static_cast | using |
| char | export | new | struct | virtual |
| class | extern | operator | switch | void |
| const | false | private | template | volatile |
| const_cast | float | protected | this | wchar_t |
| continue | for | public | throw | while |
| default | friend | register | true | |
| delete | goto | reinterpret_cast | try |
Tip: when naming variables or constants, do not use C++ keywords, otherwise ambiguity will arise.
标识符命名规则
作用:C++规定给标识符(变量、常量)命名时,有一套自己的规则
- 标识符不能是关键字
- 标识符只能由字母、数字、下划线组成
- 第一个字符必须为字母或下划线
- 标识符中字母区分大小写
建议:给标识符命名时,争取做到见名知意的效果,方便自己和他人的阅读
Identifier Naming Rules
Purpose: C++ specifies that when naming identifiers (variables, constants), there is a set of rules to follow
- Identifiers cannot be keywords
- Identifiers can only consist of letters, digits, and underscores
- The first character must be a letter or an underscore
- Identifiers are case-sensitive
Suggestion: when naming identifiers, try to make the name self-explanatory, so it is easier for yourself and others to read
Data Types
C++ requires that when creating a variable or constant, the corresponding data type must be specified, otherwise memory cannot be allocated for the variable
整型
作用:整型变量表示的是整数类型的数据
C++中能够表示整型的类型有以下几种方式,区别在于所占内存空间不同:
| 数据类型 | 占用空间 | 取值范围 |
|---|---|---|
| short(短整型) | 2字节 | (-2^15 ~ 2^15-1) |
| int(整型) | 4字节 | (-2^31 ~ 2^31-1) |
| long(长整形) | Windows为4字节,Linux为4字节(32位),8字节(64位) | (-2^31 ~ 2^31-1) |
| long long(长长整形) | 8字节 | (-2^63 ~ 2^63-1) |
Integer Types
Purpose: integer variables represent integer type data
C++ provides the following types to represent integers, which differ in the amount of memory they occupy:
| Data Type | Memory Occupied | Value Range |
|---|---|---|
| short (short integer) | 2 bytes | (-2^15 ~ 2^15-1) |
| int (integer) | 4 bytes | (-2^31 ~ 2^31-1) |
| long (long integer) | 4 bytes on Windows, 4 bytes (32-bit) or 8 bytes (64-bit) on Linux | (-2^31 ~ 2^31-1) |
| long long (long long integer) | 8 bytes | (-2^63 ~ 2^63-1) |
The sizeof Keyword
Purpose: the sizeof keyword can be used to calculate the amount of memory occupied by a data type
Syntax: sizeof( data type / variable)
Example:
1 | int main() { |
整型结论:short < int <= long <= long long
Integer type conclusion: short < int <= long <= long long
实型(浮点型)
作用:用于表示小数
浮点型变量分为两种:
- 单精度float
- 双精度double
两者的区别在于表示的有效数字范围不同。
| 数据类型 | 占用空间 | 有效数字范围 |
|---|---|---|
| float | 4字节 | 7位有效数字 |
| double | 8字节 | 15~16位有效数字 |
示例:
Floating-Point Types (Real Types)
Purpose: used to represent decimals
Floating-point variables are divided into two types:
- Single-precision float
- Double-precision double
The difference between them lies in the range of significant digits they can represent.
| Data Type | Memory Occupied | Significant Digits |
|---|---|---|
| float | 4 bytes | 7 significant digits |
| double | 8 bytes | 15~16 significant digits |
Example:
1 | int main() { |
字符型
**作用:**字符型变量用于显示单个字符
语法:char ch = 'a';
注意1:在显示字符型变量时,用单引号将字符括起来,不要用双引号
注意2:单引号内只能有一个字符,不可以是字符串
- C和C++中字符型变量只占用1个字节。
- 字符型变量并不是把字符本身放到内存中存储,而是将对应的ASCII编码放入到存储单元
示例:
Character Type
Purpose: character-type variables are used to display a single character
Syntax: char ch = 'a';
Note 1: when displaying a character variable, enclose the character in single quotes, not double quotes
Note 2: only one character is allowed inside single quotes, not a string
- In C and C++, a character variable occupies only 1 byte.
- A character variable does not store the character itself in memory; instead, it stores the corresponding ASCII code in the memory unit
Example:
1 | int main() { |
ASCII码表格:
| ASCII值 | 控制字符 | ASCII值 | 字符 | ASCII值 | 字符 | ASCII值 | 字符 |
|---|---|---|---|---|---|---|---|
| 0 | NUT | 32 | (space) | 64 | @ | 96 | 、 |
| 1 | SOH | 33 | ! | 65 | A | 97 | a |
| 2 | STX | 34 | " | 66 | B | 98 | b |
| 3 | ETX | 35 | # | 67 | C | 99 | c |
| 4 | EOT | 36 | $ | 68 | D | 100 | d |
| 5 | ENQ | 37 | % | 69 | E | 101 | e |
| 6 | ACK | 38 | & | 70 | F | 102 | f |
| 7 | BEL | 39 | , | 71 | G | 103 | g |
| 8 | BS | 40 | ( | 72 | H | 104 | h |
| 9 | HT | 41 | ) | 73 | I | 105 | i |
| 10 | LF | 42 | * | 74 | J | 106 | j |
| 11 | VT | 43 | + | 75 | K | 107 | k |
| 12 | FF | 44 | , | 76 | L | 108 | l |
| 13 | CR | 45 | - | 77 | M | 109 | m |
| 14 | SO | 46 | . | 78 | N | 110 | n |
| 15 | SI | 47 | / | 79 | O | 111 | o |
| 16 | DLE | 48 | 0 | 80 | P | 112 | p |
| 17 | DCI | 49 | 1 | 81 | Q | 113 | q |
| 18 | DC2 | 50 | 2 | 82 | R | 114 | r |
| 19 | DC3 | 51 | 3 | 83 | S | 115 | s |
| 20 | DC4 | 52 | 4 | 84 | T | 116 | t |
| 21 | NAK | 53 | 5 | 85 | U | 117 | u |
| 22 | SYN | 54 | 6 | 86 | V | 118 | v |
| 23 | TB | 55 | 7 | 87 | W | 119 | w |
| 24 | CAN | 56 | 8 | 88 | X | 120 | x |
| 25 | EM | 57 | 9 | 89 | Y | 121 | y |
| 26 | SUB | 58 | : | 90 | Z | 122 | z |
| 27 | ESC | 59 | ; | 91 | [ | 123 | { |
| 28 | FS | 60 | < | 92 | / | 124 | | |
| 29 | GS | 61 | = | 93 | ] | 125 | } |
| 30 | RS | 62 | > | 94 | ^ | 126 | ` |
| 31 | US | 63 | ? | 95 | _ | 127 | DEL |
ASCII 码大致由以下两部分组成:
- ASCII 非打印控制字符: ASCII 表上的数字 0-31 分配给了控制字符,用于控制像打印机等一些外围设备。
- ASCII 打印字符:数字 32-126 分配给了能在键盘上找到的字符,当查看或打印文档时就会出现。
ASCII code table:
| ASCII | Control | ASCII | Char | ASCII | Char | ASCII | Char |
|---|---|---|---|---|---|---|---|
| 0 | NUT | 32 | (space) | 64 | @ | 96 | 、 |
| 1 | SOH | 33 | ! | 65 | A | 97 | a |
| 2 | STX | 34 | " | 66 | B | 98 | b |
| 3 | ETX | 35 | # | 67 | C | 99 | c |
| 4 | EOT | 36 | $ | 68 | D | 100 | d |
| 5 | ENQ | 37 | % | 69 | E | 101 | e |
| 6 | ACK | 38 | & | 70 | F | 102 | f |
| 7 | BEL | 39 | , | 71 | G | 103 | g |
| 8 | BS | 40 | ( | 72 | H | 104 | h |
| 9 | HT | 41 | ) | 73 | I | 105 | i |
| 10 | LF | 42 | * | 74 | J | 106 | j |
| 11 | VT | 43 | + | 75 | K | 107 | k |
| 12 | FF | 44 | , | 76 | L | 108 | l |
| 13 | CR | 45 | - | 77 | M | 109 | m |
| 14 | SO | 46 | . | 78 | N | 110 | n |
| 15 | SI | 47 | / | 79 | O | 111 | o |
| 16 | DLE | 48 | 0 | 80 | P | 112 | p |
| 17 | DCI | 49 | 1 | 81 | Q | 113 | q |
| 18 | DC2 | 50 | 2 | 82 | R | 114 | r |
| 19 | DC3 | 51 | 3 | 83 | S | 115 | s |
| 20 | DC4 | 52 | 4 | 84 | T | 116 | t |
| 21 | NAK | 53 | 5 | 85 | U | 117 | u |
| 22 | SYN | 54 | 6 | 86 | V | 118 | v |
| 23 | TB | 55 | 7 | 87 | W | 119 | w |
| 24 | CAN | 56 | 8 | 88 | X | 120 | x |
| 25 | EM | 57 | 9 | 89 | Y | 121 | y |
| 26 | SUB | 58 | : | 90 | Z | 122 | z |
| 27 | ESC | 59 | ; | 91 | [ | 123 | { |
| 28 | FS | 60 | < | 92 | / | 124 | | |
| 29 | GS | 61 | = | 93 | ] | 125 | } |
| 30 | RS | 62 | > | 94 | ^ | 126 | ` |
| 31 | US | 63 | ? | 95 | _ | 127 | DEL |
The ASCII code table roughly consists of the following two parts:
- ASCII non-printing control characters: numbers 0-31 on the ASCII table are assigned to control characters, used to control peripheral devices such as printers.
- ASCII printable characters: numbers 32-126 are assigned to characters that can be found on the keyboard, which appear when viewing or printing documents.
转义字符
**作用:**用于表示一些不能显示出来的ASCII字符
现阶段我们常用的转义字符有:\n \\ \t
| 转义字符 | 含义 | ASCII码值(十进制) |
|---|---|---|
| \a | 警报 | 007 |
| \b | 退格(BS) ,将当前位置移到前一列 | 008 |
| \f | 换页(FF),将当前位置移到下页开头 | 012 |
| \n | 换行(LF) ,将当前位置移到下一行开头 | 010 |
| \r | 回车(CR) ,将当前位置移到本行开头 | 013 |
| \t | 水平制表(HT) (跳到下一个TAB位置) | 009 |
| \v | 垂直制表(VT) | 011 |
| \\ | 代表一个反斜线字符"" | 092 |
| ’ | 代表一个单引号(撇号)字符 | 039 |
| " | 代表一个双引号字符 | 034 |
| ? | 代表一个问号 | 063 |
| \0 | 数字0 | 000 |
| \ddd | 8进制转义字符,d范围0~7 | 3位8进制 |
| \xhh | 16进制转义字符,h范围09,af,A~F | 3位16进制 |
示例:
Escape Characters
Purpose: used to represent some ASCII characters that cannot be displayed
The escape characters we commonly use at this stage are: \n \\ \t
| Escape Character | Meaning | ASCII Code (decimal) |
|---|---|---|
| \a | Bell (alert) | 007 |
| \b | Backspace (BS), moves the current position to the previous column | 008 |
| \f | Form feed (FF), moves the current position to the beginning of the next page | 012 |
| \n | Line feed (LF), moves the current position to the beginning of the next line | 010 |
| \r | Carriage return (CR), moves the current position to the beginning of the current line | 013 |
| \t | Horizontal tab (HT) (jump to the next TAB position) | 009 |
| \v | Vertical tab (VT) | 011 |
| \\ | Represents a backslash character "" | 092 |
| ’ | Represents a single quote (apostrophe) character | 039 |
| " | Represents a double quote character | 034 |
| ? | Represents a question mark | 063 |
| \0 | The digit 0 | 000 |
| \ddd | Octal escape character, d ranges from 0 to 7 | 3-digit octal |
| \xhh | Hexadecimal escape character, h ranges from 0-9, a-f, A-F | 3-digit hexadecimal |
Example:
1 | int main() { |
String Type
Purpose: used to represent a string of characters
Two styles
-
C-style string:
char variableName[] = "string value"Example:
1 | int main() { |
注意:C风格的字符串要用双引号括起来
-
C++风格字符串:
string 变量名 = "字符串值"示例:
Note: C-style strings must be enclosed in double quotes
-
C+±style string:
string variableName = "string value"Example:
1 | int main() { |
注意:C++风格字符串,需要加入头文件==#include<string>==
Note: C+±style strings require the header file #include<string>
Boolean Type bool
Purpose: the boolean data type represents a true or false value
The bool type has only two values:
- true — true (essentially 1)
- false — false (essentially 0)
The bool type occupies 1 byte
Example:
1 | int main() { |
Data Input
Purpose: used to get data from the keyboard
Keyword: cin
Syntax: cin >> variable
Example:
1 | int main(){ |
运算符
**作用:**用于执行代码的运算
本章我们主要讲解以下几类运算符:
| 运算符类型 | 作用 |
|---|---|
| 算术运算符 | 用于处理四则运算 |
| 赋值运算符 | 用于将表达式的值赋给变量 |
| 比较运算符 | 用于表达式的比较,并返回一个真值或假值 |
| 逻辑运算符 | 用于根据表达式的值返回真值或假值 |
Operators
Purpose: used to perform operations on code
In this chapter we mainly explain the following types of operators:
| Operator Type | Purpose |
|---|---|
| Arithmetic operators | Used to handle the four basic arithmetic operations |
| Assignment operators | Used to assign the value of an expression to a variable |
| Comparison operators | Used to compare expressions and return a true or false value |
| Logical operators | Used to return a true or false value based on the value of an expression |
算术运算符
作用:用于处理四则运算
算术运算符包括以下符号:
| 运算符 | 术语 | 示例 | 结果 |
|---|---|---|---|
| + | 正号 | +3 | 3 |
| - | 负号 | -3 | -3 |
| + | 加 | 10 + 5 | 15 |
| - | 减 | 10 - 5 | 5 |
| * | 乘 | 10 * 5 | 50 |
| / | 除 | 10 / 5 | 2 |
| % | 取模(取余) | 10 % 3 | 1 |
| ++ | 前置递增 | a=2; b=++a; | a=3; b=3; |
| ++ | 后置递增 | a=2; b=a++; | a=3; b=2; |
| – | 前置递减 | a=2; b=–a; | a=1; b=1; |
| – | 后置递减 | a=2; b=a–; | a=1; b=2; |
示例1:
Arithmetic Operators
Purpose: used to handle the four basic arithmetic operations
Arithmetic operators include the following symbols:
| Operator | Term | Example | Result |
|---|---|---|---|
| + | Positive sign | +3 | 3 |
| - | Negative sign | -3 | -3 |
| + | Addition | 10 + 5 | 15 |
| - | Subtraction | 10 - 5 | 5 |
| * | Multiplication | 10 * 5 | 50 |
| / | Division | 10 / 5 | 2 |
| % | Modulo (remainder) | 10 % 3 | 1 |
| ++ | Pre-increment | a=2; b=++a; | a=3; b=3; |
| ++ | Post-increment | a=2; b=a++; | a=3; b=2; |
| – | Pre-decrement | a=2; b=–a; | a=1; b=1; |
| – | Post-decrement | a=2; b=a–; | a=1; b=2; |
Example 1:
1 | //加减乘除 |
总结:在除法运算中,除数不能为0
示例2:
Summary: in division, the divisor cannot be 0
Example 2:
1 | //取模 |
总结:只有整型变量可以进行取模运算
示例3:
Summary: only integer variables can perform the modulo operation
Example 3:
1 | //递增 |
总结:前置递增先对变量进行++,再计算表达式,后置递增相反
Summary: pre-increment performs ++ on the variable first, then evaluates the expression; post-increment is the opposite
赋值运算符
**作用:**用于将表达式的值赋给变量
赋值运算符包括以下几个符号:
| 运算符 | 术语 | 示例 | 结果 |
|---|---|---|---|
| = | 赋值 | a=2; b=3; | a=2; b=3; |
| += | 加等于 | a=0; a+=2; | a=2; |
| -= | 减等于 | a=5; a-=3; | a=2; |
| *= | 乘等于 | a=2; a*=2; | a=4; |
| /= | 除等于 | a=4; a/=2; | a=2; |
| %= | 模等于 | a=3; a%2; | a=1; |
示例:
Assignment Operators
Purpose: used to assign the value of an expression to a variable
Assignment operators include the following symbols:
| Operator | Term | Example | Result |
|---|---|---|---|
| = | Assign | a=2; b=3; | a=2; b=3; |
| += | Add and assign | a=0; a+=2; | a=2; |
| -= | Subtract and assign | a=5; a-=3; | a=2; |
| *= | Multiply and assign | a=2; a*=2; | a=4; |
| /= | Divide and assign | a=4; a/=2; | a=2; |
| %= | Modulo and assign | a=3; a%2; | a=1; |
Example:
1 | int main() { |
比较运算符
**作用:**用于表达式的比较,并返回一个真值或假值
比较运算符有以下符号:
| 运算符 | 术语 | 示例 | 结果 |
|---|---|---|---|
| == | 相等于 | 4 == 3 | 0 |
| != | 不等于 | 4 != 3 | 1 |
| < | 小于 | 4 < 3 | 0 |
| > | 大于 | 4 > 3 | 1 |
| <= | 小于等于 | 4 <= 3 | 0 |
| >= | 大于等于 | 4 >= 1 | 1 |
示例:
Comparison Operators
Purpose: used to compare expressions and return a true or false value
Comparison operators include the following symbols:
| Operator | Term | Example | Result |
|---|---|---|---|
| == | Equal to | 4 == 3 | 0 |
| != | Not equal to | 4 != 3 | 1 |
| < | Less than | 4 < 3 | 0 |
| > | Greater than | 4 > 3 | 1 |
| <= | Less than or equal to | 4 <= 3 | 0 |
| >= | Greater than or equal to | 4 >= 1 | 1 |
Example:
1 | int main() { |
注意:C和C++ 语言的比较运算中, “真”用数字“1”来表示, “假”用数字“0”来表示。
Note: in comparison operations in C and C++, “true” is represented by the number “1” and “false” by the number “0”.
逻辑运算符
**作用:**用于根据表达式的值返回真值或假值
逻辑运算符有以下符号:
| 运算符 | 术语 | 示例 | 结果 |
|---|---|---|---|
| ! | 非 | !a | 如果a为假,则!a为真; 如果a为真,则!a为假。 |
| && | 与 | a && b | 如果a和b都为真,则结果为真,否则为假。 |
| || | 或 | a || b | 如果a和b有一个为真,则结果为真,二者都为假时,结果为假。 |
**示例1:**逻辑非
Logical Operators
Purpose: used to return a true or false value based on the value of an expression
Logical operators include the following symbols:
| Operator | Term | Example | Result |
|---|---|---|---|
| ! | NOT | !a | If a is false, !a is true; if a is true, !a is false. |
| && | AND | a && b | If both a and b are true, the result is true; otherwise it is false. |
| || | OR | a || b | If either a or b is true, the result is true; when both are false, the result is false. |
Example 1: Logical NOT
1 | //逻辑运算符 --- 非 |
总结: 真变假,假变真
**示例2:**逻辑与
Summary: true becomes false, false becomes true
Example 2: Logical AND
1 | //逻辑运算符 --- 与 |
总结:逻辑与运算符总结: 同真为真,其余为假
**示例3:**逻辑或
Summary of the logical AND operator: true only when both are true; false otherwise
Example 3: Logical OR
1 | //逻辑运算符 --- 或 |
逻辑或运算符总结: 同假为假,其余为真
Summary of the logical OR operator: false only when both are false; true otherwise
程序流程结构
C/C++支持最基本的三种程序运行结构:顺序结构、选择结构、循环结构
- 顺序结构:程序按顺序执行,不发生跳转
- 选择结构:依据条件是否满足,有选择的执行相应功能
- 循环结构:依据条件是否满足,循环多次执行某段代码
Program Flow Control
C/C++ supports three basic program execution structures: sequential structure, selection structure, and loop structure
- Sequential structure: the program executes in order without jumps
- Selection structure: based on whether the condition is satisfied, the corresponding function is selectively executed
- Loop structure: based on whether the condition is satisfied, a piece of code is executed repeatedly
4.1 选择结构
if语句
**作用:**执行满足条件的语句
if语句的三种形式
-
单行格式if语句
-
多行格式if语句
-
多条件的if语句
-
单行格式if语句:
if(条件){ 条件满足执行的语句 }
示例:
4.1 Selection Structure
if Statement
Purpose: executes the statements that satisfy a condition
The three forms of the if statement
-
Single-line if statement
-
Multi-line if statement
-
Multi-condition if statement
-
Single-line if statement:
if(condition){ statement executed when the condition is satisfied }
Example:
1 | int main() { |
注意:if条件表达式后不要加分号
- 多行格式if语句:
if(条件){ 条件满足执行的语句 }else{ 条件不满足执行的语句 };

示例:
Note: do not add a semicolon after the if condition expression
- Multi-line if statement:
if(condition){ statement executed when the condition is satisfied }else{ statement executed when the condition is not satisfied };

Example:
1 | int main() { |
- 多条件的if语句:
if(条件1){ 条件1满足执行的语句 }else if(条件2){条件2满足执行的语句}... else{ 都不满足执行的语句}

示例:
- Multi-condition if statement:
if(condition 1){ statement executed when condition 1 is satisfied }else if(condition 2){ statement executed when condition 2 is satisfied }... else{ statement executed when none is satisfied }

Example:
1 | int main() { |
嵌套if语句:在if语句中,可以嵌套使用if语句,达到更精确的条件判断
案例需求:
- 提示用户输入一个高考考试分数,根据分数做如下判断
- 分数如果大于600分视为考上一本,大于500分考上二本,大于400考上三本,其余视为未考上本科;
- 在一本分数中,如果大于700分,考入北大,大于650分,考入清华,大于600考入人大。
示例:
Nested if statements: inside an if statement, you can nest another if statement to achieve more precise condition checking
Case requirements:
- Prompt the user to enter a college entrance exam score and make the following judgments based on the score
- A score greater than 600 is considered admitted to a first-tier university, greater than 500 to a second-tier university, greater than 400 to a third-tier university, otherwise considered not admitted to any undergraduate university;
- For scores in the first-tier range, a score greater than 700 means admitted to Peking University, greater than 650 means admitted to Tsinghua University, greater than 600 means admitted to Renmin University.
Example:
1 | int main() { |
练习案例: 三只小猪称体重
有三只小猪ABC,请分别输入三只小猪的体重,并且判断哪只小猪最重?
Practice case: Three little pigs weigh themselves
There are three little pigs, A, B, and C. Please enter the weight of each pig and determine which one is the heaviest?
三目运算符
作用: 通过三目运算符实现简单的判断
语法:表达式1 ? 表达式2 :表达式3
解释:
如果表达式1的值为真,执行表达式2,并返回表达式2的结果;
如果表达式1的值为假,执行表达式3,并返回表达式3的结果。
示例:
Ternary Operator
Purpose: implement simple judgments through the ternary operator
Syntax: expression1 ? expression2 : expression3
Explanation:
If the value of expression1 is true, expression2 is executed and its result is returned;
If the value of expression1 is false, expression3 is executed and its result is returned.
Example:
1 | int main() { |
总结:和if语句比较,三目运算符优点是短小整洁,缺点是如果用嵌套,结构不清晰
Summary: compared with the if statement, the advantage of the ternary operator is that it is short and tidy; the disadvantage is that if nested, the structure is not clear
1 | switch(表达式) |
示例:
Example:
1 | int main() { |
注意1:switch语句中表达式类型只能是整型或者字符型
注意2:case里如果没有break,那么程序会一直向下执行
总结:与if语句比,对于多条件判断时,switch的结构清晰,执行效率高,缺点是switch不可以判断区间
Note 1: the expression type in a switch statement can only be integer or character
Note 2: if there is no break in a case, the program will continue to execute downward
Summary: compared with the if statement, for multi-condition judgments, the switch structure is clear and executes efficiently; the disadvantage is that switch cannot judge ranges
Loop Structures
while Loop Statement
Purpose: while the loop condition is satisfied, execute the loop statements
Syntax: while(loop condition){ loop statements }
Explanation: as long as the result of the loop condition is true, the loop statements are executed

Example:
1 | int main() { |
注意:在执行循环语句时候,程序必须提供跳出循环的出口,否则出现死循环
while循环练习案例:猜数字
**案例描述:**系统随机生成一个1到100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果猜对恭喜玩家胜利,并且退出游戏。

Note: when executing loop statements, the program must provide an exit to break out of the loop, otherwise an infinite loop will occur
while loop practice case: Guess the number
Case description: the system randomly generates a number between 1 and 100, and the player guesses it. If the guess is wrong, prompt the player that the number is too large or too small. If the guess is correct, congratulate the player on winning and exit the game.

do…while循环语句
作用: 满足循环条件,执行循环语句
语法: do{ 循环语句 } while(循环条件);
**注意:**与while的区别在于do…while会先执行一次循环语句,再判断循环条件

示例:
do…while Loop Statement
Purpose: while the loop condition is satisfied, execute the loop statements
Syntax: do{ loop statements } while(loop condition);
Note: the difference from while is that do…while executes the loop statements once first, then checks the loop condition

Example:
1 | int main() { |
总结:与while循环区别在于,do…while先执行一次循环语句,再判断循环条件
练习案例:水仙花数
**案例描述:**水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身
例如:1^3 + 5^3+ 3^3 = 153
请利用do…while语句,求出所有3位数中的水仙花数
Summary: the difference from the while loop is that do…while executes the loop statements once first, then checks the loop condition
Practice case: Narcissistic numbers
Case description: a narcissistic number is a 3-digit number whose sum of the cubes of each digit equals itself
For example: 1^3 + 5^3+ 3^3 = 153
Please use the do…while statement to find all narcissistic numbers among 3-digit numbers
for Loop Statement
Purpose: while the loop condition is satisfied, execute the loop statements
Syntax: for(start expression;condition expression;end-of-loop body) { loop statements; }
Example:
1 | int main() { |
详解:

注意:for循环中的表达式,要用分号进行分隔
总结:while , do…while, for都是开发中常用的循环语句,for循环结构比较清晰,比较常用
练习案例:敲桌子
案例描述:从1开始数到数字100, 如果数字个位含有7,或者数字十位含有7,或者该数字是7的倍数,我们打印敲桌子,其余数字直接打印输出。

Detailed explanation:

Note: the expressions in a for loop must be separated by semicolons
Summary: while, do…while, and for are all commonly used loop statements in development. The for loop has a clearer structure and is the most commonly used
Practice case: Knock the table
Case description: count from 1 to 100. If the digit in the ones place contains 7, or the digit in the tens place contains 7, or the number is a multiple of 7, we print “knock the table”; otherwise, print the number directly.

Nested Loops
Purpose: nest another layer of loop inside the loop body to solve some practical problems
For example, if we want to print the following image on the screen, we need to use nested loops

Example:
1 | int main() { |
**练习案例:**乘法口诀表
案例描述:利用嵌套循环,实现九九乘法表

Practice case: Multiplication table
Case description: use nested loops to implement the 9x9 multiplication table

跳转语句
break语句
作用: 用于跳出选择结构或者循环结构
break使用的时机:
- 出现在switch条件语句中,作用是终止case并跳出switch
- 出现在循环语句中,作用是跳出当前的循环语句
- 出现在嵌套循环中,跳出最近的内层循环语句
示例1:
Jump Statements
break Statement
Purpose: used to break out of selection structures or loop structures
When to use break:
- In a switch condition statement, it terminates the case and breaks out of the switch
- In a loop statement, it breaks out of the current loop
- In nested loops, it breaks out of the nearest inner loop
Example 1:
1 | int main() { |
示例2:
Example 2:
1 | int main() { |
示例3:
Example 3:
1 | int main() { |
continue Statement
Purpose: in a loop statement, skip the remaining unexecuted statements in the current iteration and continue with the next iteration
Example:
1 | int main() { |
注意:continue并没有使整个循环终止,而break会跳出循环
Note: continue does not terminate the entire loop, while break breaks out of the loop
goto Statement
Purpose: can unconditionally jump to a statement
Syntax: goto label;
Explanation: if the label exists, when the goto statement is executed, the program jumps to the position of the label
Example:
1 | int main() { |
注意:在程序中不建议使用goto语句,以免造成程序流程混乱
Note: it is not recommended to use the goto statement in programs, to avoid confusing the program flow
Arrays
Overview
An array is a collection that stores data elements of the same type
Feature 1: every data element in an array is of the same data type
Feature 2: an array is composed of contiguous memory locations

一维数组
一维数组定义方式
一维数组定义的三种方式:
数据类型 数组名[ 数组长度 ];数据类型 数组名[ 数组长度 ] = { 值1,值2 ...};数据类型 数组名[ ] = { 值1,值2 ...};
示例
One-Dimensional Arrays
Ways to Define a One-Dimensional Array
There are three ways to define a one-dimensional array:
data type array name[ array length ];data type array name[ array length ] = { value 1, value 2 ...};data type array name[ ] = { value 1, value 2 ...};
Example
1 | int main() { |
总结1:数组名的命名规范与变量名命名规范一致,不要和变量重名
总结2:数组中下标是从0开始索引
Summary 1: the naming rules for array names are the same as those for variable names; do not use the same name as a variable
Summary 2: indices in an array start from 0
The Array Name of a One-Dimensional Array
The purposes of a one-dimensional array name:
- It can calculate the length of the entire array in memory
- It can get the first address of the array in memory
Example:
1 | int main() { |
注意:数组名是常量,不可以赋值
总结1:直接打印数组名,可以查看数组所占内存的首地址
总结2:对数组名进行sizeof,可以获取整个数组占内存空间的大小
练习案例1:五只小猪称体重
案例描述:
在一个数组中记录了五只小猪的体重,如:int arr[5] = {300,350,200,400,250};
找出并打印最重的小猪体重。
**练习案例2:**数组元素逆置
**案例描述:**请声明一个5个元素的数组,并且将元素逆置.
(如原数组元素为:1,3,2,5,4;逆置后输出结果为:4,5,2,3,1);
Note: the array name is a constant and cannot be assigned
Summary 1: printing the array name directly shows the first address of the memory occupied by the array
Summary 2: using sizeof on the array name gives the size of the memory occupied by the entire array
Practice case 1: Five little pigs weigh themselves
Case description:
The weights of five little pigs are recorded in an array, such as: int arr[5] = {300,350,200,400,250};
Find and print the weight of the heaviest little pig.
Practice case 2: Reversing array elements
Case description: declare an array of 5 elements and reverse the elements.
(If the original array elements are: 1,3,2,5,4; after reversing, the output result is: 4,5,2,3,1);
冒泡排序
作用: 最常用的排序算法,对数组内元素进行排序
- 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
- 对每一对相邻元素做同样的工作,执行完毕后,找到第一个最大值。
- 重复以上的步骤,每次比较次数-1,直到不需要比较

示例: 将数组 { 4,2,8,0,5,7,1,3,9 } 进行升序排序
Bubble Sort
Purpose: the most commonly used sorting algorithm, used to sort the elements in an array
- Compare adjacent elements. If the first is greater than the second, swap them.
- Do the same work for each pair of adjacent elements; after finishing, find the first maximum value.
- Repeat the above steps, reducing the number of comparisons by 1 each time, until no more comparisons are needed

Example: sort the array { 4,2,8,0,5,7,1,3,9 } in ascending order
1 | int main() { |
二维数组
二维数组就是在一维数组上,多加一个维度。

二维数组定义方式
二维数组定义的四种方式:
数据类型 数组名[ 行数 ][ 列数 ];数据类型 数组名[ 行数 ][ 列数 ] = { {数据1,数据2 } ,{数据3,数据4 } };数据类型 数组名[ 行数 ][ 列数 ] = { 数据1,数据2,数据3,数据4};数据类型 数组名[ ][ 列数 ] = { 数据1,数据2,数据3,数据4};
建议:以上4种定义方式,利用第二种更加直观,提高代码的可读性
示例:
Two-Dimensional Arrays
A two-dimensional array adds one more dimension on top of a one-dimensional array.

Ways to Define a Two-Dimensional Array
There are four ways to define a two-dimensional array:
data type array name[ rows ][ columns ];data type array name[ rows ][ columns ] = { {data 1, data 2 } ,{data 3, data 4 } };data type array name[ rows ][ columns ] = { data 1, data 2, data 3, data 4};data type array name[ ][ columns ] = { data 1, data 2, data 3, data 4};
Suggestion: among the above 4 definition methods, the second one is more intuitive and improves code readability
Example:
1 | int main() { |
总结:在定义二维数组时,如果初始化了数据,可以省略行数
Summary: when defining a two-dimensional array, if the data is initialized, the number of rows can be omitted
The Array Name of a Two-Dimensional Array
- View the memory space occupied by a two-dimensional array
- Get the first address of a two-dimensional array
Example:
1 | int main() { |
总结1:二维数组名就是这个数组的首地址
总结2:对二维数组名进行sizeof时,可以获取整个二维数组占用的内存空间大小
Summary 1: the name of a two-dimensional array is the first address of the array
Summary 2: using sizeof on a two-dimensional array name gives the size of the memory space occupied by the entire two-dimensional array
二维数组应用案例
考试成绩统计:
案例描述:有三名同学(张三,李四,王五),在一次考试中的成绩分别如下表,请分别输出三名同学的总成绩
| 语文 | 数学 | 英语 | |
|---|---|---|---|
| 张三 | 100 | 100 | 100 |
| 李四 | 90 | 50 | 100 |
| 王五 | 60 | 70 | 80 |
参考答案:
Two-Dimensional Array Application Case
Exam score statistics:
Case description: there are three students (Zhang San, Li Si, Wang Wu), and their scores in an exam are shown in the table below. Please output the total score of each of the three students
| Chinese | Math | English | |
|---|---|---|---|
| Zhang San | 100 | 100 | 100 |
| Li Si | 90 | 50 | 100 |
| Wang Wu | 60 | 70 | 80 |
Reference answer:
1 | int main() { |
Functions
Overview
Purpose: encapsulate a piece of frequently used code to reduce duplicate code
A large program is generally divided into several program blocks, and each module implements a specific function.
Function Definition
A function definition generally involves 5 main steps:
-
Return value type
-
Function name
-
Parameter list
-
Function body statements
-
return expression
Syntax:
1 | 返回值类型 函数名 (参数列表) |
- 返回值类型 :一个函数可以返回一个值。在函数定义中
- 函数名:给函数起个名称
- 参数列表:使用该函数时,传入的数据
- 函数体语句:花括号内的代码,函数内需要执行的语句
- return表达式: 和返回值类型挂钩,函数执行完后,返回相应的数据
**示例:**定义一个加法函数,实现两个数相加
- Return value type: a function can return a value. In the function definition
- Function name: give the function a name
- Parameter list: the data passed in when using the function
- Function body statements: the code inside the curly braces, the statements that need to be executed inside the function
- return expression: tied to the return value type, returns the corresponding data after the function finishes executing
Example: define an addition function to add two numbers
1 | //函数定义 |
1 | //函数定义 |
总结:函数定义里小括号内称为形参,函数调用时传入的参数称为实参
Summary: the parameters inside the parentheses in the function definition are called formal parameters, and the parameters passed in when calling the function are called actual parameters
Pass by Value
- The so-called pass by value means that when a function is called, the actual parameter passes its value to the formal parameter
- With pass by value, if the formal parameter changes, it does not affect the actual parameter
Example:
1 | void swap(int num1, int num2) |
总结: 值传递时,形参是修饰不了实参的
Summary: with pass by value, the formal parameter cannot modify the actual parameter
Common Function Styles
There are 4 common function styles
- No parameters, no return value
- With parameters, no return value
- No parameters, with return value
- With parameters, with return value
Example:
1 | //函数常见样式 |
Function Declaration
Purpose: tell the compiler the function name and how to call it. The actual body of the function can be defined separately.
- A function can be declared multiple times, but its definition can only appear once
Example:
1 | //声明可以多次,定义只能一次 |
Writing Functions in Separate Files
Purpose: make the code structure clearer
Writing functions in separate files generally has 4 steps
- Create a header file with the suffix .h
- Create a source file with the suffix .cpp
- Write the function declaration in the header file
- Write the function definition in the source file
Example:
1 | //swap.h文件 |
1 | //swap.cpp文件 |
1 | //main函数文件 |
Pointers
Basic Concepts of Pointers
The purpose of pointers: memory can be accessed indirectly through pointers
- Memory numbers start from 0 and are generally represented in hexadecimal
- Pointer variables can be used to store addresses
Defining and Using Pointer Variables
Pointer variable definition syntax: data type * variable name;
Example:
1 | int main() { |
指针变量和普通变量的区别
- 普通变量存放的是数据,指针变量存放的是地址
- 指针变量可以通过" * "操作符,操作指针变量指向的内存空间,这个过程称为解引用
总结1: 我们可以通过 & 符号 获取变量的地址
总结2:利用指针可以记录地址
总结3:对指针变量解引用,可以操作指针指向的内存
The difference between pointer variables and ordinary variables
- Ordinary variables store data, while pointer variables store addresses
- A pointer variable can use the “*” operator to operate on the memory space it points to; this process is called dereferencing
Summary 1: we can get the address of a variable through the & symbol
Summary 2: pointers can be used to record addresses
Summary 3: dereferencing a pointer variable allows us to operate on the memory it points to
Memory Space Occupied by Pointers
Question: a pointer is also a data type, so how much memory space does this data type occupy?
Example:
1 | int main() { |
总结:所有指针类型在32位操作系统下是4个字节
Summary: all pointer types occupy 4 bytes on 32-bit operating systems
Null Pointers and Wild Pointers
Null pointer: a pointer variable pointing to the space with memory number 0
Purpose: initialize pointer variables
Note: the memory pointed to by a null pointer cannot be accessed
Example 1: null pointer
1 | int main() { |
野指针:指针变量指向非法的内存空间
示例2:野指针
Wild pointer: a pointer variable pointing to an illegal memory space
Example 2: wild pointer
1 | int main() { |
总结:空指针和野指针都不是我们申请的空间,因此不要访问。
Summary: neither null pointers nor wild pointers point to space we allocated, so do not access them.
const Modifying Pointers
There are three cases where const modifies pointers
- const modifies the pointer — constant pointer
- const modifies the constant — pointer constant
- const modifies both the pointer and the constant
Example:
1 | int main() { |
技巧:看const右侧紧跟着的是指针还是常量, 是指针就是常量指针,是常量就是指针常量
Tip: check whether what immediately follows const on the right is a pointer or a constant. If it is a pointer, it is a constant pointer; if it is a constant, it is a pointer constant
1 | int main() { |
Pointers and Functions
Purpose: use pointers as function parameters to modify the value of actual parameters
Example:
1 | //值传递 |
总结:如果不想修改实参,就用值传递,如果想修改实参,就用地址传递
Summary: if you do not want to modify the actual parameters, use pass by value; if you want to modify them, use pass by address
Pointers, Arrays, and Functions
Case description: encapsulate a function that uses bubble sort to sort an integer array in ascending order
For example, the array: int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
Example:
1 | //冒泡排序函数 |
总结:当数组名传入到函数作为参数时,被退化为指向首元素的指针
Summary: when an array name is passed into a function as a parameter, it decays into a pointer to the first element
Structures
Basic Concepts of Structures
A structure is a user==-defined data type== that allows users to store different data types
结构体定义和使用
语法:struct 结构体名 { 结构体成员列表 };
通过结构体创建变量的方式有三种:
- struct 结构体名 变量名
- struct 结构体名 变量名 = { 成员1值 , 成员2值…}
- 定义结构体时顺便创建变量
示例:
Defining and Using Structures
Syntax: struct structure name { list of structure members };
There are three ways to create variables through a structure:
- struct structure name variable name
- struct structure name variable name = { member 1 value, member 2 value…}
- Create the variable while defining the structure
Example:
1 | //结构体定义 |
总结1:定义结构体时的关键字是struct,不可省略
总结2:创建结构体变量时,关键字struct可以省略
总结3:结构体变量利用操作符 ‘’.’’ 访问成员
Summary 1: the keyword when defining a structure is struct, which cannot be omitted
Summary 2: when creating a structure variable, the keyword struct can be omitted
Summary 3: structure variables use the operator ‘’.’’ to access members
Arrays of Structures
Purpose: put custom structures into an array for easier maintenance
Syntax: struct structure name array name[number of elements] = { {} , {} , ... {} }
Example:
1 | //结构体定义 |
Structure Pointers
Purpose: access the members in a structure through pointers
- Use the operator
->to access structure attributes through a structure pointer
Example:
1 | //结构体定义 |
总结:结构体指针可以通过 -> 操作符 来访问结构体中的成员
Summary: a structure pointer can access the members of a structure through the -> operator
Nested Structures
Purpose: a member of a structure can be another structure
For example: each teacher tutors one student, and the structure of a teacher records the structure of a student
Example:
1 | //学生结构体定义 |
**总结:**在结构体中可以定义另一个结构体作为成员,用来解决实际问题
Summary: another structure can be defined as a member inside a structure to solve practical problems
Structures as Function Parameters
Purpose: pass a structure as a parameter to a function
There are two ways to pass it:
- Pass by value
- Pass by address
Example:
1 | //学生结构体定义 |
总结:如果不想修改主函数中的数据,用值传递,反之用地址传递
Summary: if you do not want to modify the data in the main function, use pass by value; otherwise, use pass by address
1 | //学生结构体定义 |
案例1
案例描述:
学校正在做毕设项目,每名老师带领5个学生,总共有3名老师,需求如下
设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员
学生的成员有姓名、考试分数,创建数组存放3名老师,通过函数给每个老师及所带的学生赋值
最终打印出老师数据以及老师所带的学生数据。
示例:
Case 1
Case description:
The school is working on a graduation project. Each teacher leads 5 students, and there are 3 teachers in total. The requirements are as follows:
Design structures for students and teachers. In the teacher structure, there is the teacher’s name and an array of 5 students as members
The student members include name and exam score. Create an array to store 3 teachers, and assign values to each teacher and their students through a function
Finally, print the teacher data and the data of the students led by each teacher.
Example:
1 | struct Student |
案例2
案例描述:
设计一个英雄的结构体,包括成员姓名,年龄,性别;创建结构体数组,数组中存放5名英雄。
通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最终打印排序后的结果。
五名英雄信息如下:
Case 2
Case description:
Design a structure for heroes, including the members name, age, and gender; create a structure array to store 5 heroes.
Use the bubble sort algorithm to sort the heroes in the array by age in ascending order, and finally print the sorted results.
The information of the five heroes is as follows:
1 | {"刘备",23,"男"}, |
示例:
Example:
1 | //英雄结构体 |



