1, Introduction to C + +
1. C + + initial
1.1 the first C + + program
Write code
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> using namespace std; int main() { cout << "HelloWorld" << endl; system("pause"); return 0; }
1.2 notes
**Function: * * add some book titles and explanations to the code to facilitate yourself or others to read the code
Two formats
- Single line comment: / / description
- It is usually placed at the top of a line of code or at the end of a statement to explain the code
- Multiline comment: / * description information*/
- It is usually placed at the top of a piece of code to explain the whole piece of code
The compiler ignores 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;
**Significance of variables: * * it is convenient for us to manage memory space.
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> using namespace std; int main() { //Syntax of variable creation: data type variable name = variable initial value int a = 10; cout << "a = " << a << endl; system("pause"); return 0; }
1.4 constants
**Function: * * used to record unchangeable data in the program
Two ways of defining 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
- The keyword const is usually added before the variable definition to modify the variable as a constant and cannot be modified.
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> using namespace std; #define PI 3.1415 /* Definition of constants 1,#define Macro constant 2,const Modified variable */ int main0104() { const int a = 20; cout << "PI = " << PI << endl; cout << "a = " << a << endl; system("pause"); return 0; }
1.5 keywords
**Function: * * keyword is a word (identifier) reserved in C + +
Do not use variables or constants when defining keywords
1.6 identifier naming rules
**Function: * * C + + has its own rules when naming identifiers (variables, constants)
- Identifier cannot be a keyword
- The identifier can only be composed of letters, numbers and underscores
- The first character must be a letter or underscore
- Letters in identifiers are case sensitive
Suggestion: when naming an identifier, you should know the meaning according to the name
2 data type
C + + stipulates that when creating a variable or constant, the corresponding data type must be pointed out. Otherwise, memory cannot be allocated to the variable
2.1 integer
Function: integer variables represent integer data
The types that can represent integers in C + + have a centralized way. The difference is that they occupy different memory space
data type | Occupied space | Value range |
---|---|---|
Short (short integer) | 2 bytes | (-2^15 - 2^15-1) |
int (integer) | 4 bytes | (-2^31 - 2^31-1) |
Long (long integer) | win (4 bytes) Linux (32 bits: 4 bytes) (64 bits: 8 bytes) | (-2^31 - 2^31-1) |
long long (long integer) | 8 bytes | (-2^63 - 2^63-1) |
2.2 sizeof keyword
Function: use sizeof keyword to count the memory size occupied by data type
Syntax: sizeof (data type / variable)
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include <bits/stdc++.h> using namespace std; //The keyword sizeof can calculate the memory occupied by the data type int main0202() { //1. Segment integer short num1 = 10;//(-32768 ~ 32767) //2. Integer int num2 = 10; //3. Long integer long num3 = 10; //4. Long integer long long num4 = 10; cout << "num1 = " << num1 << " " << sizeof(num1) << endl; cout << "num2 = " << num2 << " " << sizeof(num2) << endl; cout << "num3 = " << num3 << " " << sizeof(num3) << endl; cout << "num4 = " << num4 << " " << sizeof(num4) << endl; system("pause"); return 0; }
2.3 real (floating point)
**Function: * * used to represent decimals
There are two types of floating point variables:
- Single precision float
- Double precision double
The difference between the two lies in the different range of significant numbers
data type | Occupied space | Significant digit range |
---|---|---|
float | 4 bytes | 7 significant digits |
double | 8 bytes | 15 ~ 16 significant digits |
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include <bits/stdc++.h> using namespace std; int main() { //1. Single precision float //2. Double precision double //By default, 6 significant decimal places are output float f1 = 3.141592658f; cout << "f1 = " << f1 << " " << sizeof(f1) << endl; double d1 = 3.1415926658; cout << "d1 = " << d1 << " " << sizeof(d1) << endl; //Scientific counting method float f2 = 3e2;//3 * 10 ^2 cout << "f2 = " << f2 << endl; float f3 = 3e-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 using hinas 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
- In C and C + +, character variables only occupy 1 byte
- Character type variables do not store the character itself in memory, but put the corresponding ASCII code in the storage unit
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<bits\stdc++.h> using namespace std; int main() { //1. Creation method of character variable char ch = 'a'; cout << ch << endl; //2. Memory size of character variable cout << "char Memory space occupied by character variables:" << sizeof(char) << endl; //3. Common errors in character variables //char ch2 = "b"; // Use single quotation marks to create character variables //char ch3 = 'abcdef'; // When creating a character variable, there can only be one character in a single quotation mark //4. ASCII encoding corresponding to character type variable //a - 97 //A - 65 cout << (int)ch << endl; system("pause"); return 0; }
2.5 escape characters
**Function: * * used to indicate some ASCII characters that cannot be displayed
Commonly used are: \ n \ \ t
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<bits\stdc++.h> using namespace std; int main() { //Escape character //Newline character \ n cout << "Hello\nWorld!" << endl; //Backslash\ cout << "\\" << endl; //Horizontal tab \ tfunction: it can output data neatly cout << "aaa\tHelloWorld" << endl; cout << "aaaaaa\tHelloWorld" << endl; cout << "aa\tHelloWorld" << endl; system("pause"); return 0; }
2.6 string type
**Function: * * used to represent a string of characters
Two styles
1. C language style string: char variable name [] = "string value"
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<bits/stdc++.h> using namespace std; int main() { char str1[] = "HelloWorld"; cout << str1 << endl; system("pause"); return 0; }
Note: C-style strings should be enclosed in double quotation marks
2. C + + style string: string variable name = "string value"
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<bits/stdc++.h> using namespace std; int main() { //C + + style string //When using string, you need to add the header #include < string >, which is included in the universal header file srting str2 = "HelloWorld"; cout << str2 << endl; system("pause"); return 0; }
Note: when using C + + string, add header file #include
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:
#define _CRT_SECURE_NO_WARNINGS 1 #include<bits\stdc++.h> using namespace std; int main() { //Create bool type data bool flag = true; cout << flag << endl; flag = false; cout << flag << endl; //View the space occupied by bool type cout << "bool Space occupied by type data:" << sizeof(bool) << endl; system("pause"); return 0; }
2.8 data input
**Function: * * used to obtain data from the keyboard
**Keywords: * * cin
Syntax: CIN > > variable
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<bits\stdc++.h> using namespace std; int main() { //1. Integer int a = 0; cout << "Please give integer variable a Assignment:" << endl; cin >> a; cout << "a = " << a << endl; //2. Floating point type float f = 3.14f; cout << "Please give floating point variable f Assignment:" << endl; cin >> f; cout << "f = " << f << endl; //3. Character type char ch = 'a'; cout << "Please give character variable ch Assignment:" << endl; cin >> ch; cout << "ch = " << ch << endl; //4. String type string str = "Hello"; cout << "Please give the string variable str Assignment:" << endl; cin >> str; cout << "str = " << str << endl; //5. Boolean type bool bl = true; cout << "Please give boolean variable bl Assignment:" << endl; cin >> bl; cout << "bl = " << bl << endl; system("pause"); return 0; }
3 operator
**Function: * * used to execute code operation
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 |
---|---|---|---|
+ | just right | +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:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //add , subtract , multiply and divide int a1 = 10; int b1 = 3; cout << a1 + b1 << endl; cout << a1 - b1 << endl; cout << a1 * b1 << endl; cout << a1 / b1 << endl; //Two integers are still integers. Remove the decimal part int a2 = 10; int b2 = 20; cout << a2 / b2 << endl; //int a3 = 10; //int b3 = 0; //cout << a3 / b3 << endl;// Divisor cannot be 0 double d1 = 0.5; double d2 = 0.22; cout << d2 / d1 << endl; system("pause"); return 0; }
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:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //Assignment Operators // = int a = 10; a = 100; cout << "a = " << a << endl; // += a = 10; a += 2; cout << "a = " << a << endl; // -= a = 10; a -= 2; cout << "a = " << a << endl; // *= a = 10; a *= 2; cout << "a = " << a << endl; // /= a = 10; a /= 10; cout << "a = " << a << endl; // %= a = 10; 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 >= 3 | 1 |
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //Comparison operator // == int a = 10; int b = 20; cout << (a == b) << endl; // != cout << (a != b) << endl; // > cout << (a > b) << endl; // < cout << (a < b) << endl; // >= cout << (a >= b) << endl; // <= cout << (a <= b) << endl; system("pause"); return 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
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //Logical operator not! int a = 10; //In C + +, all but 0 are true cout << !a << endl; //0 cout << !!a << endl; //1 system("pause"); return 0; }
Summary: true becomes false, false becomes true
**Example 2: * * logic and
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //Logic and operation&& int a = 10; int b = 10; cout << (a&&b) << endl; //1 a = 0; b = 10; cout << (a&&b) << endl; //0 a = 0; b = 0; cout << (a&&b) << endl; //0 system("pause"); return 0; }
Conclusion: the same truth is true and the rest is false
**Example 3: * * logical or
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { int a = 10; int b = 10; cout << (a || b) << endl; //1 a = 0; 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; }
Conclusion: the same false is false, and the rest is true
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
- Select structure: perform corresponding functions selectively according to whether the conditions are met
- 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
There are three forms of if statements:
1. Single line format: if (condition) {statement executed when the condition is met}
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //Select a single line if statement of the structure //The user enters a score. If the score is greater than 600, it will be regarded as entering a university and output on the screen //1. User input score int score = 0; cout << "Please enter a score:" << endl; cin >> score; //2. Print user entered scores cout << "The score you entered is:" << score << endl; //3. Judge whether the score is greater than 600. If it is greater than 600, it will be output //Note: do not add a semicolon after the if condition if (score > 600) { cout << "Congratulations on your admission to a university" << endl; } system("pause"); return 0; }
2. Multi line format if statement: if (condition) {statement executed when the condition meets} else {statement executed when the condition does not meet}
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //Select structure - multiline if statement //Enter the test score. If the score is greater than 600, it will be regarded as having been admitted to a university and output it on the screen. If not, it will be printed //1. Enter test score int score = 0; cout << "Please enter an exam score" << endl; cin >> score; //2. Prompt user for score cout << "The score you entered is:" << score << endl; //3. Judge if (score > 600) { cout << "Congratulations, admitted to a university" << endl; } else { cout << "Failed to enter a university" << endl; } system("pause"); return 0; }
3. Multi conditional if statement: if (condition 1) {statement executed when condition 1 meets} else if (condition 2) {statement executed when condition 2 meets} Else {does not satisfy the executed statement}
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //Select multiple conditional if statements int score = 0; cout << "Please enter a test score:" << endl; cin >> score; cout << "The score you entered is:" << score << endl; //Enter an examination score. If it is greater than 600, it will be regarded as entering a university and output on the screen //If it is greater than 500, it is regarded as having been admitted to two universities, and the screen output //If it is greater than 400, it is regarded as having been admitted to three universities and output on the screen if (score > 600) { cout << "Congratulations, admitted to a university" << endl; } else if (score > 500) { cout << "Congratulations, admitted to two universities" << endl; } else if (score > 400) { cout << "Congratulations, admitted to three universities" << endl; } else { cout << "Sorry, you didn't get an undergraduate degree" << endl; } system("pause"); return 0; }
**Nested if statements: * * in if statements, you can use nested if statements to achieve more accurate conditional 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
- In a book, if the score is greater than 700, you will be admitted to Peking University, greater than 650, Tsinghua University and National People's Congress
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { int score = 0; cout << "Please enter a test score:" << endl; cin >> score; cout << "The score you entered is:" << score << endl; //Enter an examination score. If it is greater than 600, it will be regarded as entering a university and output on the screen //If it is greater than 500, it is regarded as having been admitted to two universities, and the screen output //If it is greater than 400, it is regarded as having been admitted to three universities and output on the screen if (score > 600) { if (score > 700) { cout << "Congratulations on being admitted to Peking University" << endl; } else if (score > 650) { cout << "Congratulations on being admitted to Tsinghua University" << endl; } else { cout << "Congratulations on being admitted to the National People's Congress" << endl; } } else if (score > 500) { cout << "Congratulations, admitted to two universities" << endl; } else if (score > 400) { cout << "Congratulations, admitted to three universities" << endl; } else { cout << "Sorry, you didn't get an undergraduate degree" << endl; } system("pause"); return 0; }
4.1.2 ternary operator
**Function: * * simple judgment can be realized through the ternary 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:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //ternary operator //Create three variables a, b and c, compare a and b, and assign the large value of the variable to variable c int a = 0; int b = 0; int c = 0; cout << "Please enter a Value of:" << endl; cin >> a; cout << "Please enter b Value of:" << endl; cin >> b; c = (a > b ? a : b); cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; //In C + +, the ternary operator returns variables and can continue to assign values (a < b ? a : b) = 100; cout << "a = " << a << endl; cout << "b = " << b << endl; system("pause"); return 0; }
4.1.3 switch statement
**Function: * * execute multi conditional branch statements
Syntax:
switch(expression) { case Result 1:Execute statement;break; case Result 2:Execute statement;break; ... default:Execute statement;break; }
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //switch Statements //Rate movies //10 ~ 9 classic //8 ~ 7 very good //6 ~ 5 general //Rotten film below 5 //1. Prompt users to score cout << "Please rate the movie:" << endl; //2. The user started scoring int score = 0; cin >> score; cout << "Your score is:" << score << " branch" << endl; //3. Prompt the user for the final result according to the score entered by the user switch (score) { case 10: cout << "What do you think is a classic movie" << endl; break; case 9: cout << "What do you think is a classic movie" << endl; break; case 8: cout << "Do you think it's a very good film" << endl; break; case 7: cout << "Do you think it's a very good film" << endl; break; case 6: cout << "Do you think it's an ordinary film" << endl; break; case 5: cout << "Do you think it's an ordinary film" << endl; break; default: cout << "Do you think this is a bad film" << endl; break; } system("pause"); return 0; }
Differences between if and switch statements
- Disadvantages of switch: when judging, it can only be integer or character type, not an interval
- switch has the advantages of clear structure and high execution efficiency
- If there is no break in the case, the program will run all the time
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: * * execute the loop statement as long as the result of the loop condition is true
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //while Loop //Print the 10 numbers 0 ~ 9 on the screen int num = 0; while (num<10) { cout << "num = " << num << endl; num++; } system("pause"); return 0; }
4.2.2 do... while loop statement
**Function: * * execute loop statements when loop conditions are met
Syntax: do {loop statement} while (loop condition)
Note: the difference between while and do... While is that it will execute a loop statement first, and then judge the loop conditions
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //Output 10 numbers from 0 to 9 on the screen 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 condition
**Exercise case: * * number of daffodils
**Case description: * * daffodil value refers to a three digit number, and the sum of the three powers of the numbers in 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
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { int num = 100; do { int a = 0; int b = 0; int c = 0; a = num % 10; b = num / 10 % 10; c = num / 100; if (a*a*a+b*b*b+c*c*c == num) { cout << num << endl; } num++; } while (num<1000); system("pause"); return 0; }
4.2.3 for loop statement
**Function: * * execute loop statements when loop conditions are met
Syntax: for (start expression; conditional expression; end loop body) {loop statement;}
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //for loop //The number 0 prints to the number 9 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
Nested loop
**Function: * * nest another layer of loop in the loop body to solve some practical problems
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { char x = '*'; //Print star map for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { cout << x<<" " ; } cout << endl; } system("pause"); return 0; }
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:
- In the switch conditional statement, the function is to terminate the case and jump out of the switch
- Appears in a circular statement to jump out of the current circular statement
- Appears in a nested loop, jumping out of the nearest inner loop
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //break usage timing //1. Appear in switch //Cout < < please select Copy difficulty < < endl; //Cout < < 1. Ordinary < < endl; //Cout < < 2, medium < < endl; //Cout < < 3. Difficulties < < endl; //int select = 0; //cin >> select; //switch (select) //{ //case 1: // Cout < < you chose ordinary difficulty < < endl; // break; //case 2: // Cout < < you chose medium difficulty < < endl; // break; //case 3: // Cout < < what you choose is difficulty < < endl; // break; //default: // break; //} //2. Appears in a circular statement /*for (int i = 0; i < 10; i++) { if (i == 5) { break; } cout << i << endl; }*/ //3. Appears in a nested 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 the summary of circular statements, skip the remaining unexecuted statements in this cycle and continue to execute the next cycle
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //continue Statement for (int i = 0; i < 30; i++) { if (i % 2 == 0) { continue; } 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: * * can jump statements unconditionally
Syntax: goto tag;
**Explanation: * * if the name of the tag exists, the goto statement will jump to the location of the tag
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //goto Statement cout << "1," << endl; cout << "2," << endl; cout << "3," << endl; goto FLAG; cout << "4," << endl; cout << "5," << endl; cout << "6," << endl; FLAG: cout << "7," << 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 containing data elements of the same type
characteristic:
- Each data element in the array is of the same data type
- An array consists of contiguous 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,...};
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; int main() { //array /* 1. Data type array name [array length]; 2. Data type array name [array length] = {value 1, value 2,...}; 3. Data type array name [] = {value 1, value 2,...}; */ //1. Data type array name [array length]; int arr[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; for (int i = 0; i < 5; i++) { cout << arr[i] << endl; } cout << "===================" << endl; //2. Data type array name [array length] = {value 1, value 2,...}; int arr2[5] = { 10,20,30,40,50 }; for (int i = 0; i < 5; i++) { cout << arr2[i] << endl; } cout << "=====================" << endl; //3. Data type array name [] = {value 1, value 2,...}; int arr3[] = { 90, 80,70,60,50,40,30,20,10 }; for (int i = 0; i < 9; i++) { cout << arr3[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 of one-dimensional array name:
- 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 function //1. You can count the space occupied by the entire array through the array name int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; cout << "Space occupied by the whole array:" << sizeof(arr) << endl; cout << "The memory occupied by integer type is:" << sizeof(arr[0]) << endl; cout << "The number of elements in the array is:" << sizeof(arr) / sizeof(int) << endl; //2. You can view 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:" << (int)&arr[0] << endl; cout << "The address of the second element in the array is:" << (int)&arr[1] << endl; //The array name is a constant and cannot be assigned system("pause"); return 0; }
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, the number of comparisons is - 1 each time, and you know there is no need to compare
Comparison times: total rounds of sorting = number of elements - 1
Comparison times per round = element - number of sorting rounds - 1
**Example: * * sort the array {4,2,8,0,5,7,1,3,9} in ascending order
int main() { //Using bubble sort to realize ascending order int arr[9] = { 4,2,8,0,5,7,1,3,9 }; cout << "Before sorting:" << endl; for (int i = 0; i < 9; i++) { cout << arr[i] << " "; } cout << endl; //Sort: for (int i = 0; i < 9 - 1; i++) { //Comparison of inner circulation for (int j = 0; j < 9 - i - 1; j++) { //If the first number is larger than the second, swap the two numbers if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } //Sorted results cout << "After sorting:" << endl; for (int i = 0; i < 9; i++) { cout << arr[i] << " "; } cout << 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.
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() { //Definition of two-dimensional array int arr[2][3] = { {1,2,3}, {4,5,6} }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr[i][j]<<" "; } cout << endl; } system("pause"); return EXIT_SUCCESS; }
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 usage //1. You can view the array memory space int arr[2][3] = { {1,2,3}, {4,5,6} }; cout << "Space occupied by two-dimensional array:" << sizeof(arr) << endl; cout << "The memory occupied by the first row of two-dimensional array is:" << sizeof(arr[0]) << endl; cout << "The memory occupied by the first element of the two-dimensional array is:" << sizeof(arr[0][0]) << endl; cout << "Rows of 2D array:" << sizeof(arr) / sizeof(arr[0]) << endl; cout << "Number of columns of two-dimensional array:" << sizeof(arr[0]) / sizeof(arr[0][0]) << endl; //2. You can view the first address of the two-dimensional array cout << "The first address of the two-dimensional array is:" << (int)arr << endl; system("pause"); return EXIT_SUCCESS; }
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 |
answer:
int main() { //Two dimensional array case - test score statistics //1. Create a 2D array int scores[3][3] = { {100,100,100}, {90,50,100}, {60,70,80} }; string names[3] = { "Zhang San","Li Si","Wang Wu" }; //2. Count the scores per person for (int i = 0; i < 3; i++) { int a = 0; for (int j = 0; j < 3; j++) { a += scores[i][j]; } cout << names[i] << "The total score is:" << a << endl; } system("pause"); return EXIT_SUCCESS; }
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:
- return type
- Function name
- parameter list
- Function body statement
- 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 the 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
//Definition of function int add(int num1, int num2) { int sum = num1 + num2; return sum; } int main() { system("pause"); return EXIT_SUCCESS; }
6.3 function call
**Function: * * use defined function
Syntax: function name (parameter)
Example:
int add(int num1, int num2) { int sum = num1 + num2; return sum; } int main() { int a = 10; int b = 20; int c = add(a, b); cout << "c = " << c << endl; system("pause"); return EXIT_SUCCESS; }
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 << "Value before exchange:" << endl; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; int temp = num1; num1 = num2; num2 = temp; cout << "Value after exchange:" << endl; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; return; } int main() { int a = 10; int b = 20; cout << "a = " << a << endl; cout << "b = " << b << endl; swap(a, b); //During value transfer, the formal parameters of the function change, but the actual parameters do not change cout << "a = " << a << endl; cout << "b = " << b << endl; system("pause"); return EXIT_SUCCESS; }
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 forms of functions //1. No participation and no return void test01() { cout << "this is test01" << endl; } //2. No return with reference 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 1000; } //4. Participation and return int test04(int a) { cout << "this is test04" << endl; return a; } int main() { //Call of parameterless and non return function test01(); cout << "===========================" << endl; //Call of function with parameters and no return test02(100); cout << "===========================" << endl; //Call of parameterless return function int num1 = test03(); cout << "num1 = " << num1 << endl; cout << "===========================" << endl; //Call of function with parameters and return int num2 = test04(10000); cout << "num2 = " << num2 << endl; system("pause"); return EXIT_SUCCESS; }
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:
//Declaration of function int max(int a, int b); using namespace std; //Declaration of function //Comparison function to compare two integer numbers and return the maximum value int main() { int a = 10; int b = 20; cout << max(a, b) << endl; system("pause"); return EXIT_SUCCESS; } int max(int a, int b) { return a > b ? a : b; }
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 a suffix of 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);
7 pointer
7.1 basic concept of pointer
**Function of pointer: * * memory can be accessed through pointer introduction
- 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;
Usage process of pointer?:
-
Define pointer
-
Let the pointer record the address of the variable
-
The data in memory can be accessed by using the pointer * before modification. This step is called dereference
int main() { //1. Define pointer int a = 10; //Syntax of pointer definition: data type * pointer variable; int * p; //Let pointer p record the address of variable a p = &a; cout << "a Your address is:" << &a << endl; cout << "p = " << p << endl; //2. Use pointer //You can find the memory pointed to by the pointer by dereferencing //Add a * before the pointer to represent dereference and find the data in memory pointed to by the pointer cout << *p << endl; *p = 1000; cout << "a = " << a << endl; cout << "*p = " << *p << endl; system("pause"); return EXIT_SUCCESS; }
7.3 memory space occupied by pointer
In 32-bit operating system: 4 bytes
Under 64 bit operating system: 8 bytes
int main() { //Memory space occupied by pointer int a = 10; //int * p; //p = &a; int * p = &a; cout << "sizeof(int *) = " << sizeof(int *) << endl; cout << "sizeof(float *) = " << sizeof(float *) << endl; cout << "sizeof(double *) = " << sizeof(double *) << endl; cout << "sizeof(char *) = " << sizeof(char *) << endl; system("pause"); return EXIT_SUCCESS; }
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() { //Null pointer //1. Null pointers are used to initialize pointer variables int * p = NULL; //2. Null pointers are not accessible //The memory number between 0 and 255 is occupied by the system, so it cannot be accessed //An error will be reported when accessing a null pointer *p = 100; system("pause"); return EXIT_SUCCESS; }
**Wild pointer: * * pointer variable points to illegal memory space
Example 2: field pointer
int main() { //Field pointer //In the program, try to avoid wild pointers int * p = (int *)0x1100; system("pause"); return EXIT_SUCCESS; }
In the program, try to avoid using wild pointers
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 conditions:
- const modifier pointer - constant pointer
- const int * p = &a;
- Features: the pointer can be changed, but the value pointed by the pointer cannot be changed
- const modifier constant - pointer constant
- int * const p = &a;
- Features: the pointer cannot be changed, but the value pointed by the pointer can be changed
- const modifies both pointers and constants
- const int * const p = &a;
- Features: the pointer and the value pointed by the pointer cannot be changed
Example:
int main() { //1. Const modifier pointer const pointer int a = 10; int b = 10; //The value pointed to by the pointer cannot be changed, and the pointer can be changed const int * p = &a; //*p = 20; error p = &b;//correct //2. const modifier constant //The pointer cannot be changed, and the value pointed by the pointer can be changed int * const p2 = &a; *p2 = 100; //p2 = &b; The pointer cannot be changed //3. const modifies pointers and constants const int * const p3 = &a; //Neither the pointer nor the value pointed to by the pointer can be changed //*p3 = 100; error //p3 = &b; error system("pause"); return EXIT_SUCCESS; }
7.6 pointers and arrays
**Function: * * use pointer to access elements in array
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; int main() { //Pointers and arrays //Using pointers to access elements in an array int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; cout << "The first element is:" << arr[0] << endl; int * p = arr;//arr is the first address of the array cout << "Use pointers to access the first element of the array" << *p << endl; p++;//Offset the pointer back by 4 bytes cout << "Use a pointer to access the second element of the array" << *p << endl; cout << "Traversing arrays with pointers" << endl; int * p2 = arr; for (int i = 0; i < 10; i++) { //cout << arr[i] << endl; cout << *p2 << endl; p2++; } system("pause"); return EXIT_SUCCESS; }
7.7 pointers and functions
**Function: * * use the pointer as the function parameter to modify the value of the actual parameter
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; //Realize two digital exchanges void swap(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; } void swap01(int *p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } int main() { //Pointers and functions //1. Value transfer int a = 10; int b = 20; swap(a, b); cout << "a = " << a << endl; cout << "b = " << b << endl; //2. Address delivery //If it is address passing, you can modify the argument swap01(&a, &b); cout << "a = " << a << endl; cout << "b = " << b << endl; system("pause"); return EXIT_SUCCESS; }
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 realize the ascending order of integer array
For example, array: int arr[10] = {4,3,6,9,1,2,10,8,7,5}
Examples
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; //Bubble sort function void bubbleSort(int *arr, int len) { for (int i = 0; i < len-1; i++) { for (int j = 0; j < len - i - 1; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } //Print array void printArray(int *arr, int len) { for (int i = 0; i < len; i++) { cout << arr[i] << endl; } } int main() { //1. Create array first int arr[10] = { 4,3,6,9,1,2,10,8,7,5 }; int len = sizeof(arr) / sizeof(arr[0]); //2. Create a function to realize bubble sorting bubbleSort(arr, len); //3. Print sorted array printArray(arr, len); system("pause"); return EXIT_SUCCESS; }
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:
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> using namespace std; //1. Create student data type: student (name, age, score) struct Student { //Member list //full name string name; //Age int age; //fraction int score; }s3; //2. Create specific students by student data type int main() { //Use of structure //(1)struct Student s1; //The struct keyword can be omitted struct Student s1; //Assign value to s1 attribute s1.name = "Zhang San"; s1.age = 18; s1.score = 100; cout << "full name:" << s1.name << " Age:" << s1.age << " fraction:" << s1.score << endl; //(2)struct Student s2 = { ... }; struct Student s2 = {"Li Si", 19, 80}; cout << "full name:" << s2.name << " Age:" << s2.age << " fraction:" << s2.score << endl; //(3) When defining a structure, create a structure variable by the way s3.name = "Wang Wu"; s3.age = 20; s3.score = 60; cout << "full name:" << s3.name << " Age:" << s3.age << " fraction:" << s3.score << endl; system("pause"); return EXIT_SUCCESS; }
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 "." To access members
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:
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> using namespace std; //Structure array //1. Define structure struct Student { //full name string name; //Age int age; //fraction int score; }; int main() { //2. Create structure array struct Student stuArray[3] = { {"Zhang San", 18, 100}, {"Li Si", 19, 99}, {"Wang Wu", 20, 66} }; //3. Assign value to structure array stuArray[2].name = "Zhao Liu"; //4. Traversal structure array for (int i = 0; i < 3; i++) { cout << stuArray[i].name << " " << stuArray[i].age << " " << stuArray[i].score << endl; } system("pause"); return EXIT_SUCCESS; }
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:
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> using namespace std; //Structure pointer struct student { string name; int age; int score; }; int main() { //Create student structure variable struct student s = { "Zhang San", 18, 100 }; //Pointer to structure variable through pointer struct student *p = &s; //Accessing data in structure variables through pointers //You need to use '- >' to access the attributes in the structure through the structure pointer cout << "full name:" << p->name << " Age:" << p->age << " fraction:" << p->score << endl; system("pause"); return EXIT_SUCCESS; }
Summary: the structure pointer can access the members in the structure through the - > operator
8.5 structure nested structure
**Function: * * a member in a structure can be another structure
**For example: * * each teacher tutors a college. In the structure of a teacher, record the structure of a student
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> using namespace std; //Define student structure struct student { string name; int age; int score; }; //Define teacher structure struct teacher { int id; string name; int age; student stu; }; int main() { //Structure nested structure //Create teacher teacher t; t.id = 10000; t.name = "Lao Wang"; t.age = 50; student s = {"Zhang San",18,100}; t.stu = s; cout << "Teacher's name:" << t.name << " Teacher's number:" << t.id << " Teacher's age:" << t.age << " Students assisted by teachers:" << t.stu.name << " The age of the student is:" << t.stu.age << " The student's score is:" << t.stu.score << endl; system("pause"); return EXIT_SUCCESS; }
8.6 function parameters of structure
**Function: * * transfer structure as parameter to function
There are two delivery methods:
- pass by value
- Address delivery
Example:
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> using namespace std; //Define student structure struct student { string name; int age; int score; }; //Print student information function //pass by value void printStudent01(student stu) { stu.age = 100; cout << "Results printed in subfunction 01:" << endl; cout << "full name:" << stu.name << " Age:" << stu.age << " fraction:" << stu.score << endl; } //Address delivery void printStudent02(student *p) { p->age = 200; cout << "Results printed in subfunction 02:" << endl; cout << "full name:" << p->name << " Age:" << p->age << " fraction:" << p->score << endl; } int main() { student s = { "Zhang San",20,100 }; cout << "stay main Result printed in function:" << endl; cout << "full name:" << s.name << " Age:" << s.age << " fraction:" << s.score << endl; cout << "============================" << endl; printStudent01(s); cout << "============================" << endl; cout << "stay main Result printed in function:" << endl; cout << "full name:" << s.name << " Age:" << s.age << " fraction:" << s.score << endl; cout << "============================" << endl; printStudent02(&s); cout << "============================" << endl; cout << "stay main Result printed in function:" << endl; cout << "full name:" << s.name << " Age:" << s.age << " fraction:" << s.score << endl; cout << "============================" << endl; system("pause"); return EXIT_SUCCESS; }
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:
#define _CRT_SECURE_NO_WARNINGS 1 #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> void printStudents(); using namespace std; //const usage scenario in structure struct student { string name; int age; int score; }; //Changing the formal parameter in the function to a pointer can reduce the memory space and will not copy a new copy void printStudents(const student *s) { //s->age = 100; // After const is added, an error will be reported in case of modification to prevent misoperation cout << "full name:" << s->name << " Age:" << s->age << " fraction:" << s->score << endl; } int main() { student s = { "Zhang San",15,70 }; //Print structure information through function printStudents(&s); cout << "full name:" << s.name << " Age:" << s.age << " fraction:" << s.score << endl; system("pause"); return EXIT_SUCCESS; }