C + + Beginner
The first C + + program
Writing a C + + program is divided into four steps
- Create project
- create a file
- Write code
- Run program
Create project
Visual Studio is the tool we use to write C + + programs
create a file
Write code
#include <iostream> using namespace std; int main() { cout << "hello world" << endl; /* main A function is an entry to a program Every program must have such a function Yes and only one */ system("pause"); return 0; }
Run program
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 code
-
Multiline comment: / * description information*/
- It is usually placed above a piece of code to give an overall description of the code
The compiler ignores the contents of comments when executing code
variable
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() { //Variable creation syntax: data type variable name = variable initial value int a = 10; system("pause"); return 0; }
constant
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 above the file to represent a constant
- cons modified variable: const data type variable name constant value
- Usually, the keyword const is added before the variable definition, and the modification amount is constant and cannot be changed
Example
#include <iostream> using namespace std; // Macro constant #define day 7 int main() { cout << "There are:" << day << "day" << endl; // const modifier variable const int year = 100; return 0; }
keyword
Function: keywords are pre reserved words (identifiers) in C + +
- Do not use keywords when defining variables or constants
Identifier naming rules
Function: C + + has its own rules for naming identifiers (variables and 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 an underscore
-
Letters in identifiers are case sensitive
Suggestion: when naming an identifier, try to see the effect of knowing the meaning of the name
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
integer
Function: integer variables can represent integer data
There are several ways to represent integer types in C + +. The difference is that they occupy different memory
data type | Occupied space | Value range |
---|---|---|
Short (short integer) | 2 bytes | -215~215-1 |
Int (integer) | 4 bytes | -231~231-1 |
Long (long integer) | win is 4 bytes, Linux 32-bit is 4 bytes / 64 bit is 8 bytes | -231~231-1 |
Long long (long integer) | 8 bytes | -263~263-1 |
sizeof keyword
Function: use sizeof keyword to count the memory size occupied by data type
Syntax: sizeof (data type / variable)
Example
#include <iostream> using namespace std; int main() { int a = 5; cout << sizeof(a) << endl; cout << sizeof(int) << endl; const int year = 100; cout << sizeof(year) << endl; return 0; }
Real (floating point)
Function: used to represent decimals
There are two types of floating point types:
- 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 | 4bit | 7 is a significant number |
double | 8bit | 15 ~ 16 significant digits |
#include <iostream> using namespace std; int main() { // float float a = 5.6; cout << a << endl; // double double b = 5.6; cout << b << endl; //Scientific counting representation float d = 3e2; //For 3 * 10 ^ 2 cout << d << endl; return 0; }
character
Function: character type variable is used to display a single character
Syntax: char c = "a";
When displaying character variables, enclose the key characters in single quotation marks instead of double quotation marks
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 in the storage unit
#include <iostream> using namespace std; int main() { // character char d = 'D'; cout << d << endl; cout << (int)d << endl; // Character type corresponds to ASCII encoding /* char d = "D"; When creating character variables, use single quotes char d = 'hello'; When creating a character variable, there can only be one value in a single quotation mark */ system("pause"); return 0; }
Escape character
Function: used to represent some ASCII characters that cannot be displayed
Common escape characters are: / /, / t, / n
#include <iostream> using namespace std; int main() { // Newline \ n cout << "Hello World \n"; cout <<"Hello World" << endl; // Anti inclined rod\ cout << "\\" << endl; // Horizontal tab \ tto output data neatly cout << "Hello \t World"; system("pause"); return 0; }
String type
Function: used to represent a string of characters
Two styles
-
C style string: char variable name [] = "string value"
#include <iostream> using namespace std; int main() { char a[] = "hello world"; // Double quotation mark cout << a <<endl; cout << sizeof(a) << endl; // 12 system("pause"); return 0; }
-
C + + style string: string variable name = "string value"
#include <iostream> #Include < string > / / include this header file when using C + + style strings using namespace std; int main() { // Contains a header file string a = "hello world"; cout << a <<endl; cout << sizeof(a) << endl; // 40 system("pause"); return 0; }
Boolean data type bool
Role: Boolean data types represent true or false values
The bool type has only two values
- True: true (essentially 1)
- False: false (essentially 0)
bool type occupies a byte size
#include <iostream> #Include < string > / / include this header file when using C + + style strings using namespace std; int main() { // Create bool data type bool flag = true; // True stands for true cout << flag << endl; // In essence, 1 represents a true value and 0 represents a false value // View the memory space occupied by the bool type cout << flag << endl; system("pause"); return 0; }
Input of data
Function: used to obtain data from the keyboard
Syntax: CIN > > variable
#include <iostream> #Include < string > / / include this header file when using C + + style strings using namespace std; int main() { // integer int a = 0; cout << "Please enter an integer:"; cin >> a; cout << "Integer variable a = " << a << endl; // String type string a = "hello"; cout << "Please enter a string number:"; cin >> a; cout << "String variable a = " << a << endl; // bool type bool a = false; // If it is not empty, it is true cout << "Please enter a bool Number:"; cin >> a; cout << "bool Type variable a = " << a << endl; // character char a = '0'; cout << "Please enter a character:"; cin >> a; cout << "Character variable a = " << a << endl; // float float a = 3.14f; cout << "Please enter a floating point number:"; cin >> a; cout << "Floating point variable a = " << a << endl; system("pause"); return 0; }
operator
Function: used to execute code operations
Arithmetic operator
Function: used to process four operations
"+" plus, "-" minus, "/" divide, "*" multiply, "%" remainder, "+ +" increase, "--" decrease
#include <iostream> #Include < string > / / include this header file when using C + + style strings using namespace std; int main() { int a = 10; int b = 3; // + cout << a+b << endl; //- cout << a - b << endl; // /The result of dividing two integers is an integer, and the decimal is removed cout << a / b << endl; // * cout << a * b << endl; // %Two decimals cannot be remainder cout << a % b << endl; system("pause"); return 0; }
++And--
#include <iostream> #Include < string > / / include this header file when using C + + style strings using namespace std; int main() { // ++Increasing int a = 10; ++a; // The result of adding one to the variable is incremented in advance a++; // Post increment // Pre increment: first perform variable + 1, and then perform expression operation int b = 10; int c = ++b * 10; cout << "Front b=" << b << endl; cout << "Front c=" << c << endl; // After increment, the expression is calculated first, and then the variable + 1 int b1 = 10; int c1 = b1++ * 10; cout << "Post b=" << b1 << endl; cout << "Post c=" << c1 << endl; system("pause"); return 0; }
Assignment Operators
Function: used to assign the value of an expression to a variable
"=" equals, "+ =" plus equals, "- =" minus equals, "/ =" divide equals, "% =" remainder equals, "* =" multiply equals
#include <iostream> #Include < string > / / include this header file when using C + + style strings using namespace std; int main() { int a = 10; int b = 20; // += a += b; // Equivalent to: a = a + b cout << a << endl; // -= a -= b; // Equivalent to: a = a - b cout << a << endl; // /= a /= b; // Equivalent to: a = a / b cout << a << endl; // *= a *= b; // Equivalent to a = a * b cout << a << endl; // = a = b - a; cout << a << endl; }
Comparison operator
"= =" equal to, "< =" less than or equal to, "> =" greater than or equal to, "! =" not equal to, "<" less than, ">" greater than
Return bool type
#include <iostream> #Include < string > / / include this header file when using C + + style strings using namespace std; int main() { 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; }
Because of the priority of the operation, it should be separated by parentheses
Logical operator
Function: used to return true or false values according to the value of the expression
"!" Not, "& &" and, "|" or
#include <iostream> #Include < string > / / include this header file when using C + + style strings using namespace std; int main() { // Logical operator // ! True to false, false to true bool a = true; cout << !a<< endl; // &&If both are true, it is true; The same truth is true, and the rest is false int a1 = 10; int b = 0; cout << (a1 && b) << endl; // ||As long as one is true, it is true; The same false is false, and the rest is true cout << (a1 || b) << endl; // Comprehensive application cout << (a1 || !( a1 && ! a ) ); }
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: executes a piece of code multiple times according to whether the conditions are met
Select structure
if statement
Function: execute statements that meet conditions
Three forms of if statements
- Single line format if statement
- Multiline if statement
- Multi conditional if statement
Single line format
#include <iostream> using namespace std; int main() { // Select a single line if statement for the structure // The user enters a number int num = 1; cout << "Please enter a number:"; cin >> num; // Judge whether the number is greater than 100. If yes, the original number will be output if (num >= 100){ // Note that if statements should not be followed by semicolons, otherwise, if will not be judged cout << num; } }
Multiline if statement
#include <iostream> using namespace std; int main() { // Select a single line if statement for the structure // The user enters a number int num = 1; cout << "Please enter a number:"; cin >> num; // Judge whether the number is greater than 100, and if yes, output the original number; Otherwise, output 0 if (num >= 100) { // Note that if statements should not be followed by semicolons, otherwise, if will not be judged cout << num << endl; } else { cout << "0" << endl; } }
Multi conditional if statement
#include <iostream> using namespace std; int main() { // Select a single line if statement for the structure // The user enters a number int num = 1; cout << "Please enter a number:"; cin >> num; // Judge whether the number is greater than 600, and if yes, output the original number; Whether the number is less than 600 and greater than 0; if yes, output 100; Otherwise, output 0 if (num >= 600) { // Note that if statements should not be followed by semicolons, otherwise, if will not be judged cout << num << endl; } else if (num >= 100) { cout << "100" << endl; } else { cout << "0" << endl; } }
If (condition 1) {condition 1 satisfies the execution statement} else if (condition 2) {condition 2 satisfies and condition 1 does not satisfy, the executed statement} ·· else {does not satisfy the executed statement}
Nested if statement
In if statements, if statements can be nested to achieve more accurate condition judgment
Case: input 3 numbers to determine the maximum number
#include <iostream> using namespace std; int main() { int num = 1; int num1 = 1; int num2 = 1; cout << "Please enter three numbers:"; cin >> num; cin >> num1; cin >> num2; if ( num > num1 ) { // Judge num and num1 if ( num > num2 ) { // Judge num and num2 cout << num << "maximum" << endl; } else { cout << num2 << "maximum" << endl; } } else { if (num1 > num2) { cout << num1 << "maximum" << endl; } else { cout << num2 << "maximum" << endl; } cout << "Judgment complete" << endl; } }
ternary operator
Function: realize simple judgment through three eye operation
Syntax: expression 1? Expression 2: expression 3
#include <iostream> using namespace std; int main() { // Ternary operation // Compare a with b and assign a large value to c int a = 10; int b = 20; int c = 0; c = a > b ? a : b; // If a is larger than b, assign a to c /* if ( a > b ) { c = a; } else { c = b } */ }
In C + +, the ternary operator returns variables and can continue to assign values
switch Statements
Function: execute multi conditional branch statements
Syntax:
switch ( expression ) { case Result 1: Execute statement; break; // Not every case in the switch must correspond to break. The function of break jumps out one layer ······ default: Execute statement; break; // default judgment is not necessary }
Example
#include <iostream> using namespace std; int main() { // switch statement // Film scoring int score = 0; cout << "Please enter a score:"; cin >> score; cout << "Your score is:" << score << endl; switch (score) { case 10: cout << "It's a classic movie" << endl; break; // Exit the current branch. If there is no break, it will continue to run down default: // Execute the statement when all conditions are not met cout << "ordinary" << endl; } }
Disadvantages: when judging, it can only be integer or character type, not an interval
Advantages: clear structure and high execution efficiency
be careful
- The expression type in the switch statement can only be integer or character
- If there is no break in the case, the program will always execute downward
Cyclic structure
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
#include <iostream> using namespace std; int main() { int nu = 0; // Print numbers from 0 to 9 on the screen while ( nu < 10 ) { cout << nu << endl; nu++; } }
Figure guessing game
#include <iostream> using namespace std; // The system time header file contains #include <ctime> int main() { // Add the seed of random number and generate random number by using the current system time to prevent the random number from being the same every time srand((unsigned int)time(NULL)); // System generated random number int rand_nu = rand() % 100 + 1; // rand()%100 generates random numbers from 0 to 99 // Guess numbers int guess_nu = 0; while (guess_nu != rand_nu) { cout << "Please enter a number:"; cin >> guess_nu; // judge if (guess_nu > rand_nu) { cout << "Lost big, please guess again!!!" << endl; } else if (guess_nu < rand_nu){ cout << "Lost small, please guess again!!!" << endl; } else { cout << "Congratulations, you guessed right!!!" << endl; break; } } }
do ··· while loop statement
Function: execute loop statements when loop conditions are met
Syntax: do {loop statement} while (loop condition);
Note: the difference between do and while is that do While will execute a cycle time first to judge the cycle conditions
#include <iostream> using namespace std; int main() { // do...while statement // Output 10 numbers from 0 to 9 on the screen int num = 0; do { cout << num << endl; num++; } while (num <= 9); }
Narcissistic number
Narcissus number 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
#include <iostream> using namespace std; int main() { int nu = 100; // Narcissistic number do { int ge = 0; // Defines a number of digits int shi = 0; // Define ten digit numbers int bai = 0; // Defines the number of hundreds ge = nu % 10; shi = nu / 10 % 10; bai = nu / 100; if (ge*ge*ge + shi*shi*shi + bai*bai*bai == nu){ cout << "Number of daffodils:" << nu << endl; } nu++; } while ( nu <= 999 ); }
for loop statement
Function: execute loop statements when loop conditions are met
Syntax: for (start expression; conditional expression; end loop body) {loop statement;}
#include <iostream> using namespace std; int main() { // for loop // Print from number 0 to 9 for (int i = 0; i < 10; i++ ) { cout << i << endl; } // it's fine too int i = 0; for (;;) { if (i >= 10) { break; } cout << i << endl; i++; } }
Case: knocking on the table
Count from 1 to the number 100. If the number contains 7, or the number ten contains 7, or the number is a multiple of 7, we print and knock the table, and the rest will be printed out
#include <iostream> using namespace std; int main() { // Count from 1 to the number 100. If the number contains 7, or the number ten contains 7, or the number is a multiple of 7, we print and knock the table, and the rest will be printed out for (int i = 1; i < 100; i++) { if (i % 10 == 7 || i % 100 / 10 == 7 || i % 7 == 0) { cout << "Knock on the table" << endl; } else { cout << i << endl; } } }
Nested loop
Function: nested one layer of loop in the loop to solve some practical problems
#include <iostream> using namespace std; int main() { // Nested loop for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { cout << "*"; } cout << "" << endl; } }
Print 99 multiplication formula table
#include <iostream> using namespace std; int main() { // Nested loop for (int i = 1; i < 10; i++) { for (int j = 1; j < i+1; j++) { cout << i << "*" << j << "=" << i * j << "\t"; } cout << "" << endl; } }
Jump statement
break statement
Function: used to jump out of the selection structure or loop structure
When to use break:
- It appears in the switch statement to terminate the case and jump out of the switch
- Appears in a loop statement to jump out of the current loop statement
- Appears in a nested loop, jumping out of the nearest inner loop statement
continue Statement
Function: in a loop statement, skip the remaining unexecuted statements in this loop and continue to execute the next loop
#include <iostream> using namespace std; int main() { for (int i = 0; i <= 10; i++) { if (i % 2 == 0) { continue; } else { cout << i << "\t"; } } }
goto Statement
Function: you 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
#include <iostream> using namespace std; int main() { // goto cout << "hello" << endl; cout << "hello" << endl; cout << "hello" << endl; goto flag; cout << "hello" << endl; cout << "hello" << endl; flag: cout << "world"; }
array
summary
Array: a collection containing data elements of the same type
characteristic
- Each data element in the array is of the same data type
- Arrays consist of contiguous memory locations
One dimensional array
Definition mode
- Data type array name [array length];
- Array type array name [array length] = {value 1, value 2...};
- Array type array name [] = {value 1, value 2...}
#include <iostream> using namespace std; int main() { // 1. Data type array name [array length]; int arr[4]; arr[0] = 10; // Assignment operation // 2. Array type array name [array length] = {value 1, value 2...}; int arr1[5] = { 2, 2, 10, 20 }; // If not all data are filled in during initialization, 0 will be used to fill in the remaining data cout << arr1[0] << endl; // Value by subscript index // Use cycle value for (int i = 0; i < 5; i++) { cout << arr1[i] << endl; } }
When defining an array, it must have an initial length
The naming convention of array name is consistent with that of variable name. Do not duplicate the name of variable
Subscripts in the array are indexed from 0
Array name
Purpose of one-dimensional array name:
- You can count the length of integer groups in memory
- You can get the first address of the array in memory
#include <iostream> using namespace std; int main() { int arr[5] = { 2, 2, 10, 20 }; cout << "The space occupied by the array is" << sizeof(arr) << "\n" << "There are" << (sizeof(arr) / sizeof(arr[0])) << "Elements" << endl; cout << "The first address of the array is" << (int)arr << "\n The space occupied by each element is" << sizeof(arr[0]) << "\n The address of the first element in the array is" << (int)&arr[0] << endl; }
The array name is a constant and cannot be assigned
case
Find the largest element in the array
#include <iostream> using namespace std; int main() { //Find the largest number in the array int max_nu = 0; // max_nu is used to store the maximum value int arr[5] = { 300, 350, 200, 400, 250 }; for (int i = 0; i < ((sizeof(arr) / sizeof(arr[0]))-1); i++) { max_nu = arr[i] > arr[i + 1] ? arr[i] : arr[i + 1]; } cout << max_nu << endl; }
Group element inversion
Swap the beginning and end of the elements in the array
#include <iostream> using namespace std; int main() { // The contents of the array are reversed int arr1[5] = { 300, 350, 200, 400, 250 }; int end = sizeof(arr1) / sizeof(arr1[0]); // End subscript int start = 0; // Starting subscript while (start < end) { int temp = arr1[start]; arr1[start] = arr1[end]; arr1[end] = temp; start++; end--; } for (int i = 0; i < (sizeof(arr1) / sizeof(arr1[0])); i++) { cout << arr1[i] << endl; } }
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 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
Sort int arr = {4, 2, 8, 0, 5, 7, 1, 3, 9};
#include <iostream> using namespace std; int main() { // Bubble sort is used to realize ascending sort int arr[ ] = {4, 2, 8, 0, 5, 7, 1, 3, 9}; cout << "Before sorting:"; for (int i = 0; i < (sizeof(arr) / sizeof(arr[0])); i++) { cout << arr[i] << " "; } for (int i = 0; i < (sizeof(arr) / sizeof(arr[0]) - 1); i++) { // The number of sorting times is the number of elements minus one for (int j = 0; j < (sizeof(arr) / sizeof(arr[0]) - 1 - i); j++) { // Inner layer cycle comparison times number of elements - sorting times - 1 if (arr[j] > arr[j + 1]) { // If the previous number is larger than the second number, exchange the order int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } cout << "After sorting:"; for (int i = 0; i < (sizeof(arr) / sizeof(arr[0])); i++) { cout << arr[i] << " "; } }
Two dimensional array
A two-dimensional array is to add one more dimension to the array
Definition mode
- 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};
The second method is more intuitive and improves the readability of the code
#include <iostream> using namespace std; int main() { // 1. ` data type array name [number of rows] [number of columns]` int arr1[2][3]; // 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} }; // Secondary cycle, number of rows printed in outer cycle, number of columns printed in inner cycle for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr2[i][j] << " "; }; cout << endl; }; // 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 }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr2[i][j] << " "; }; cout << endl; }; // 4. ` data type array name [] [number of columns] = {data 1, data 2, data 3, data 4}` int arr3[2][3] = { 1, 2, 3, 4, 5, 6 }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << arr2[i][j] << " "; }; cout << endl; }; }
Array name
- View the memory space occupied by the two-dimensional array
- Get the first address of two-dimensional array
#include <iostream> using namespace std; int main() { int arr2[2][3] = { {1, 2 ,3}, {4, 5, 6} }; // View occupied memory cout << "The memory space occupied by the two-dimensional array is:" << sizeof(arr2) << endl; cout << "The memory occupied by the first row of the two-dimensional array is:" << sizeof(arr2[0]) << endl; cout << "The memory occupied by the first element of the two-dimensional array is:" << sizeof(arr2[0][0]) << endl; cout << "The number of elements in one row of the binary array is:" << sizeof(arr2[0]) / sizeof(arr2[0][0]) << endl << "The number of rows of the two-dimensional array is:" << sizeof(arr2) / sizeof(arr2[0]) << endl; // View the first address of a two-dimensional array cout << "The first address of the two-dimensional array is:" << (int)arr2 << endl; cout << "The first address of the first row of the two-dimensional array is:" << (int)arr2[0] << endl; cout << "The first address of the first element of the two-dimensional array is:" << (int)&arr2[0][0]; }
case
There is an array int arr [3] [3] = {100, 100, 100}, {90, 50, 100}, {60, 70, 80}
Calculates the sum of each row of the array
#include <iostream> using namespace std; int main() { // Sums the numbers in each row of the array int arr[3][3] = { {100, 100, 100}, {90, 50, 100}, {60, 70, 80} }; // Loop twice to get each value in the array for (int i = 0; i < (sizeof(arr) / sizeof(arr[0])); i++) { int sum = 0; for (int j = 0; j < (sizeof(arr[0]) / sizeof(arr[0][0])); j++) { sum += arr[i][j]; }; cout << "The first" << (i + 1) << "The sum of lines is:" << sum <<endl; }; }
function
summary
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
Definition of function
There are generally five steps to define a function
- return type
- Function name
- Parameter series
- Function body statement
- return expression
grammar
Return value type function name (parameter list) { Function body statement return expression }
Implement an addition function, pass in two integer values, calculate the result of data addition, and return
#include <iostream> using namespace std; // Function body int add(int num1, int num2) { return num1 + num2; }
Function call
Function: use defined functions
Syntax: function name (parameter)
#include <iostream> using namespace std; // Function body int add(int num1, int num2) { // The parameter in the function definition has no actual value, which is called formal parameter (formal parameter) return num1 + num2; } int main() { cout << add(1, 2) << endl; // The add function is called in the main function, where 1 and 2 are arguments (actual parameters), and the positions should be one to one. }
pass by value
- 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 changes, the argument will not be affected
#include <iostream> using namespace std; /* pass by value Define a function to exchange two numbers If the function does not need a return value declaration, you can write void */ void swap(int num1, int num2) { cout << "Number before exchange" << endl << "num1:" << num1 << "\tnum2:" << num2; int temp = num1; num1 = num2; num2 = temp; cout << "\n Number after exchange" << endl << "num1:" << num1 << "\tnum2:" << num2; } int main() { int num1 = 10; int num2 = 20; cout << "Number before not called" << endl << "num1:" << num1 << "\tnum2:" << num2 << endl; // When we do value transfer, the formal parameters of the function change and will not affect the formal parameters swap(num2, num1); }
Common styles for functions
There are four common function styles
- There is no return
- No reference, no return
- Return without participation
- Participation and return
#include <iostream> #include <string> using namespace std; // 1. No return with reference void test01(string str) { cout << str << endl; } // 2. No reference and no return void test02() { cout << "this is test02" << endl; } // 3. Return without participation int test03() { return 100; } // 4. Participation and return int test04(int num1, int num2) { return num1 * num2; } int main() { // 1. There is no callback with parameters test01("hello world"); // 2. No parameter and no return call test02(); // 3. There is no callback with parameters cout << test03() << endl; // 4. Call with parameters and return cout << test04(2, 3) << endl; }
Declaration of function
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
#include <iostream> #include <string> using namespace std; // Function declaration: tell the compiler about the existence of the function in advance // Function declaration -- > without this declaration, the function will not be called int max(int num1, int num2); int main() { int a = 10; int b = 20; cout << max(a, b) << endl; } // Comparison function to compare two integer numbers and return a larger number int max(int num1, int num2) { return num1 > num2 ? num1 : num2; }
Function sub file writing
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 new source file
/* In the new source file */ #include "header. h" // Comparison function to compare two integer numbers and return a larger number. Function definition int max(int num1, int num2) { return num1 > num2 ? num1 : num2; } /* In the new header file (named header. h) */ #include <iostream> using namespace std; int max(int num1, int num2); /* In the run file */ #include "header. h" int main() { int a = 10; int b = 20; cout << max(a, b) << endl; }
Pointer
Basic concepts
Function: memory can be accessed indirectly through pointer
- The memory number starts from 0 and is generally represented by hexadecimal digits
- Pointer variables can be used to save addresses
Definition and use
Pointer variable definition syntax: data type * variable name
#include <iostream> using namespace std; int main() { // Define a pointer int a = 10; // Pointer definition syntax: data type * variable name int * p; // Let the pointer record the address of variable a p = &a; // &Addressing symbol cout << "a Your address is:" << &a << endl; cout << "Pointer p The value of is:" << p << endl; // Use pointer // You can find the memory pointed to by the pointer by dereferencing // Add * before the pointer to dereference and find the data in memory pointed to by the pointer *p = 100; cout << "a be equal to:" << a << "\n*p be equal to" << *p << endl; }
Memory space occupied by pointer
#include <iostream> using namespace std; // In the 32-bit operating system, the pointer occupies 4 bits, regardless of the data type // In 64 bit operating system, the pointer occupies 8bit int main() { int a = 10; int * p = &a; cout << "int *:" << sizeof(int*) << endl; cout << "char *:" << sizeof(char*) << endl; cout << "p:" << sizeof(p) << endl; }
Null and implicit pointers
Null pointer: pointer variable points to the space numbered 0 in memory
Purpose: initialize pointer variables
Note: the memory pointed to by the null pointer cannot be accessed
Wild pointer: pointer variable points to illegal memory space
#include <iostream> using namespace std; int main() { // Null pointer // Null pointers are used to initialize pointer objects int* p1 = NULL; // Null pointer cannot be accessed, it is occupied by the system // Field pointer // Wild pointers must be avoided in the program int * p = (int *)0x1100; }
const modifier pointer
const modifier pointer has three cases
- Const decorated pointer -- constant pointer const int * P = & A
- The pointer can be modified, but the value pointed to cannot be modified
- Const modifier constant -- pointer constant int * const P = & A
- The point of the pointer cannot be changed, and the value of the pointer can be changed
- const modifies both pointers and constants
#include <iostream> using namespace std; int main() { int a = 10; int b = 10; // const pointer const int* p = &a; // The value pointed to by the pointer cannot be changed, and the position pointed to can be modified // * p = 20; error p = &b; // correct // constant pointer int* const p1 = &a; // The value pointed to by the pointer can be modified, but the position pointed to cannot be modified *p1 = 20; // correct // p = &b; error }
Memory method: see whether the pointer or constant is immediately followed on the right side of const. Whether the pointer is a constant pointer or a constant is a constant pointer
Pointers and arrays
Function: use the pointer to access the elements in the array
#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 the pointer to access the first element:" << *p << endl; p++; // Offset the pointer by 4bit cout << "Access the second element with a pointer:" << *p << endl; // Use pointers to access arrays, or through p1 [index values] int* p1 = arr; for (int i = 0; i < (sizeof(arr) / sizeof(arr[0])); i++) { cout << *p1++ << " "; } for (int i = 0; i < (sizeof(arr) / sizeof(arr[0])); i++) { cout << p1[i] << " "; } }
Pointers and functions
Function: use the pointer as the parameter of the function to modify the value of the argument
#include <iostream> using namespace std; void swap(int* p1, int* p2) { int temp = *p1; *p1 = *p2; *p2 = temp; } int main() { // Functions and pointers // Address delivery int a = 10; int b = 30; cout << "a:" << a << " b:" << b << endl; swap(&a, &b); cout << "after a:" << a << " b:" << b << endl; // The memory in the address has changed }
Pointer, array, function
Encapsulates a function that uses bubble sorting to sort integer arrays in ascending order
For example, array: int arr [] = {4, 3, 6, 9, 1, 2, 10, 8, 7, 5};
#include <iostream> using namespace std; // Bubble sort function void sort(int * arr, int length) { // The parameter is the memory address of the array for (int i = 0; i < length - 1; i++) { for (int j = 0; j < length - 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 print(int* arr, int length) { for (int i = 0; i < length; i++) { cout << arr[i] << " "; } } int main() { int arr[] = { 4, 3, 6, 9, 1, 2, 10, 8, 7, 5 }; int length = sizeof(arr) / sizeof(arr[0]); sort(arr, length); print(arr, length); }
structural morphology
Basic concepts
Structures are user-defined data types, allowing users to store different data types
Definition and use
Syntax: struct struct name {struct member list}
There are three ways to create variables through structures
- struct structure name variable name
- struct structure name variable name = {member value 1, member value 2,...}
- Defining a structure is a way to create variables
#include <iostream> #include <string> using namespace std; // Create data types of students: including (name, age, score) // User defined data type, a data type composed of a collection of types struct Student { // Member list string name; // name int age; // age int score; // score }s3; // Creating structure variables int main() { // Create specific students by student type // struct Student s1 struct Student s1; // The struct keyword can be omitted, but cannot be omitted when defining // Assign a value to the s1 attribute through Accessing properties in structure variables s1.name = "Zhang San"; s1.age = 18; s1.score = 90; cout << "name:" << s1.name << " age:" << s1.age << " score:" << s1.score << endl; // struct Stufent s2 = { ... } struct Student s2 = { "Li Si", 18, 80 }; cout << "name:" << s2.name << " age:" << s2.age << " score:" << s2.score << endl; // In the definition, you create structure variables by the way s3.name = "Wang Wu"; s3.age = 18; s3.score = 85; cout << "name:" << s3.name << " age:" << s3.age << " score:" << s3.score << endl; }
Structure array
Function: put the custom structure into the array for easy maintenance
Syntax: struct structure name array name [number of elements] = {{}, {} {} }
#include <iostream> #include <string> using namespace std; // Structure array // Define structure array struct Student { string name; int age; int score; }; int main() { // Create structure array struct Student stuArray[3] = { // Assign a value to the structure array {"zhangsan", 18, 100}, {"lisi", 19, 99}, {"wangwu", 20, 85} }; // Modify value stuArray[2].name = "lihua"; stuArray[2].age = 19; stuArray[2].score = 89; // Traversal array for (int i = 0; i < 3; i++) { cout << "name:" << stuArray[i].name << " age:" << stuArray[i].age << " score:" << stuArray[i].score << endl; }; }
Structure pointer
Role: access members in a structure through a pointer
- Using the operator - > you can access structure properties through the structure pointer
#include <iostream> #include <string> using namespace std; // Structure pointer // Define student structure struct Student { string name; int age; int score; }; int main() { // Create student structure variable struct Student s = { "zhangsan", 18, 99 }; // Pointer to structure variable struct Student* p = &s; // Accessing data in a structure variable through a pointer cout << "name:" << p->name << " age:" << p->age << " score:" << p->score << endl; }
Structure nested structure
Action: a member in a structure can be another structure
For example, each teacher tutors a student, a teacher's structure, and records a student's structure
#include <iostream> #include <string> using namespace std; // Structure pointer // Define student structure struct Student { string name; int age; int score; }; // Define teacher structure struct Treacher { int id; string name; int age; struct Student stu; // Tutoring students }; int main() { // Structure nested structure // Create teacher object struct Treacher t; t.id = 100000; t.name = "Lao Wang"; t.age = 58; t.stu.name = "Xiao Wang"; t.stu.age = 16; t.stu.score = 60; cout << "tea_name:" << t.name << " tea_id:" << t.id << " tea_age:" << t.age << "\nstu_name:" << t.stu.name << " stu_age:" << t.stu.age << " stu_score:" << t.stu.score << endl; }
Structure as function parameter
Function: pass structure as parameter to function
There are two ways of transmission
- pass by value
- Address delivery
#include <iostream> #include <string> using namespace std; // Define student structure struct Student { string name; int age; int score; }; // Function for printing student information, value transfer void printStuInfo(Student stu) { stu.age = 100; cout << "name:" << stu.name << " age:" << stu.age << " score:" << stu.score << endl; }; // Address passing: the modification of formal parameters will cause the change of arguments void printStudentInfo2(Student* p) { cout << "name:" << p->name << " age:" << p->age << " score:" << p->score << endl; }; int main() { // Parameters of structure function // Pass the student into a parameter and print all the information on the student // Create structure variable struct Student stu; stu.name = "zhangsan"; stu.age = 20; stu.score = 85; cout << "pass by value" << endl; printStuInfo(stu); cout << "Address delivery" << endl; printStudentInfo2(&stu); }
const usage scenario in structure
Function: use const to prevent five operations
#include <iostream> #include <string> using namespace std; // Define student structure struct Student { string name; int age; int score; }; // Address transfer, saving space void printStudentInfo2(const Student* p) { // After const is added, an error will be reported once there is a modified operation, which can prevent our misoperation cout << "name:" << p->name << " age:" << p->age << " score:" << p->score << endl; }; int main() { // const usage scenario // Create structure variable struct Student stu; stu.name = "zhangsan"; stu.age = 20; stu.score = 85; printStudentInfo2(&stu); }
Structural case
Case 1
#include <iostream> #include <string> #include <ctime> using namespace std; // Define student structure struct Student { string name; int score; }; // Teacher structure definition struct Teacher { string name; Student stuArray[5]; }; // A function that assigns values to teachers and students void allocateSpace(Teacher tArray[], int len) { // Assign a value to the teacher string name = "abcde"; for (int i = 0; i < len; i++) { tArray[i].name = "Teacher_"; tArray[i].name += name[i]; // Value of string // Assign a value to each student for (int j = 0; j < 5; j++) { tArray[i].stuArray[j].name = "Student_"; tArray[i].stuArray[j].name += name[j]; int random = rand() % 61 + 40; // 40-99 tArray[i].stuArray[j].score = random; } }; }; // Print student and teacher information void printInfo(Teacher* tArray, int len) { for (int i = 0; i < len; i++) { cout << "teacher_name:" << tArray[i].name << endl; for (int j = 0; j < 5; j++) { cout << "stu_name:" << tArray[i].stuArray[j].name << " stu_score:" << tArray[i].stuArray[j].score << endl; }; cout << "--------------------------------------------------------------------------------" << endl; }; } int main() { // Random number seed srand((unsigned int)time(NULL)); // Three teachers array Teacher tArray[3]; // Assign a value to the teacher's information through the function, and assign a value to the student information brought by the teacher int len = sizeof(tArray) / sizeof(tArray[0]); allocateSpace(tArray, len); printInfo(tArray, len); }
Case 2
There are five students who sort the students in the array in ascending order according to their age by bubble sorting method, and finally print the sorted results
{ {"stu1", 23}, {"stu2", 22}, {"stu3", 20}, {"stu4", 21}, {"stu5", 19} }
#include <iostream> #include <string> using namespace std; // Define student structure struct Student { string name; int age; }; // sort void sort(Student* stuArray, int len) { for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - i - 1; j++) { if (stuArray[j].age > stuArray[j + 1].age) { struct Student temp = stuArray[j]; stuArray[j] = stuArray[j + 1]; stuArray[j + 1] = temp; }; }; }; }; // output void printInfo(const Student * stuArray, int len) { for (int i = 0; i < len; i++) { cout << "name:" << stuArray[i].name << " age:" << stuArray[i].age << endl; }; }; int main() { // Create an array to hold five students Student stuArray[] = { {"stu1", 23}, {"stu2", 22}, {"stu3", 20}, {"stu4", 21}, {"stu5", 19} }; int len = sizeof(stuArray) / sizeof(stuArray[0]); sort(stuArray, len); printInfo(stuArray, len); };