Introduction to C + + Basics
1. Initial knowledge of C + +
[introduction to C + +]( (31 messages) [C + +] dark horse programmer "C + + from introduction to Mastery"_ Langli xiaofeixia blog - CSDN blog_ Dark horse programmer C++)
1.1 the first C + + program
#include<iostream> using namespace std; int main() { int a =10; //cout << "Hello, world!" << endl; cout << "a="<<a<<endl;// return 0; }
L in endl is the letter L, not the number 1
1.1.3 coding
#include<iostream> using namespace std; int main() { cout << "Hello world" << endl; system("pause"); return 0; }
1.2 notes
Function: add some instructions and explanations in the code to facilitate yourself or other programmers to read the code
Two formats
- Single line comment: / / description
- It is usually placed above a line of code or at the end of a statement to explain the line of code
- Multiline comment: / * description information*/
- It is usually placed above a piece of code to give an overall description of the code
Tip: the compiler will ignore the contents of comments when compiling code
1.3 variables
Function: name a specified memory space to facilitate the operation of this memory
Syntax: data type variable name = initial value;
Example:
#include<iostream> using namespace std; int main() { //Definition of variables //Syntax: data type variable name = initial value int a = 10; cout << "a = " << a << endl; system("pause"); return 0; }
Note: when creating a variable, C + + must give the variable an initial value, otherwise an error will be reported
1.4 constants
Function: used to record unchangeable data in the program
There are two ways to define constants in C + +
-
#Define macro constant: #define constant name constant value
- It is usually defined at the top of the file to represent a constant
-
Const modified variable const data type constant name = constant value
- Usually, the keyword const is added before the variable definition to modify that the variable is constant and cannot be modified
Example:
//1. Macro constant #define day 7 int main() { cout << "In a week " << day << " day" << endl; //day = 8; // An error is reported. Macro constants cannot be modified //2. const modifier variable const int month = 12; cout << "A total of in a year " << month << " Months" << endl;//month here has no double quotation marks //month = 24; // An error is reported. Constants cannot be modified system("pause"); return 0; }
1.5 keywords
**Function: * * keyword is a word (identifier) reserved in C + +
- When defining variables or constants, do not use keywords
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 occur.
1.6 identifier naming rules
Function: when C + + specifies to name identifiers (variables and constants), it has its own set of rules
- Identifier cannot be a keyword
- The identifier can only be composed of letters, numbers and underscores (no spaces)
- The first character must be a letter or underscore
- Letters in identifiers are case sensitive
Suggestion: when naming the identifier, strive to achieve the effect of seeing the name and knowing the meaning, which is convenient for yourself and others to read
2 data type
C + + stipulates that when creating a variable or constant, the corresponding data type must be specified, otherwise memory cannot be allocated to the variable
The meaning of data type: allocate appropriate memory space to variables
2.1 integer
Function: integer variables represent integer data
The types that can represent integers in C + + can be expressed in the following ways. The difference lies in the different memory space occupied:
data type | Occupied space | Value range |
---|---|---|
Short (short integer) | 2 bytes (value range - 32768 to + 32767) | (-2^15 ~ 2^15-1) |
Int (integer) | 4 bytes | (-2^31 ~ 2^31-1) |
Long (long shaping) | 4 bytes for Windows, 4 bytes (32 bits) for Linux, 8 bytes (64 bits) | (-2^31 ~ 2^31-1) |
Long long | 8 bytes | (-2^63 ~ 2^63-1) |
If short=32768 is defined, it is out of the range of short. When running, short will return to - 36768 and return to the first cycle
2.2 sizeof keyword
**Function: * * use sizeof keyword to count the memory size occupied by data type
Syntax: sizeof (data type / variable) can also be used to place data structures or variables with defined data types
Example:
int main() { cout << "short Memory space occupied by type: " << sizeof(short) << endl; cout << "int Memory space occupied by type: " << sizeof(int) << endl; cout << "long Memory space occupied by type: " << sizeof(long) << endl; cout << "long long Memory space occupied by type: " << sizeof(long long) << endl; system("pause"); return 0; }
Integer conclusion: short < int < = long < = long long
2.3 real (floating point)
Function: used to represent decimals
There are two types of floating-point variables:
- float precision sheet
- Double precision double
The difference is that the range of significant numbers represented is different. Double precision can express more precision
data type | Occupied space | Significant digit range |
---|---|---|
float | 4 bytes | 7 significant digits |
double | 8 bytes | 15 ~ 16 significant digits |
Example:
int main() { float f1 = 3.14f; double d1 = 3.14; cout << f1 << endl; cout << d1<< endl; cout << "float sizeof = " << sizeof(f1) << endl; cout << "double sizeof = " << sizeof(d1) << endl; //Scientific counting method float f2 = 3e2; // 3 * 10 ^ 2 cout << "f2 = " << f2 << endl; float f3 = 3e-2; // 3 * 0.1 ^ 2 cout << "f3 = " << f3 << endl; system("pause"); return 0; }
2.4 character type
**Function: * * character type variable is used to display a single character
Syntax: char ch = 'a';
Note 1: when displaying character type variables, enclose the characters in single quotation marks instead of double quotation marks
Note 2: there can only be one character in a single quotation mark, not a string
- Character variables in C and C + + only occupy 1 byte.
- Character type variables do not store the character itself in memory, but put the corresponding ASCII code into the storage unit
Example:
int main() { char ch = 'a'; cout << ch << endl; cout << sizeof(char) << endl; //ch = "abcde"; // Error, double quotation marks are not allowed //ch = 'abcde'; // Error, only one character can be referenced in a single quotation mark cout << (int)ch << endl; //View the ASCII code corresponding to character a ch = 97; //You can assign values to character variables directly in ASCII cout << ch << endl; system("pause"); return 0; }
ASCII table:
ASCII value | Control character | ASCII value | character | ASCII value | character | ASCII value | character |
---|---|---|---|---|---|---|---|
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 code is roughly composed of the following two parts:
- ASCII non printing control characters: the numbers 0-31 on the ASCII table are assigned to the control characters, which are used to control some peripheral devices such as printers.
- ASCII printed characters: the numbers 32-126 are assigned to characters that can be found on the keyboard and appear when viewing or printing a document.
2.5 escape characters
**Function: * * used to indicate some ASCII characters that cannot be displayed
At this stage, our commonly used escape characters are: \ n \ \ t
Escape character | meaning | ASCII value (decimal) |
---|---|---|
\a | alert | 007 |
\b | Backspace (BS) to move the current position to the previous column | 008 |
\f | Page 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 | Press enter (CR) to move the current position to the beginning of the line | 013 |
\t | Horizontal tabulation (HT) (skip to next TAB position) | 009 |
\v | Vertical tabulation (VT) | 011 |
\\ | Represents a backslash character '' | 092 |
' | Represents a single quotation mark (apostrophe) character | 039 |
" | Represents a double quote character | 034 |
? | Represents a question mark | 063 |
\0 | Number 0 | 000 |
\ddd | Octal escape character, d range 0 ~ 7 | 3-bit octal |
\xhh | Hexadecimal escape character, h range 09, af, A~F | 3-bit hexadecimal |
Example:
int main() { cout << "\\" << endl; cout << "\tHello" << endl; cout << "\n" << endl; system("pause"); return 0; }
2.6 string type
Function: used to represent a string of characters
Two styles
-
C style string: char variable name [] = "string value"
Example:
int main() { char str1[] = "hello world"; cout << str1 << endl; system("pause"); return 0; }
Note: C-style strings should be enclosed in double quotation marks
-
C + + style string: string variable name = "string value"
Example:
int main() { string str = "hello world"; cout << str << endl; system("pause"); return 0; }
Note: for C + + style strings, you need to add header files = = #include < string >==
2.7 boolean type bool
**Function: * * Boolean data type represents true or false value
The bool type has only two values:
- True - true (essentially 1)
- False - false (essentially 0)
bool type takes up 1 byte
Example:
int main() { bool flag = true; cout << flag << endl; // 1 flag = false; cout << flag << endl; // 0 cout << "size of bool = " << sizeof(bool) << endl; //1 system("pause"); return 0; }
2.8 data input
Function: used to obtain data from the keyboard
**Keywords: * * cin
Syntax: CIN > > variable
Example:
int main(){ //Integer input int a = 0; cout << "Please enter an integer variable:" << endl; cin >> a; cout << a << endl; //Floating point input double d = 0; cout << "Please enter a floating point variable:" << endl; cin >> d; cout << d << endl; //Character input char ch = 0; cout << "Please enter a character variable:" << endl; cin >> ch; cout << ch << endl; //String input string str; cout << "Please enter a string variable:" << endl; cin >> str; cout << str << endl; //Boolean type input bool flag = true; cout << "Please enter a boolean variable:" << endl; cin >> flag; cout << flag << endl; system("pause"); return EXIT_SUCCESS; }
3 operator
**Function: * * used to execute code operation
In this chapter, we mainly explain the following types of operators:
Operator type | effect |
---|---|
Arithmetic operator | Used to process four operations |
Assignment Operators | Used to assign the value of an expression to a variable |
Comparison operator | Used to compare expressions and return a true or false value |
Logical operator | Used to return true or false values based on the value of an expression |
3.1 arithmetic operators
Function: used to process four operations
Arithmetic operators include the following symbols:
operator | term | Examples | result |
---|---|---|---|
+ | Plus sign | +3 | 3 |
- | minus sign | -3 | -3 |
+ | plus | 10 + 5 | 15 |
- | reduce | 10 - 5 | 5 |
* | ride | 10 * 5 | 50 |
/ | except | 10 / 5 | 2 |
% | Mold taking (residual) | 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:
//add , subtract , multiply and divide int main() { int a1 = 10; int b1 = 3; cout << a1 + b1 << endl; cout << a1 - b1 << endl; cout << a1 * b1 << endl; cout << a1 / b1 << endl; //The result of dividing two integers is still an integer int a2 = 10; int b2 = 20; cout << a2 / b2 << endl; int a3 = 10; int b3 = 0; //cout << a3 / b3 << endl; // An error is reported. The divisor cannot be 0 //Two decimals can be divided double d1 = 0.5; double d2 = 0.25; cout << d1 / d2 << endl; system("pause"); return 0; }
Summary: divisor cannot be 0 in division operation
Example 2:
//Take mold int main() { int a1 = 10; int b1 = 3; cout << 10 % 3 << endl; int a2 = 10; int b2 = 20; cout << a2 % b2 << endl; int a3 = 10; int b3 = 0; //cout << a3 % b3 << endl; // In modulo operation, the divisor cannot be 0 //Two decimals cannot be modulo double d1 = 3.14; double d2 = 1.1; //cout << d1 % d2 << endl; system("pause"); return 0; }
Summary: only integer variables can perform modulo operations
Example 3:
//Increasing int main() { //Post increment int a = 10; a++; //Equivalent to a = a + 1 cout << a << endl; // 11 //Pre increment int b = 10; ++b; cout << b << endl; // 11 //difference //Pre increment first + + the variable, and then calculate the expression int a2 = 10; int b2 = ++a2 * 10; cout << b2 << endl; //Post increment calculates the expression first, and then calculates the variable++ int a3 = 10; int b3 = a3++ * 10; cout << b3 << endl;//a3 equals 11 and b3 equals 100 system("pause"); return 0; }
Conclusion: the pre increment is performed on the variable with + +, and then the expression is calculated. The post increment is the opposite
Post increment calculates the expression first, and then calculates the variable++
3.2 assignment operator
**Function: * * used to assign the value of an expression to a variable
The assignment operator includes the following symbols:
operator | term | Examples | result |
---|---|---|---|
= | assignment | a=2; b=3; | a=2; b=3; |
+= | Plus equals | a=0; a+=2; | a=2; |
-= | Minus equals | a=5; a-=3; | a=2; |
*= | Multiply equal | a=2; a*=2; | a=4; |
/= | Division equals | a=4; a/=2; | a=2; |
%= | Modulo equal | a=3; a%2; | a=1; |
Example:
int main() { //Assignment Operators // = int a = 10; a = 100; cout << "a = " << a << endl; // += a = 10; a += 2; // a = a + 2; cout << "a = " << a << endl; // -= a = 10; a -= 2; // a = a - 2 cout << "a = " << a << endl; // *= a = 10; a *= 2; // a = a * 2 cout << "a = " << a << endl; // /= a = 10; a /= 2; // a = a / 2; cout << "a = " << a << endl; // %= a = 10; a %= 2; // a = a % 2; cout << "a = " << a << endl; system("pause"); return 0; }
3.3 comparison operator
**Function: * * used to compare expressions and return a true value or false value
The comparison operator has the following symbols:
operator | term | Examples | 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:
Remember to add () after cout to delimit the operation order
int main() { int a = 10; int b = 20; cout << (a == b) << endl; // 0 cout << (a != b) << endl; // 1 cout << (a > b) << endl; // 0 cout << (a < b) << endl; // 1 cout << (a >= b) << endl; // 0 cout << (a <= b) << endl; // 1 system("pause"); return 0; }
Note: in the comparison operation of C and C + + languages, "true" is represented by the number "1", and "false" is represented by the number "0".
3.4 logical operators
**Function: * * used to return true or false values according to the value of the expression
Logical operators have the following symbols:
operator | term | Examples | result |
---|---|---|---|
! | wrong | !a | If a is false, then! A is true; If a is true, then! 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 one of a and b is true, the result is true. If both are false, the result is false. |
**Example 1: * * logical non
//Logical operator --- not int main() { int a = 10; cout << !a << endl; // 0 cout << !!a << endl; // 1 system("pause"); return 0; }
Summary: true becomes false, false becomes true
In C + +, it is 1 as long as it is not 0
**Example 2: * * logic and
//Logical operators --- and int main() { int a = 10; int b = 10; cout << (a && b) << endl;// 1 a = 10; b = 0; cout << (a && b) << endl;// 0 a = 0; b = 0; cout << (a && b) << endl;// 0 system("pause"); return 0; }
Summary: logic and operator summary: the same as true is true, and the rest is false
**Example 3: * * logical or
//Logical operator --- or int main() { int a = 10; int b = 10; cout << (a || b) << endl;// 1 a = 10; b = 0; cout << (a || b) << endl;// 1 a = 0; b = 0; cout << (a || b) << endl;// 0 system("pause"); return 0; }
The other logical operators are true or false
4 program flow structure
C/C + + supports three basic program running structures: sequential structure, selection structure and loop structure
- Sequence structure: the program is executed in sequence without jump
- Whether the structure meets the conditions and whether the corresponding function is selected
- Loop structure: execute a piece of code multiple times according to whether the conditions are met
4.1 structure selection
4.1.1 if statement
**Function: * * execute statements that meet the conditions
Three forms of if statement
-
Single line format if statement
-
Multiline if statement
-
Multi conditional if statement
-
Single line format if statement: if (condition) {statement executed when the condition is met}
Example:
int main() { //Select structure - single line if statement //Enter a score. If the score is greater than 600, it will be regarded as entering a university and printed on the screen int score = 0; cout << "Please enter a score:" << endl; cin >> score; cout << "The score you entered is: " << score << endl; //if statement //Note: do not add a semicolon after the if judgment statement if (score > 600) { cout << "I was admitted to Tsinghua University!!!" << endl; } system("pause"); return 0; }
Note: do not add a semicolon after the if conditional expression
Using namespace is a wrong expression. It should be using namespace std;, Remember
- Multi line format if statement: if (condition) {statement executed when the condition meets} else {statement executed when the condition does not meet};
Example:
int main() { int score = 0; cout << "Please enter the test score:" << endl; cin >> score; if (score > 600) { cout << "I was admitted to a university" << endl; } else { cout << "I failed to enter a university" << endl; } system("pause"); return 0; }
- Multi conditional if statements: if (condition 1) {statements executed when condition 1 satisfies} else if (condition 2) {statements executed when condition 2 satisfies} Else {does not satisfy the executed statement}
Example:
int main() { int score = 0; cout << "Please enter the test score:" << endl; cin >> score; if (score > 600) { cout << "I was admitted to a university" << endl; } else if (score > 500) { cout << "I was admitted to two universities" << endl; } else if (score > 400) { cout << "I was admitted to three universities" << endl; } else { cout << "I didn't go to college" << endl; } system("pause"); return 0; }
Nested if statements: if statements can be nested in if statements to achieve more accurate condition judgment
Case requirements:
- Prompt the user to enter a college entrance examination score, and make the following judgment according to the score
- If the score is greater than 600, it will be regarded as one, two, three and the rest will be regarded as not having been admitted to undergraduate;
- If the score in a book is more than 700, you will be admitted to Peking University, more than 650, Tsinghua University and more than 600 to the National People's Congress.
Example:
int main() { int score = 0; cout << "Please enter the test score:" << endl; cin >> score; if (score > 600) { cout << "I was admitted to a university" << endl; if (score > 700) { cout << "I was admitted to Peking University" << endl; } else if (score > 650) { cout << "I was admitted to Tsinghua University" << endl; } else { cout << "I was admitted to the National People's Congress" << endl; } } else if (score > 500) { cout << "I was admitted to two universities" << endl; } else if (score > 400) { cout << "I was admitted to three universities" << endl; } else { cout << "I didn't go to college" << endl; } system("pause"); return 0; }
Exercise case: weigh three piglets
There are three piglets ABC. Please input the weight of the three piglets respectively and judge which piglet is the heaviest?
[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-q9j4h4eb-164674389444) (C: \ users \ Tait \ appdata \ roaming \ typora user images \ image-20220305164015397. PNG)]
#include<iostream> using namespace std; int main(){ int A,B,C; cout << "Please enter pig A Weight of:"; cin >> A; cout << "Please enter pig B Weight of:"; cin >> B; cout << "Please enter pig C Weight of:"; cin >> C; if (A > B){ if(A > C) cout << "Little pig A Heaviest"; else cout << "Little pig C Heaviest"; } else if (B > C) cout << "Little pig B Heaviest"<<endl; else cout << "Little pig C Heaviest"; }
Logical thinking is still very important. We should learn to think with the thinking mode of computer
4.1.2 ternary operator
Function: realize simple judgment through the three eye operator
Syntax: expression 1? Expression 2: expression 3
Explanation:
If the value of expression 1 is true, execute expression 2 and return the result of expression 2;
If the value of expression 1 is false, execute expression 3 and return the result of expression 3.
Example:
int main() { int a = 10; int b = 20; int c = 0; c = a > b ? a : b; cout << "c = " << c << endl; //The ternary operator in C + + returns variables and can continue to assign values (a > b ? a : b) = 100; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; system("pause"); return 0; }
Summary: compared with if statement, the advantage of ternary operator is short and neat, while the disadvantage is that if nested, the structure is not clear
4.1.3 switch statement
**Function: * * execute multi conditional branch statements
Syntax:
switch(expression) { case Result 1: execute the statement;break; case Result 2: execute the statement;break; ... default:Execute statement;break; }
Example:
int main() { //Please rate the movie //10 ~ 9 classic // 8 ~ 7 very good // 6 ~ 5 general // Rotten film with less than 5 points int score = 0; cout << "Please rate the movie" << endl; cin >> score; switch (score) { case 10: case 9: cout << "classic" << endl; break; case 8: cout << "very nice" << endl; break; case 7: case 6: cout << "commonly" << endl; break; default: cout << "Rotten film" << endl; break; } system("pause"); return 0; }
Note that the type of switch can only be integer or 1:1 in the statement
Note 2: if there is no break in the case, the program will always execute downward
Conclusion: compared with if statements, for multi condition judgment, switch has clear structure and high execution efficiency. The disadvantage is that switch cannot judge the interval
4.2 circulation structure
4.2.1 while loop statement
**Function: * * execute loop statements when loop conditions are met
Syntax: while (loop condition) {loop statement}
Explanation: as long as the result of the loop condition is true, the loop statement is executed
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qi99mxpo-164674389445) (C: \ users \ Tait \ appdata \ roaming \ typora user images \ image-20220305200305850. PNG)]
Example:
int main() { int num = 0; while (num < 10) { cout << "num = " << num << endl; num++; } system("pause"); return 0; }
Note: when executing a loop statement, the program must provide an exit to jump out of the loop, otherwise an endless loop will appear
while loop exercise case: guess numbers
**Case description: * * the system randomly generates a number between 1 and 100, and the player guesses. If the guess is wrong, the player will be prompted that the number is too large or too small. If the guess is right, congratulations on the player's victory and exit the game.
#include<iostream> #include<cstdlib> using namespace std; int main() { int num = rand() %100+1; int a=0; cout << "Please enter the guessed number: "<<endl; cin >> a; if(a>num) { cout<<"The number is big"<<endl; } else if(a<num) { cout<<"The number is small"<<endl; } else(a=num) { cout<<"Congratulations, you guessed right"<<endl; } system("pause"); return 0; }
4.2.2 do... while loop statement
Function: execute loop statement when loop conditions are met
Syntax: do {loop statement} while (loop condition);
**Note: * * the difference between * * and while is that do... While will execute a loop statement first, and then judge the loop conditions
Example:
int main() { int num = 0; do { cout << num << endl; num++; } while (num < 10); system("pause"); return 0; }
Summary: the difference between do... While and while loop is that do... While executes the loop statement once before judging the loop conditions
#include<iostream> using namespace std; int main() { int num =0; // do while(num<10){ cout<<num<<endl; num++; } // while(num<10); system("pause"); return 0; }
Exercise case: daffodils
**Case description: * * daffodil number refers to a three digit number, and the sum of the three powers of the number on each digit is equal to itself
For example: 1 ^ 3 + 5 ^ 3 + 3 ^ 3 = 153
Please use the do... while statement to find the number of daffodils in all three digits
// An highlighted block #include<iostream> using namespace std; //Refers to all identifiers defined in the calling namespace std #Include < CTime > / / header file, used for C + + string int main() { int num = 100; do { int a = 0; int b = 0; int c = 0; int d = 0; a = num % 10; b = num / 10 % 10; c = num / 100; d = a*a*a + b*b*b + c*c*c; if (d == num) { cout << num << endl; } num++; } while (num < 1000); system("pause"); //Pause the program and press any key to continue return 0; }
4.2.3 for loop statement
Function: execute loop statement when loop conditions are met
Syntax: for (start expression; conditional expression; end loop body) {loop statement;}
Example:
int main() { for (int i = 0; i < 10; i++) { cout << i << endl; } system("pause"); return 0; }
Note: expressions in the for loop should be separated by semicolons
Summary: while, do... While and for are commonly used loop statements in development. The for loop structure is relatively clear and commonly used
Exercise case: knocking on the table
Case description: count from 1 to 100. If the digit contains 7, or the digit ten contains 7, or the digit is a multiple of 7, we print and knock on the table, and the other digits are printed out directly.
// An highlighted block #include<iostream> using namespace std; //Refers to all identifiers defined in the calling namespace std #Include < CTime > / / header file, used for C + + string int main() { // int i = 0; for (i = 1; i < 100; i++) { if (i % 7 == 0) { cout << "qiaozhuozi" << endl; } else if (i % 10 == 7) { cout << "qiaozhuozi" << endl; } else if (i / 10 % 10 == 7) { cout << "qiaozhuozi" << endl; } else { cout << i << endl; } } system("pause"); //Pause the program and press any key to continue return 0;//Indicates that the program exits normally, returns to the main program and continues to execute }
4.2.4 nested loops
Function: nest another layer of loop in the loop body to solve some practical problems
For example, if we want to print the following pictures on the screen, we need to use nested loops
Example:
int main() { //The outer loop is executed once and the inner loop is executed once for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { cout << "*" << " "; } cout << endl; } system("pause"); return 0; }
**Exercise case: * * multiplication formula table
Case description: using nested loop to realize 99 multiplication table
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-lu6fc1pa-164674389446) (C: \ users \ Tait \ appdata \ roaming \ typora \ typora user images \ image-20220306113031632. PNG)]
#include<iostream> using namespace std; //Refers to all identifiers defined in the calling namespace std #Include < CTime > / / header file, used for C + + string int main() { int i = 0; int j = 0; for (i = 1; i < 10; i++) { for (j = 1; j <= i; j++) { cout << j << "*" << i << "=" << j * i << " ";//The following "" is to make the formula look like the multiplication formula yi'yang } cout << endl; } system("pause"); //Pause the program and press any key to continue return 0;//Indicates that the program exits normally, returns to the main program and continues to execute }
4.3 jump statement
4.3.1 break statement
Function: used to jump out of the selection structure or loop structure
When to use break:
- It appears in the switch conditional statement to terminate the case and jump out of the switch. The most commonly used is in the switch (case) statement, otherwise each case will be output.
- Appears in a circular statement to jump out of the current circular statement
- Appears in a nested loop and jumps out of the nearest inner loop statement
Example 1:
int main() { //1. Using break in a switch statement cout << "Please select the difficulty of your challenge copy:" << endl; cout << "1,ordinary" << endl; cout << "2,secondary" << endl; cout << "3,difficulty" << endl; int num = 0; cin >> num; switch (num) { case 1: cout << "You chose ordinary difficulty" << endl; break; case 2: cout << "You chose medium difficulty" << endl; break; case 3: cout << "You chose difficulty" << endl; break; } system("pause"); return 0; }
Example 2:
int main() { //2. Use break in loop statements for (int i = 0; i < 10; i++) { if (i == 5) { break; //Jump out of loop statement } cout << i << endl; } system("pause"); return 0; }
Example 3:
int main() { //Use break in a nested loop statement to exit the inner loop for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (j == 5) { break; } cout << "*" << " "; } cout << endl; } system("pause"); return 0; }
4.3.2 continue statement
**Function: * * in a loop statement, skip the remaining unexecuted statements in this loop and continue to execute the next loop
Example:
int main() { for (int i = 0; i < 100; i++) { if (i % 2 == 0) { continue;//If the loop is executed to one line, the next line will not be executed. If it is broken, it will exit the loop and no longer execute the loop } cout << i << endl; } system("pause"); return 0; }
Note: continue does not terminate the whole loop, but break will jump out of the loop
4.3.3 goto statement
**Function: * * you can jump to statements unconditionally. / / you are not good at using them, which will cause confusion in the flow of program statements
Syntax: goto tag;
**Explanation: * * if the name of the tag exists, the goto statement will jump to the location of the tag
Example:
int main() { cout << "1" << endl; goto FLAG; cout << "2" << endl; cout << "3" << endl; cout << "4" << endl; FLAG: cout << "5" << endl; system("pause"); return 0; }
Note: goto statement is not recommended in the program to avoid confusion of program flow
5 array
5.1 general
An array is a collection of data elements of the same type stored in a continuous memory space
**Feature 1: * * each data element in the array is of the same data type
**Feature 2: * * array is composed of continuous memory locations
5.2 one dimensional array
5.2.1 definition method of 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...};
Examples
int main() { //Definition method 1 //Data type array name [number of elements]; int score[10]; //Assignment with subscript score[0] = 100; score[1] = 99; score[2] = 85; //Using subscript output cout << score[0] << endl; cout << score[1] << endl; cout << score[2] << endl; //The second definition method //Data type array name [number of elements] = {value 1, value 2, value 3...}; //If there are less than 10 data in {}, the remaining data shall be filled with 0 int score2[10] = { 100, 90,80,70,60,50,40,30,20,10 }; //Output one by one //cout << score2[0] << endl; //cout << score2[1] << endl; //One output is too troublesome, so you can use loops to output for (int i = 0; i < 10; i++) { cout << score2[i] << endl; } //Definition method 3 //Data type array name [] = {value 1, value 2, value 3...}; int score3[] = { 100,90,80,70,60,50,40,30,20,10 }; for (int i = 0; i < 10; i++) { cout << score3[i] << endl; } system("pause"); return 0; }
Summary 1: the naming convention of array name is consistent with that of variable name. Do not duplicate the name of variable
Summary 2: the index in the array starts from 0
5.2.2 one dimensional array name
Purpose name of one-dimensional array:
- You can count the length of the entire array in memory
- You can get the first address of the array in memory
Example:
int main() { //Array name usage //1. You can get the memory space occupied by the whole array int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; cout << "The memory space occupied by the whole array is: " << sizeof(arr) << endl; cout << "The memory space occupied by each element is: " << sizeof(arr[0]) << endl; cout << "The number of elements in the array is: " << sizeof(arr) / sizeof(arr[0]) << endl; //2. You can get the first address of the array through the array name cout << "The first address of the array is: " << (int)arr << endl; cout << "The address of the first element in the array is: " << &arr[0] << endl; cout << "The address of the second element in the array is: " << (int)&arr[1] << endl; //arr = 100; Error, array name is constant, so it cannot be assigned system("pause"); return 0; }
Note: the array name is a constant and cannot be assigned
Summary 1: print the array name directly, and you can view the first address of the memory occupied by the array
Summary 2: sizeof the array name, you can get the memory space occupied by the whole array
Cout < < "the address of the first element in the array is:" < & arr [0] < < endl; Running result: 0x6ffde0 (represented by hexadecimal number)
Number converted to decimal: cout < < the address of the first element in the array is: "< (int) & arr [0] < < endl; But it didn't run, so I can't find a way to solve the bug for the time being
Exercise case 1: weigh five piglets
Case description:
The weight of five piglets is recorded in an array, such as int arr [5] = {300350200400250}; Find and print the heaviest pig weight.
#include<iostream> using namespace std; int main() { //1: Create a weight array of 5 piglets int arr[5] = {300,350,200,400,250}; //2: Find maximum value from array int max=0;//First identify a maximum value of 0 for(int i=0;i<5;i++)//Circular statement { //cout<<arr[i]<<endl; //If the element in the accessed array is larger than the maximum value in the identification, the maximum value needs to be updated; if(arr[i]>max)//Select statement { max=arr[i]; } } cout<<"The heaviest piglet weighs "<<max<<endl; //3: Print Max system("pause"); return 0; }
If + for nesting is mainly used
**Exercise case 2: * * array element inversion
**Case description: * * Please declare an array of 5 elements and invert the elements (for example, the original array elements are: 1,3,2,5,4; the output result after inversion is: 4,5,2,3,1);
5.2.3 bubble sorting
Function: the most commonly used sorting algorithm to sort the elements in the array
- Compare adjacent elements. If the first one is bigger than the second, exchange them.
- Do the same work for each pair of adjacent elements. After execution, find the first maximum value.
- Repeat the above steps for - 1 times each time until no comparison is needed
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-r7ttqr0Y-1646743894946)(assets/1541905327273.png)]
Example: sort the array {4,2,8,0,5,7,1,3,9} in ascending order
int main() { int arr[9] = { 4,2,8,0,5,7,1,3,9 }; for (int i = 0; i < 9 - 1; i++) { for (int j = 0; j < 9 - 1 - i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for (int i = 0; i < 9; i++) { cout << arr[i] << endl; } system("pause"); return 0; }
5.3 two dimensional array
A two-dimensional array is to add one more dimension to a one-dimensional array.
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-km7kfp6g-164674389447) (assets / 1541905559138. PNG)]
5.3.1 definition method of two-dimensional array
There are four ways to define a two-dimensional array:
- Data type array name [number of rows] [number of columns];
- Data type array name [number of rows] [number of columns] = {data 1, data 2}, {data 3, data 4}};
- Data type array name [number of rows] [number of columns] = {data 1, data 2, data 3, data 4};
- Data type array name [] [number of columns] = {data 1, data 2, data 3, data 4};
Suggestion: for the above four definition methods, the second one is more intuitive to improve the readability of the code
Example:
int main() { //Mode 1 //Array type array name [number of rows] [number of columns] int arr[2][3]; arr[0][0] = 1; arr[0][1] = 2; arr[0][2] = 3; arr[1][0] = 4; arr[1][1] = 5; arr[1][2] = 6; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr[i][j] << " "; } cout << endl; } //Mode 2 //Data type array name [number of rows] [number of columns] = {data 1, data 2}, {data 3, data 4}}; int arr2[2][3] = { {1,2,3}, {4,5,6} }; //Mode 3 //Data type array name [number of rows] [number of columns] = {data 1, data 2, data 3, data 4}; int arr3[2][3] = { 1,2,3,4,5,6 }; //Mode 4 //Data type array name [] [number of columns] = {data 1, data 2, data 3, data 4}; int arr4[][3] = { 1,2,3,4,5,6 }; system("pause"); return 0; }
Summary: when defining a two-dimensional array, if the data is initialized, the number of rows can be omitted
5.3.2 two dimensional array name
- View the memory space occupied by two-dimensional array
- Get the first address of two-dimensional array
Example:
int main() { //2D array name int arr[2][3] = { {1,2,3}, {4,5,6} }; cout << "2D array size: " << sizeof(arr) << endl; cout << "One row size of two-dimensional array: " << sizeof(arr[0]) << endl; cout << "2D array element size: " << sizeof(arr[0][0]) << endl; cout << "Rows of 2D array: " << sizeof(arr) / sizeof(arr[0]) << endl; cout << "Number of two-dimensional array columns: " << sizeof(arr[0]) / sizeof(arr[0][0]) << endl; //address cout << "First address of 2D array:" << arr << endl; cout << "First row address of 2D array:" << arr[0] << endl; cout << "Address of the second row of two-dimensional array:" << arr[1] << endl; cout << "Address of the first element of 2D array:" << &arr[0][0] << endl; cout << "Address of the second element of 2D array:" << &arr[0][1] << endl; system("pause"); return 0; }
Summary 1: the two-dimensional array name is the first address of the array
Summary 2: when sizeof a two-dimensional array name, you can get the memory space occupied by the whole two-dimensional array
5.3.3 application cases of two-dimensional array
Test score statistics:
Case description: there are three students (Zhang San, Li Si and Wang Wu). Their scores in one exam are shown in the table below. Please output the total scores of the three students respectively
language | mathematics | English | |
---|---|---|---|
Zhang San | 100 | 100 | 100 |
Li Si | 90 | 50 | 100 |
Wang Wu | 60 | 70 | 80 |
Reference answer:
int main() { int scores[3][3] = { {100,100,100}, {90,50,100}, {60,70,80}, }; string names[3] = { "Zhang San","Li Si","Wang Wu" }; for (int i = 0; i < 3; i++) { int sum = 0; for (int j = 0; j < 3; j++) { sum += scores[i][j]; } cout << names[i] << "The total score of students is: " << sum << endl; } system("pause"); return 0; }
6 function
6.1 general
**Function: * * encapsulate a piece of frequently used code to reduce repeated code
A large program is generally divided into several program blocks, and each module realizes specific functions.
6.2 definition of function
The definition of a function generally consists of five steps:
1. Return value type
2. Function name
3. Parameter table column
4. Function body statement
5. return expression
Syntax:
Return value type function name (parameter list) { Function body statement return expression }
- Return value type: a function can return a value. In function definition
- Function name: give the function a name
- Parameter list: the data passed in when using this function
- Function body statement: the code in curly braces and the statement to be executed in the function
- Return expression: linked to the return value type. After the function is executed, the corresponding data is returned
**Example: * * define an addition function to add two numbers
//Function definition int add(int num1, int num2) { int sum = num1 + num2; return sum; }
6.3 function call
**Function: * * use defined function
Syntax: function name (parameter)
Example:
//Function definition int add(int num1, int num2) //Num1 and num2 in the definition are called formal parameters, or formal parameters for short { int sum = num1 + num2; return sum; } int main() { int a = 10; int b = 10; //Call the add function int sum = add(a, b);//a and b at the time of calling are called actual parameters, which are referred to as actual parameters for short cout << "sum = " << sum << endl; a = 100; b = 100; sum = add(a, b); cout << "sum = " << sum << endl; system("pause"); return 0; }
Summary: the parentheses in the function definition are called formal parameters, and the parameters passed in during function call are called arguments
6.4 value transfer
- The so-called value passing means that the real parameter passes the value to the formal parameter when the function is called
- When the value is passed, if the formal parameter occurs, the argument will not be affected
Example:
void swap(int num1, int num2) { cout << "Before exchange:" << endl; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; int temp = num1; num1 = num2; num2 = temp; cout << "After exchange:" << endl; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; //return ; When a function is declared, there is no need to return a value. You can leave return blank } int main() { int a = 10; int b = 20; swap(a, b); cout << "mian Medium a = " << a << endl; cout << "mian Medium b = " << b << endl; system("pause"); return 0; }
Summary: formal parameters cannot modify arguments when passing values
6.5 common styles of functions
There are four common function styles
- No reference, no return
- There is no return
- Return without participation
- Participation and return
Example:
//Common styles of functions //1. No reference, no return void test01() { //void a = 10; // No type. Cannot create variable because memory cannot be allocated cout << "this is test01" << endl; //test01(); function call } //2. There is no return void test02(int a) { cout << "this is test02" << endl; cout << "a = " << a << endl; } //3. Return without participation int test03() { cout << "this is test03 " << endl; return 10; } //4. Participation and return int test04(int a, int b) { cout << "this is test04 " << endl; int sum = a + b; return sum; }
6.6 function declaration
Function: tell the compiler the function name and how to call the function. The actual body of a function can be defined separately.
- A function can be declared multiple times, but a function can only be defined once
Example:
//You can declare multiple times and define only once //statement int max(int a, int b); int max(int a, int b); //definition int max(int a, int b) { return a > b ? a : b; } int main() { int a = 100; int b = 200; cout << max(a, b) << endl; system("pause"); return 0; }
6.7 function sub file preparation
**Function: * * make the code structure clearer
Function sub file writing generally has four steps
- Create the suffix h header file
- Create the suffix cpp source file
- Write the declaration of the function in the header file
- Write the definition of the function in the source file
Example:
//swap.h file #include<iostream> using namespace std; //A function declaration that implements the exchange of two numbers void swap(int a, int b);
//swap.cpp file #include "swap.h" void swap(int a, int b) { int temp = a; a = b; b = temp; cout << "a = " << a << endl; cout << "b = " << b << endl; }
//main function file #include "swap.h" int main() { int a = 100; int b = 200; swap(a, b); system("pause"); return 0; }
7 pointer
7.1 basic concept of pointer
Function of pointer: memory can be accessed indirectly through pointer
- The memory number is recorded from 0, which is generally represented by hexadecimal digits
- Pointer variables can be used to save addresses
7.2 definition and use of pointer variables
Pointer variable definition syntax: data type * variable name;
Example:
int main() { //1. Definition of pointer int a = 10; //Define integer variable a //Pointer definition syntax: data type * variable name; int * p; //Assignment pointer variable p = &a; //The pointer points to the address of variable a cout << &a << endl; //Address of print data a cout << p << endl; //Print pointer variable p //2. Use of pointers //Memory pointed to by * operation pointer variable cout << "*p = " << *p << endl; system("pause"); return 0; }
Difference between pointer variable and ordinary variable
- Ordinary variables store data and pointer variables store addresses
- Pointer variables can operate the memory space pointed to by pointer variables through the "*" operator. This process is called dereference
Summary 1: we can get the address of the variable through the & symbol
Summary 2: use the pointer to record the address
Summary 3: dereference the pointer variable and operate the memory pointed to by the pointer
7.3 memory space occupied by pointer
Question: pointer is also a data type. How much memory does this data type occupy?
Example:
int main() { int a = 10; int * p; p = &a; //The pointer points to the address of data a cout << *p << endl; //*Dereference cout << sizeof(p) << endl; cout << sizeof(char *) << endl; cout << sizeof(float *) << endl; cout << sizeof(double *) << endl; system("pause"); return 0; }
Summary: all pointer types are 4 bytes under 32-bit operating system
7.4 null pointer and wild pointer
Null pointer: pointer variable points to the space numbered 0 in memory
**Purpose: * * initialize pointer variable
**Note: * * the memory pointed to by the null pointer is inaccessible
Example 1: null pointer
int main() { //The pointer variable p points to the space with memory address number 0 int * p = NULL; //Error accessing null pointer //Memory numbers 0 ~ 255 are the memory occupied by the system and are not allowed to be accessed by users cout << *p << endl; system("pause"); return 0; }
Wild pointer: pointer variable points to illegal memory space
Pointer example: field 2
int main() { //The pointer variable p points to the space with the memory address number 0x1100 int * p = (int *)0x1100; //Error in accessing field pointer cout << *p << endl; system("pause"); return 0; }
Conclusion: null pointer and wild pointer are not the space we apply for, so don't visit.
7.5 const modifier pointer
const modifier pointer has three cases
- const modifier pointer - constant pointer
- const modifier constant - pointer constant
- const modifies both pointers and constants
Example:
int main() { int a = 10; int b = 10; //const modifies the pointer. The pointer can be changed, and the value pointed to by the pointer cannot be changed const int * p1 = &a; p1 = &b; //correct //*p1 = 100; report errors //const is a constant. The pointer cannot be changed, and the value pointed to by the pointer can be changed int * const p2 = &a; //p2 = &b; // error *p2 = 100; //correct //const modifies both pointers and constants const int * const p3 = &a; //p3 = &b; // error //*p3 = 100; // error system("pause"); return 0; }
Tip: look at the pointer or constant immediately following the right side of const. The pointer is the constant pointer, and the constant is the constant pointer
7.6 pointers and arrays
**Function: * * use pointer to access elements in array
Example:
int main() { int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int * p = arr; //Pointer to array cout << "First element: " << arr[0] << endl; cout << "Pointer to access the first element: " << *p << endl; for (int i = 0; i < 10; i++) { //Traversing arrays with pointers cout << *p << endl; p++; } system("pause"); return 0; }
7.7 pointers and functions
**Function: * * use the pointer as the function parameter to modify the value of the actual parameter
Example:
//pass by value void swap1(int a ,int b) { int temp = a; a = b; b = temp; } //Address delivery void swap2(int * p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } int main() { int a = 10; int b = 20; swap1(a, b); // Value passing does not change the argument swap2(&a, &b); //Address passing changes the arguments cout << "a = " << a << endl; cout << "b = " << b << endl; system("pause"); return 0; }
Summary: if you don't want to modify the argument, pass it by value. If you want to modify the argument, pass it by address
7.8 pointer, array and function
**Case description: * * encapsulates a function and uses bubble sorting to sort integer arrays in ascending order
For example, array: int arr [10] = {4,3,6,9,1,2,10,8,7,5};
Example:
//Bubble sort function void bubbleSort(int * arr, int len) //int * arr can also be written as int arr [] { for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } //Print array function void printArray(int arr[], int len) { for (int i = 0; i < len; i++) { cout << arr[i] << endl; } } int main() { int arr[10] = { 4,3,6,9,1,2,10,8,7,5 }; int len = sizeof(arr) / sizeof(int); bubbleSort(arr, len); printArray(arr, len); system("pause"); return 0; }
Summary: when an array name is passed into a function as an argument, it is degenerated into a pointer to the first element
8 structure
8.1 basic concept of structure
Structures are user-defined data types that allow users to store different data types
8.2 definition and use of structure
Syntax: struct structure name {structure member list};
There are three ways to create variables through structures:
- struct structure name variable name
- struct structure name variable name = {member 1 value, member 2 value...}
- Create variables when defining structures
Example:
//Structure definition struct student { //Member list string name; //full name int age; //Age int score; //fraction }stu3; //Structure variable creation method 3 int main() { //Structure variable creation method 1 struct student stu1; //The struct keyword can be omitted stu1.name = "Zhang San"; stu1.age = 18; stu1.score = 100; cout << "full name:" << stu1.name << " Age:" << stu1.age << " fraction:" << stu1.score << endl; //Structure variable creation method 2 struct student stu2 = { "Li Si",19,60 }; cout << "full name:" << stu2.name << " Age:" << stu2.age << " fraction:" << stu2.score << endl; stu3.name = "Wang Wu"; stu3.age = 18; stu3.score = 80; cout << "full name:" << stu3.name << " Age:" << stu3.age << " fraction:" << stu3.score << endl; system("pause"); return 0; }
Summary 1: when defining a structure, the keyword is struct and cannot be omitted
Summary 2: when creating structural variables, the keyword struct can be omitted
Summary 3: structural variables use the operator '.' Access member
8.3 structure array
**Function: * * put the customized structure into the array for easy maintenance
Syntax: struct structure name array name [number of elements] = {{}, {} {} }
Example:
//Structure definition struct student { //Member list string name; //full name int age; //Age int score; //fraction } int main() { //Structure array struct student arr[3]= { {"Zhang San",18,80 }, {"Li Si",19,60 }, {"Wang Wu",20,70 } }; for (int i = 0; i < 3; i++) { cout << "full name:" << arr[i].name << " Age:" << arr[i].age << " fraction:" << arr[i].score << endl; } system("pause"); return 0; }
8.4 structure pointer
**Function: * * access members in structure through pointer
- Using the operator - > you can access the structure properties through the structure pointer
Example:
//Structure definition struct student { //Member list string name; //full name int age; //Age int score; //fraction }; int main() { struct student stu = { "Zhang San",18,100, }; struct student * p = &stu; p->score = 80; //Members can be accessed through the pointer - > operator cout << "full name:" << p->name << " Age:" << p->age << " fraction:" << p->score << endl; system("pause"); return 0; }
Summary: the structure pointer can access the members in the structure through the - > operator
8.5 structure nested structure
Action: a member in a structure can be another structure
**For example: * * each teacher tutors a student. In the structure of a teacher, record the structure of a student
Example:
//Definition of student structure struct student { //Member list string name; //full name int age; //Age int score; //fraction }; //Definition of teacher structure struct teacher { //Member list int id; //Employee number string name; //Teacher name int age; //Teacher age struct student stu; //Substructure student }; int main() { struct teacher t1; t1.id = 10000; t1.name = "Lao Wang"; t1.age = 40; t1.stu.name = "Zhang San"; t1.stu.age = 18; t1.stu.score = 100; cout << "Teacher staff No.: " << t1.id << " full name: " << t1.name << " Age: " << t1.age << endl; cout << "Name of trainee: " << t1.stu.name << " Age:" << t1.stu.age << " Test score: " << t1.stu.score << endl; system("pause"); return 0; }
**Summary: * * in a structure, you can define another structure as a member to solve practical problems
8.6 function parameters of structure
**Function: * * transfer the structure to the function as a parameter
There are two delivery methods:
- pass by value
- Address delivery
Example:
//Definition of student structure struct student { //Member list string name; //full name int age; //Age int score; //fraction }; //pass by value void printStudent(student stu ) { stu.age = 28; cout << "Name in subfunction:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl; } //Address delivery void printStudent2(student *stu) { stu->age = 28; cout << "Name in subfunction:" << stu->name << " Age: " << stu->age << " fraction:" << stu->score << endl; } int main() { student stu = { "Zhang San",18,100}; //pass by value printStudent(stu); cout << "Name in main function:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl; cout << endl; //Address delivery printStudent2(&stu); cout << "Name in main function:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl; system("pause"); return 0; }
Summary: if you do not want to modify the data in the main function, pass it by value, otherwise pass it by address
8.7 const usage scenario in structure
**Function: * * use const to prevent misoperation
Example:
//Definition of student structure struct student { //Member list string name; //full name int age; //Age int score; //fraction }; //const usage scenario void printStudent(const student *stu) //Add const to prevent misoperation in function body { //stu->age = 100; // The operation failed because of the const modifier cout << "full name:" << stu->name << " Age:" << stu->age << " fraction:" << stu->score << endl; } int main() { student stu = { "Zhang San",18,100 }; printStudent(&stu); system("pause"); return 0; }
8.8 structural case
8.8.1 case 1
Case description:
The school is working on the completion project. Each teacher leads 5 students, with a total of 3 teachers. The needs are as follows
Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members
Students' members have names and test scores. Create an array to store 3 teachers, and assign values to each teacher and students through functions
Finally, print out the teacher data and the student data brought by the teacher.
Example:
struct Student { string name; int score; }; struct Teacher { string name; Student sArray[5]; }; void allocateSpace(Teacher tArray[] , int len) { string tName = "teacher"; string sName = "student"; string nameSeed = "ABCDE"; for (int i = 0; i < len; i++) { tArray[i].name = tName + nameSeed[i]; for (int j = 0; j < 5; j++) { tArray[i].sArray[j].name = sName + nameSeed[j]; tArray[i].sArray[j].score = rand() % 61 + 40; } } } void printTeachers(Teacher tArray[], int len) { for (int i = 0; i < len; i++) { cout << tArray[i].name << endl; for (int j = 0; j < 5; j++) { cout << "\t full name:" << tArray[i].sArray[j].name << " fraction:" << tArray[i].sArray[j].score << endl; } } } int main() { srand((unsigned int)time(NULL)); //Random number seed header file #include < CTime > Teacher tArray[3]; //Teacher array int len = sizeof(tArray) / sizeof(Teacher); allocateSpace(tArray, len); //Create data printTeachers(tArray, len); //print data system("pause"); return 0; }
8.8.2 case 2
Case description:
Design a hero structure, including member name, age and gender; Create a structure array, in which 5 heroes are stored.
Through the bubble sorting algorithm, the heroes in the array are sorted in ascending order according to their age, and the sorted results are finally printed.
The information of the five heroes is as follows:
{"Liu Bei",23,"male"}, {"Guan Yu",22,"male"}, {"Fei Zhang",20,"male"}, {"Zhao Yun",21,"male"}, {"army officer's hat ornaments",19,"female"},
Example:
//Hero structure struct hero { string name; int age; string sex; }; //Bubble sorting void bubbleSort(hero arr[] , int len) { for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - 1 - i; j++) { if (arr[j].age > arr[j + 1].age) { hero temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } //Print array void printHeros(hero arr[], int len) { for (int i = 0; i < len; i++) { cout << "full name: " << arr[i].name << " Gender: " << arr[i].sex << " Age: " << arr[i].age << endl; } } int main() { struct hero arr[5] = { {"Liu Bei",23,"male"}, {"Guan Yu",22,"male"}, {"Fei Zhang",20,"male"}, {"Zhao Yun",21,"male"}, {"army officer's hat ornaments",19,"female"}, }; int len = sizeof(arr) / sizeof(hero); //Get the number of array elements bubbleSort(arr, len); //sort printHeros(arr, len); //Print system("pause"); return 0; }
u->score << endl;
}
int main() {
student stu = { "Zhang San",18,100}; //pass by value printStudent(stu); cout << "Name in main function:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl; cout << endl; //Address delivery printStudent2(&stu); cout << "Name in main function:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl; system("pause"); return 0;
}
> Summary: if you do not want to modify the data in the main function, pass it by value, otherwise pass it by address ### 8.7 const usage scenario in structure **effect:**use const To prevent misoperation **Example:** ```C++ //Definition of student structure struct student { //Member list string name; //full name int age; //Age int score; //fraction }; //const usage scenario void printStudent(const student *stu) //Add const to prevent misoperation in function body { //stu->age = 100; // The operation failed because of the const modifier cout << "full name:" << stu->name << " Age:" << stu->age << " fraction:" << stu->score << endl; } int main() { student stu = { "Zhang San",18,100 }; printStudent(&stu); system("pause"); return 0; }
8.8 structural case
8.8.1 case 1
Case description:
The school is working on the completion project. Each teacher leads 5 students, with a total of 3 teachers. The needs are as follows
Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members
Students' members have names and test scores. Create an array to store 3 teachers, and assign values to each teacher and students through functions
Finally, print out the teacher data and the student data brought by the teacher.
Example:
struct Student { string name; int score; }; struct Teacher { string name; Student sArray[5]; }; void allocateSpace(Teacher tArray[] , int len) { string tName = "teacher"; string sName = "student"; string nameSeed = "ABCDE"; for (int i = 0; i < len; i++) { tArray[i].name = tName + nameSeed[i]; for (int j = 0; j < 5; j++) { tArray[i].sArray[j].name = sName + nameSeed[j]; tArray[i].sArray[j].score = rand() % 61 + 40; } } } void printTeachers(Teacher tArray[], int len) { for (int i = 0; i < len; i++) { cout << tArray[i].name << endl; for (int j = 0; j < 5; j++) { cout << "\t full name:" << tArray[i].sArray[j].name << " fraction:" << tArray[i].sArray[j].score << endl; } } } int main() { srand((unsigned int)time(NULL)); //Random number seed header file #include < CTime > Teacher tArray[3]; //Teacher array int len = sizeof(tArray) / sizeof(Teacher); allocateSpace(tArray, len); //Create data printTeachers(tArray, len); //print data system("pause"); return 0; }
8.8.2 case 2
Case description:
Design a hero structure, including member name, age and gender; Create a structure array, in which 5 heroes are stored.
Through the bubble sorting algorithm, the heroes in the array are sorted in ascending order according to their age, and the sorted results are finally printed.
The information of the five heroes is as follows:
{"Liu Bei",23,"male"}, {"Guan Yu",22,"male"}, {"Fei Zhang",20,"male"}, {"Zhao Yun",21,"male"}, {"army officer's hat ornaments",19,"female"},
Example:
//Hero structure struct hero { string name; int age; string sex; }; //Bubble sorting void bubbleSort(hero arr[] , int len) { for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - 1 - i; j++) { if (arr[j].age > arr[j + 1].age) { hero temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } //Print array void printHeros(hero arr[], int len) { for (int i = 0; i < len; i++) { cout << "full name: " << arr[i].name << " Gender: " << arr[i].sex << " Age: " << arr[i].age << endl; } } int main() { struct hero arr[5] = { {"Liu Bei",23,"male"}, {"Guan Yu",22,"male"}, {"Fei Zhang",20,"male"}, {"Zhao Yun",21,"male"}, {"army officer's hat ornaments",19,"female"}, }; int len = sizeof(arr) / sizeof(hero); //Get the number of array elements bubbleSort(arr, len); //sort printHeros(arr, len); //Print system("pause"); return 0; }