Introduction to C + + Zero foundation -- August 19, 2021

Posted by arjay_comsci on Fri, 24 Dec 2021 11:38:18 +0100

Introduction to C + + Basics

1. Introduction to C + +

1.1 first C + + program

Writing a C + + program is divided into four steps

  • Create project
  • create a file
  • Write code
  • Run program

1.1. 1 create project

Visual Studio is the main tool we use to write C + + programs. Let's open it first

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-vpwkfjour-1629339524052) (assets / 1541383178746. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-02qg1Dn3-1629339524070)(assets/1541384366413.png)]

1.1. 2 create file

Right click the source file and select Add - > new item

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-CbKlJHAe-1629339524071)(assets/1541383817248.png)]

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

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-DxyPpw61-1629339524073)(assets/1541384140042.png)]

1.1. 3 write code

#include<iostream>
using namespace std;

int main() {

	cout << "Hello world" << endl;

	system("pause");

	return 0;
}

1.1. 4 operation procedure

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-dcE11G9C-1629339524073)(assets/1541384818688.png)]

1.2 notes

Function: add some instructions and explanations in the code to facilitate yourself or other programmers to read the code

Two formats

  1. Single line comment: / / description
    • It is usually placed above a line of code or at the end of a statement to explain the line of code
  2. Multiline comment: / * description information*/
    • It is usually placed above a piece of code to give an overall description of the code

Tip: the compiler ignores the contents of comments when compiling code

1.3 variables

Function: name a specified memory space to facilitate the operation of this memory

Syntax: data type variable name = initial value;

Example:

#include<iostream>
using namespace std;

int main() {

	//Definition of variables
	//Syntax: data type variable name = initial value

	int a = 10;

	cout << "a = " << a << endl;
	
	system("pause");

	return 0;
}

Note: when creating a variable, C + + must give the variable an initial value, otherwise an error will be reported

1.4 constants

Function: used to record unchangeable data in the program

There are two ways to define constants in C + +

  1. #Define macro constant: #define constant name constant value

    • It is usually defined above the file to represent a constant
  2. Const modified variable const data type constant name = constant value

    • Usually, the keyword const is added before the variable definition to modify the variable as a constant and cannot be modified

Example:

//1. Macro constant
#define day 7

int main() {

	cout << "In a week " << day << " day" << endl;
	//day = 8;  // An error is reported. Macro constants cannot be modified

	//2. const modifier variable
	const int month = 12;
	cout << "A total of in a year " << month << " Months" << endl;
	//month = 24; // An error is reported. Constants cannot be modified
	
	
	system("pause");

	return 0;
}

1.5 keywords

**Function: * * keyword is a word (identifier) reserved in C + +

  • When defining variables or constants, do not use keywords

C + + keywords are as follows:

asmdoifreturntypedef
autodoubleinlineshorttypeid
booldynamic_castintsignedtypename
breakelselongsizeofunion
caseenummutablestaticunsigned
catchexplicitnamespacestatic_castusing
charexportnewstructvirtual
classexternoperatorswitchvoid
constfalseprivatetemplatevolatile
const_castfloatprotectedthiswchar_t
continueforpublicthrowwhile
defaultfriendregistertrue
deletegotoreinterpret_casttry

Tip: when naming variables or constants, do not use C + + keywords, otherwise ambiguity will occur.

1.6 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 underscore
  • Letters in identifiers are case sensitive

Suggestion: when naming the identifier, try to achieve the effect of seeing the name and knowing the meaning, so as to facilitate reading by yourself and others

2 data type

C + + stipulates that when creating a variable or constant, the corresponding data type must be specified, otherwise memory cannot be allocated to the variable

2.1 integer

Function: integer variables represent integer data

There are several ways to represent integer types in C + +. The difference is that the memory space is different:

data typeOccupied spaceValue range
Short (short integer)2 bytes(-2^15 ~ 2^15-1)
Int (integer)4 bytes(-2^31 ~ 2^31-1)
Long (long shaping)4 bytes for Windows, 4 bytes (32 bits) for Linux, 8 bytes (64 bits)(-2^31 ~ 2^31-1)
Long long8 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:

int main() {

	cout << "short Memory space occupied by type: " << sizeof(short) << endl;

	cout << "int Memory space occupied by type: " << sizeof(int) << endl;

	cout << "long Memory space occupied by type: " << sizeof(long) << endl;

	cout << "long long Memory space occupied by type: " << sizeof(long long) << endl;

	system("pause");

	return 0;
}

Integer conclusion: short < int < = long < = long long

2.3 real (floating point)

Function: used to represent decimals

There are two types of floating point variables:

  1. Single precision float
  2. Double precision double

The difference between the two is that the range of significant numbers represented is different.

data typeOccupied spaceSignificant digit range
float4 bytes7 significant digits
double8 bytes15 ~ 16 significant digits

Example:

int main() {

	float f1 = 3.14f;
	double d1 = 3.14;

	cout << f1 << endl;
	cout << d1<< endl;

	cout << "float  sizeof = " << sizeof(f1) << endl;
	cout << "double sizeof = " << sizeof(d1) << endl;

	//Scientific counting method
	float f2 = 3e2; // 3 * 10 ^ 2 
	cout << "f2 = " << f2 << endl;

	float f3 = 3e-2;  // 3 * 0.1 ^ 2
	cout << "f3 = " << f3 << endl;

	system("pause");

	return 0;
}

2.4 character type

**Function: * * character type variable is used to display a single character

Syntax: char ch = 'a';

Note 1: when displaying character variables, use single quotation marks to enclose the characters, not double quotation marks

Note 2: there can only be one character in a single quotation mark, not a string

  • Character variables in C and C + + only occupy 1 byte.
  • Character type variables do not store the character itself in memory, but put the corresponding ASCII code into the storage unit

Example:

int main() {
	
	char ch = 'a';
	cout << ch << endl;
	cout << sizeof(char) << endl;

	//ch = "abcde"; // Error, double quotation marks are not allowed
	//ch = 'abcde'; // Error, only one character can be referenced in a single quotation mark

	cout << (int)ch << endl;  //View the ASCII code corresponding to character a
	ch = 97; //You can assign values to character variables directly in ASCII
	cout << ch << endl;

	system("pause");

	return 0;
}

ASCII table:

ASCII valueControl characterASCII valuecharacterASCII valuecharacterASCII valuecharacter
0NUT32(space)64@96,
1SOH33!65A97a
2STX34"66B98b
3ETX35#67C99c
4EOT36$68D100d
5ENQ37%69E101e
6ACK38&70F102f
7BEL39,71G103g
8BS40(72H104h
9HT41)73I105i
10LF42*74J106j
11VT43+75K107k
12FF44,76L108l
13CR45-77M109m
14SO46.78N110n
15SI47/79O111o
16DLE48080P112p
17DCI49181Q113q
18DC250282R114r
19DC351383S115s
20DC452484T116t
21NAK53585U117u
22SYN54686V118v
23TB55787W119w
24CAN56888X120x
25EM57989Y121y
26SUB58:90Z122z
27ESC59;91[123{
28FS60<92/124|
29GS61=93]125}
30RS62>94^126`
31US63?95_127DEL

ASCII code is roughly composed of the following two parts:

  • ASCII non printing control characters: the numbers 0-31 on the ASCII table are assigned to the control characters, which are used to control some peripheral devices such as printers.
  • ASCII printed characters: the numbers 32-126 are assigned to characters that can be found on the keyboard and appear when viewing or printing a document.

2.5 escape characters

**Function: * * used to indicate some ASCII characters that cannot be displayed

At this stage, we often use escape characters: \ n \ \ t

Escape charactermeaningASCII value (decimal)
\aalert007
\bBackspace (BS) to move the current position to the previous column008
\fPage feed (FF) moves the current position to the beginning of the next page012
\nLine feed (LF) moves the current position to the beginning of the next line010
\rPress enter (CR) to move the current position to the beginning of the line013
\tHorizontal tabulation (HT) (skip to next TAB position)009
\vVertical tabulation (VT)011
\\Represents a backslash character ''092
'Represents a single quotation mark (apostrophe) character039
"Represents a double quote character034
?Represents a question mark063
\0Number 0000
\dddOctal escape character, d range 0 ~ 73-bit octal
\xhhHexadecimal escape character, h range 09, af, A~F3-bit hex

Example:

int main() {
	
	
	cout << "\\" << endl;
	cout << "\tHello" << endl;
	cout << "\n" << endl;

	system("pause");

	return 0;
}

2.6 string type

Function: used to represent a string of characters

Two styles

  1. C style string: char variable name [] = "string value"

    Example:

    int main() {
    
    	char str1[] = "hello world";
    	cout << str1 << endl;
        
    	system("pause");
    
    	return 0;
    }
    

Note: C-style strings should be enclosed in double quotes

  1. C + + style string: string variable name = "string value"

    Example:

    int main() {
    
    	string str = "hello world";
    	cout << str << endl;
    	
    	system("pause");
    
    	return 0;
    }
    

Note: for C + + style strings, you need to add header files = = #include < string >==

2.7 boolean type bool

**Function: * * Boolean data type represents true or false value

The bool type has only two values:

  • True - true (essentially 1)
  • False - false (essentially 0)

bool type takes up 1 byte

Example:

int main() {

	bool flag = true;
	cout << flag << endl; // 1

	flag = false;
	cout << flag << endl; // 0

	cout << "size of bool = " << sizeof(bool) << endl; //1
	
	system("pause");

	return 0;
}

2.8 data input

Function: used to obtain data from the keyboard

**Keywords: * * cin

Syntax: CIN > > variable

Example:

int main(){

	//Integer input
	int a = 0;
	cout << "Please enter an integer variable:" << endl;
	cin >> a;
	cout << a << endl;

	//Floating point input
	double d = 0;
	cout << "Please enter a floating point variable:" << endl;
	cin >> d;
	cout << d << endl;

	//Character input
	char ch = 0;
	cout << "Please enter a character variable:" << endl;
	cin >> ch;
	cout << ch << endl;

	//String input
	string str;
	cout << "Please enter a string variable:" << endl;
	cin >> str;
	cout << str << endl;

	//Boolean type input
	bool flag = true;
	cout << "Please enter a boolean variable:" << endl;
	cin >> flag;
	cout << flag << endl;
	system("pause");
	return EXIT_SUCCESS;
}

3 operator

**Function: * * used to execute code operations

In this chapter, we mainly explain the following types of operators:

Operator typeeffect
Arithmetic operatorUsed to process four operations
Assignment Operators Used to assign the value of an expression to a variable
Comparison operatorUsed to compare expressions and return a true or false value
Logical operatorUsed 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:

operatortermExampleresult
+Plus sign+33
-minus sign-3-3
+plus10 + 515
-reduce10 - 55
*ride10 * 550
/except10 / 52
%Mold taking (residual)10 % 31
++Pre incrementa=2; b=++a;a=3; b=3;
++Post incrementa=2; b=a++;a=3; b=2;
Pre decrementa=2; b=–a;a=1; b=1;
Post decrementa=2; b=a–;a=1; b=2;

Example 1:

//add , subtract , multiply and divide
int main() {

	int a1 = 10;
	int b1 = 3;

	cout << a1 + b1 << endl;
	cout << a1 - b1 << endl;
	cout << a1 * b1 << endl;
	cout << a1 / b1 << endl;  //The result of dividing two integers is still an integer

	int a2 = 10;
	int b2 = 20;
	cout << a2 / b2 << endl; 

	int a3 = 10;
	int b3 = 0;
	//cout << a3 / b3 << endl; // An error is reported. The divisor cannot be 0


	//Two decimals can be divided
	double d1 = 0.5;
	double d2 = 0.25;
	cout << d1 / d2 << endl;

	system("pause");

	return 0;
}

Summary: divisor cannot be 0 in division operation

Example 2:

//Take mold
int main() {

	int a1 = 10;
	int b1 = 3;

	cout << 10 % 3 << endl;

	int a2 = 10;
	int b2 = 20;

	cout << a2 % b2 << endl;

	int a3 = 10;
	int b3 = 0;

	//cout << a3 % b3 << endl; // In modulo operation, the divisor cannot be 0

	//Two decimals cannot be modulo
	double d1 = 3.14;
	double d2 = 1.1;

	//cout << d1 % d2 << endl;

	system("pause");

	return 0;
}

Summary: only integer variables can perform modulo operations

Example 3:

//Increasing
int main() {

	//Post increment
	int a = 10;
	a++; //Equivalent to a = a + 1
	cout << a << endl; // 11

	//Pre increment
	int b = 10;
	++b;
	cout << b << endl; // 11

	//difference
	//Pre incrementing first + + the variable, and then calculate the expression
	int a2 = 10;
	int b2 = ++a2 * 10;
	cout << b2 << endl;

	//Post increment evaluates the expression first, and then the variable is incremented++
	int a3 = 10;
	int b3 = a3++ * 10;
	cout << b3 << endl;

	system("pause");

	return 0;
}

Conclusion: the pre increment is performed on the variable with + +, and then the expression is calculated. The post increment is the opposite

3.2 assignment operator

**Function: * * used to assign the value of an expression to a variable

The assignment operator includes the following symbols:

operatortermExampleresult
=assignmenta=2; b=3;a=2; b=3;
+=Plus equalsa=0; a+=2;a=2;
-=Minus equalsa=5; a-=3;a=2;
*=Multiply equala=2; a*=2;a=4;
/=Division equalsa=4; a/=2;a=2;
%=Modulo equala=3; a%2;a=1;

Example:

int main() {

	//Assignment Operators 

	// =
	int a = 10;
	a = 100;
	cout << "a = " << a << endl;

	// +=
	a = 10;
	a += 2; // a = a + 2;
	cout << "a = " << a << endl;

	// -=
	a = 10;
	a -= 2; // a = a - 2
	cout << "a = " << a << endl;

	// *=
	a = 10;
	a *= 2; // a = a * 2
	cout << "a = " << a << endl;

	// /=
	a = 10;
	a /= 2;  // a = a / 2;
	cout << "a = " << a << endl;

	// %=
	a = 10;
	a %= 2;  // a = a % 2;
	cout << "a = " << a << endl;

	system("pause");

	return 0;
}

3.3 comparison operators

**Function: * * used to compare expressions and return a true or false value

Comparison operators have the following symbols:

operatortermExampleresult
==Equal to4 == 30
!=Not equal to4 != 31
<less than4 < 30
>greater than4 > 31
<=Less than or equal to4 <= 30
>=Greater than or equal to4 >= 11

Example:

int main() {

	int a = 10;
	int b = 20;

	cout << (a == b) << endl; // 0 

	cout << (a != b) << endl; // 1

	cout << (a > b) << endl; // 0

	cout << (a < b) << endl; // 1

	cout << (a >= b) << endl; // 0

	cout << (a <= b) << endl; // 1
	
	system("pause");

	return 0;
}

Note: in the comparison operation of C and C + + languages, "true" is represented by the number "1", and "false" is represented by the number "0".

3.4 logical operators

**Function: * * used to return true or false values according to the value of the expression

Logical operators have the following symbols:

operatortermExampleresult
!wrong!aIf a is false, then! A is true; If a is true, then! A is false.
&&Anda && bIf both a and b are true, the result is true, otherwise it is false.
||ora || bIf one of a and b is true, the result is true. If both are false, the result is false.

**Example 1: * * logical non

//Logical operator --- not
int main() {

	int a = 10;

	cout << !a << endl; // 0

	cout << !!a << endl; // 1

	system("pause");

	return 0;
}

Summary: true becomes false, false becomes true

**Example 2: * * logic and

//Logical operators --- and
int main() {

	int a = 10;
	int b = 10;

	cout << (a && b) << endl;// 1

	a = 10;
	b = 0;

	cout << (a && b) << endl;// 0 

	a = 0;
	b = 0;

	cout << (a && b) << endl;// 0

	system("pause");

	return 0;
}

Summary: logic and operator summary: the same as true is true, and the rest is false

**Example 3: * * logical or

//Logical operator --- or
int main() {

	int a = 10;
	int b = 10;

	cout << (a || b) << endl;// 1

	a = 10;
	b = 0;

	cout << (a || b) << endl;// 1 

	a = 0;
	b = 0;

	cout << (a || b) << endl;// 0

	system("pause");

	return 0;
}

Logical or operator summary: 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: executes a piece of code multiple times according to whether the conditions are met

4.1 selection of structure

4.1.1 if statement

**Function: * * execute qualified statements

Three forms of if statements

  • Single line format if statement

  • Multiline if statement

  • Multi conditional if statement

  1. Single line format if statement: if (condition) {statement executed when the condition is met}

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-f73jaCHu-1629339524075)(assets/clip_image002.png)]

    Example:

    int main() {
    
    	//Select structure - single line if statement
    	//Enter a score. If the score is greater than 600, it will be regarded as entering a university and printed on the screen
    
    	int score = 0;
    	cout << "Please enter a score:" << endl;
    	cin >> score;
    
    	cout << "The score you entered is: " << score << endl;
    
    	//if statement
    	//Note: do not add a semicolon after the if judgment statement
    	if (score > 600)
    	{
    		cout << "I was admitted to a university!!!" << endl;
    	}
    
    	system("pause");
    
    	return 0;
    }
    

Note: do not add a semicolon after the if conditional expression

  1. Multi line format if statement: if (condition) {statement executed when the condition meets} else {statement executed when the condition does not meet};

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-NfQIvLlb-1629339524075)(assets/clip_image002-1541662519170.png)]

Example:

int main() {

	int score = 0;

	cout << "Please enter the test score:" << endl;

	cin >> score;

	if (score > 600)
	{
		cout << "I was admitted to a university" << endl;
	}
	else
	{
		cout << "I failed to enter a university" << endl;
	}

	system("pause");

	return 0;
}
  1. Multi conditional if statement: if (condition 1) {condition 1 satisfies the executed statement} else if (condition 2) {condition 2 satisfies the executed statement} Else {none of them satisfy the executed statement}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-eVBSN8hX-1629339524076)(assets/clip_image002-1541662566808.png)]

Example:

	int main() {

	int score = 0;

	cout << "Please enter the test score:" << endl;

	cin >> score;

	if (score > 600)
	{
		cout << "I was admitted to a university" << endl;
	}
	else if (score > 500)
	{
		cout << "I was admitted to two universities" << endl;
	}
	else if (score > 400)
	{
		cout << "I was admitted to three universities" << endl;
	}
	else
	{
		cout << "I didn't go to college" << endl;
	}

	system("pause");

	return 0;
}

Nested if statements: if statements can be nested in if statements to achieve more accurate condition judgment

Case requirements:

  • Prompt the user to enter a college entrance examination score, and make the following judgment according to the score
  • If the score is greater than 600, it will be regarded as one, two and three, and the rest will be regarded as not having been admitted to undergraduate;
  • In a book, if the score is more than 700, you will be admitted to Peking University, more than 650, Tsinghua University and more than 600 to the National People's Congress.

Example:

int main() {

	int score = 0;

	cout << "Please enter the test score:" << endl;

	cin >> score;

	if (score > 600)
	{
		cout << "I was admitted to a university" << endl;
		if (score > 700)
		{
			cout << "I was admitted to Peking University" << endl;
		}
		else if (score > 650)
		{
			cout << "I was admitted to Tsinghua University" << endl;
		}
		else
		{
			cout << "I was admitted to the National People's Congress" << endl;
		}
		
	}
	else if (score > 500)
	{
		cout << "I was admitted to two universities" << endl;
	}
	else if (score > 400)
	{
		cout << "I was admitted to three universities" << endl;
	}
	else
	{
		cout << "I didn't go to college" << endl;
	}

	system("pause");

	return 0;
}

Exercise case: weigh three piglets

There are three piglets ABC. Please input the weight of the three piglets respectively and judge which piglet is the heaviest? [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-PhqzxGwq-1629339524076)(assets / three piglets. jpg)]

4.1. 2 ternary operator

Function: realize simple judgment through 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:

int main() {

	int a = 10;
	int b = 20;
	int c = 0;

	c = a > b ? a : b;
	cout << "c = " << c << endl;

	//The ternary operator in C + + returns variables and can continue to assign values

	(a > b ? a : b) = 100;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;

	system("pause");

	return 0;
}

Summary: compared with the if statement, the advantage of the ternary operator is short and neat, but the disadvantage is that if nested, the structure is not clear

4.1.3 switch statement

**Function: * * execute multi conditional branch statements

Syntax:

switch(expression)

{

	case Result 1: execute the statement;break;

	case Result 2: execute the statement;break;

	...

	default:Execute statement;break;

}

Example:

int main() {

	//Please rate the movie 
	//10 ~ 9 classic   
	// 8 ~ 7 very good
	// 6 ~ 5 general
	// Rotten film with less than 5 points

	int score = 0;
	cout << "Please rate the movie" << endl;
	cin >> score;

	switch (score)
	{
	case 10:
	case 9:
		cout << "classic" << endl;
		break;
	case 8:
		cout << "very nice" << endl;
		break;
	case 7:
	case 6:
		cout << "commonly" << endl;
		break;
	default:
		cout << "Rotten film" << endl;
		break;
	}

	system("pause");

	return 0;
}

Note 1: the expression type in the switch statement can only be integer or character

Note 2: if there is no break in the case, the program will always execute downward

Conclusion: compared with if statements, for multi condition judgment, switch has clear structure and high execution efficiency. The disadvantage is that switch cannot judge the interval

4.2 circulation structure

4.2. 1. While loop statement

**Function: * * execute loop statements when loop conditions are met

Syntax: while (loop condition) {loop statement}

Explanation: as long as the result of the loop condition is true, the loop statement is executed

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-uhMCfo5w-1629339524077)(assets/clip_image002-1541668640382.png)]

Example:

int main() {

	int num = 0;
	while (num < 10)
	{
		cout << "num = " << num << endl;
		num++;
	}
	
	system("pause");

	return 0;
}

Note: when executing a loop statement, the program must provide an exit to jump out of the loop, otherwise an endless loop will occur

while loop exercise case: guess numbers

**Case description: * * the system randomly generates a number between 1 and 100, and the player guesses. If the guess is wrong, the player will be prompted that the number is too large or too small. If the guess is right, congratulations on the player's victory and exit the game.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-KNXhucYc-1629339524078)(assets / guess number. jpg)]

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 * * and while is that do... While will execute a loop statement first, and then judge the loop conditions

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-cZ4m0dHt-1629339524078)(assets/clip_image002-1541671163478.png)]

Example:

int main() {

	int num = 0;

	do
	{
		cout << num << endl;
		num++;

	} while (num < 10);
	
	
	system("pause");

	return 0;
}

Summary: the difference between do... While and while loop is that do... While executes the loop statement once before judging the loop conditions

Exercise case: daffodils

**Case description: * * daffodil 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

Please use the do... while statement to find the number of daffodils in all 3 digits

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:

int main() {

	for (int i = 0; i < 10; i++)
	{
		cout << i << endl;
	}
	
	system("pause");

	return 0;
}

Detailed explanation:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ZkDEKH4Q-1629339524079)(assets/1541673704101.png)]

Note: the expressions in the for loop should be separated by semicolons

Summary: while, do... While and for are loop statements commonly used in development. The for loop structure is relatively clear and commonly used

Exercise case: knocking on the table

Case description: count from 1 to 100. If the digit contains 7, or the digit ten contains 7, or the digit is a multiple of 7, we print and knock on the table, and the other digits are printed directly.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-GgoTv9uV-1629339524079)(assets/timg.gif)]

4.2. 4 nested loop

Function: nest another layer of loop in the loop body to solve some practical problems

For example, if we want to print the following pictures on the screen, we need to use nested loops

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-d4FFwSVt-1629339524080)(assets/1541676003486.png)]

Example:

int main() {

	//The outer loop is executed once and the inner loop is executed once
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			cout << "*" << " ";
		}
		cout << endl;
	}

	system("pause");

	return 0;
}

**Exercise case: * * multiplication formula table

Case description: use nested loop to realize 99 multiplication table

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Shu2tsUz-1629339524080)(assets/0006018857256120_b.jpg)]

4.3 jump statement

4.3.1 break statement

Function: used to jump out of the selection structure or loop structure

When to use break:

  • It appears in the switch conditional statement to terminate the case and jump out of the switch
  • 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

Example 1:

int main() {
	//1. Use break in switch statements
	cout << "Please select the difficulty of your challenge copy:" << endl;
	cout << "1,ordinary" << endl;
	cout << "2,secondary" << endl;
	cout << "3,difficulty" << endl;

	int num = 0;

	cin >> num;

	switch (num)
	{
	case 1:
		cout << "You chose ordinary difficulty" << endl;
		break;
	case 2:
		cout << "You chose medium difficulty" << endl;
		break;
	case 3:
		cout << "You chose difficulty" << endl;
		break;
	}

	system("pause");

	return 0;
}

Example 2:

int main() {
	//2. Using break in a loop statement
	for (int i = 0; i < 10; i++)
	{
		if (i == 5)
		{
			break; //Jump out of loop statement
		}
		cout << i << endl;
	}

	system("pause");

	return 0;
}

Example 3:

int main() {
	//Use break in a nested loop statement to exit the inner loop
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			if (j == 5)
			{
				break;
			}
			cout << "*" << " ";
		}
		cout << endl;
	}
	
	system("pause");

	return 0;
}

4.3.2 continue statement

**Function: * * in a loop statement, skip the remaining unexecuted statements in this loop and continue to execute the next loop

Example:

int main() {

	for (int i = 0; i < 100; i++)
	{
		if (i % 2 == 0)
		{
			continue;
		}
		cout << i << endl;
	}
	
	system("pause");

	return 0;
}

Note: continue does not terminate the entire 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 tag name exists, the goto statement will jump to the location of the tag

Example:

int main() {

	cout << "1" << endl;

	goto FLAG;

	cout << "2" << endl;
	cout << "3" << endl;
	cout << "4" << endl;

	FLAG:

	cout << "5" << endl;
	
	system("pause");

	return 0;
}

Note: goto statement is not recommended in the program to avoid confusion of program flow

5 array

5.1 general

An array is a collection containing data elements of the same type

**Feature 1: * * each data element in the array is of the same data type

**Feature 2: * * array is composed of continuous memory locations

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-02FZ3vsB-1629339524080)(assets/1541748375356.png)]

5.2 one dimensional array

5.2. 1. Definition method of one-dimensional array

There are three ways to define a one-dimensional 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...};

Example

int main() {

	//Definition method 1
	//Data type array name [number of elements];
	int score[10];

	//Assignment with subscript
	score[0] = 100;
	score[1] = 99;
	score[2] = 85;

	//Using subscript output
	cout << score[0] << endl;
	cout << score[1] << endl;
	cout << score[2] << endl;


	//The second definition method
	//Data type array name [number of elements] = {value 1, value 2, value 3...};
	//If there are less than 10 data in {}, the remaining data shall be filled with 0
	int score2[10] = { 100, 90,80,70,60,50,40,30,20,10 };
	
	//Output one by one
	//cout << score2[0] << endl;
	//cout << score2[1] << endl;

	//One output is too cumbersome, so you can use loops to output
	for (int i = 0; i < 10; i++)
	{
		cout << score2[i] << endl;
	}

	//Definition mode 3
	//Data type array name [] = {value 1, value 2, value 3...};
	int score3[] = { 100,90,80,70,60,50,40,30,20,10 };

	for (int i = 0; i < 10; i++)
	{
		cout << score3[i] << endl;
	}

	system("pause");

	return 0;
}

Summary 1: the naming convention of array name is consistent with that of variable name. Do not duplicate the name of variable

Summary 2: the index in the array starts from 0

5.2. 2 one dimensional array name

Purpose of one-dimensional array name:

  1. You can count the length of the entire array in memory
  2. You can get the first address of the array in memory

Example:

int main() {

	//Array name usage
	//1. You can get the memory space occupied by the entire array
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };

	cout << "The memory space occupied by the whole array is: " << sizeof(arr) << endl;
	cout << "The memory space occupied by each element is: " << sizeof(arr[0]) << endl;
	cout << "The number of elements of the array is: " << sizeof(arr) / sizeof(arr[0]) << endl;

	//2. You can get the first address of the array through the array name
	cout << "The first address of the array is: " << (int)arr << endl;
	cout << "The address of the first element in the array is: " << (int)&arr[0] << endl;
	cout << "The address of the second element in the array is: " << (int)&arr[1] << endl;

	//arr = 100;  Error, array name is constant, so it cannot be assigned


	system("pause");

	return 0;
}

Note: the array name is a constant and cannot be assigned

Summary 1: print the array name directly, and you can view the first address of the memory occupied by the array

Summary 2: sizeof the array name can obtain the memory space occupied by the entire array

Exercise case 1: weigh five piglets

Case description:

The weight of five piglets is recorded in an array, such as int arr [5] = {300350200400250};

Find and print the heaviest pig weight.

**Exercise case 2: * * array element inversion

**Case description: * * Please declare an array of 5 elements and invert the elements

(for example, the original array elements are: 1,3,2,5,4; the output result after inverse is: 4,5,2,3,1);

5.2. 3 bubble sorting

Function: the most commonly used sorting algorithm to sort the elements in the array

  1. Compare adjacent elements. If the first one is bigger than the second, exchange them.
  2. Do the same work for each pair of adjacent elements. After execution, find the first maximum value.
  3. Repeat the above steps for - 1 times each time until no comparison is needed

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-UilFAvkD-1629339524081)(assets/1541905327273.png)]

Example: sort the array {4,2,8,0,5,7,1,3,9} in ascending order

int main() {

	int arr[9] = { 4,2,8,0,5,7,1,3,9 };

	for (int i = 0; i < 9 - 1; i++)
	{
		for (int j = 0; j < 9 - 1 - i; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}

	for (int i = 0; i < 9; i++)
	{
		cout << arr[i] << endl;
	}
    
	system("pause");

	return 0;
}

5.3 two dimensional array

A two-dimensional array is to add one more dimension to a one-dimensional array.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-AEuiAeBt-1629339524081)(assets/1541905559138.png)]

5.3. 1. Definition method of two-dimensional array

There are four ways to define a two-dimensional array:

  1. Data type array name [number of rows] [number of columns];
  2. Data type array name [number of rows] [number of columns] = {data 1, data 2}, {data 3, data 4}};
  3. Data type array name [number of rows] [number of columns] = {data 1, data 2, data 3, data 4};
  4. Data type array name [] [number of columns] = {data 1, data 2, data 3, data 4};

Suggestion: for the above four definitions, the second one is more intuitive to improve the readability of the code

Example:

int main() {

	//Mode 1  
	//Array type array name [number of rows] [number of columns]
	int arr[2][3];
	arr[0][0] = 1;
	arr[0][1] = 2;
	arr[0][2] = 3;
	arr[1][0] = 4;
	arr[1][1] = 5;
	arr[1][2] = 6;

	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			cout << arr[i][j] << " ";
		}
		cout << endl;
	}

	//Mode 2 
	//Data type array name [number of rows] [number of columns] = {data 1, data 2}, {data 3, data 4}};
	int arr2[2][3] =
	{
		{1,2,3},
		{4,5,6}
	};

	//Mode 3
	//Data type array name [number of rows] [number of columns] = {data 1, data 2, data 3, data 4};
	int arr3[2][3] = { 1,2,3,4,5,6 }; 

	//Mode 4 
	//Data type array name [] [number of columns] = {data 1, data 2, data 3, data 4};
	int arr4[][3] = { 1,2,3,4,5,6 };
	
	system("pause");

	return 0;
}

Summary: when defining a two-dimensional array, if data is initialized, the number of rows can be omitted

5.3. 2 two dimensional array name

  • View the memory space occupied by the two-dimensional array
  • Get the first address of two-dimensional array

Example:

int main() {

	//2D array name
	int arr[2][3] =
	{
		{1,2,3},
		{4,5,6}
	};

	cout << "2D array size: " << sizeof(arr) << endl;
	cout << "One row size of two-dimensional array: " << sizeof(arr[0]) << endl;
	cout << "2D array element size: " << sizeof(arr[0][0]) << endl;

	cout << "Rows of 2D array: " << sizeof(arr) / sizeof(arr[0]) << endl;
	cout << "Number of 2D array columns: " << sizeof(arr[0]) / sizeof(arr[0][0]) << endl;

	//address
	cout << "First address of 2D array:" << arr << endl;
	cout << "Address of the first row of 2D array:" << arr[0] << endl;
	cout << "Address of the second row of 2D array:" << arr[1] << endl;

	cout << "Address of the first element of 2D array:" << &arr[0][0] << endl;
	cout << "Address of the second element of 2D array:" << &arr[0][1] << endl;

	system("pause");

	return 0;
}

Summary 1: the two-dimensional array name is the first address of the array

Summary 2: when sizeof a two-dimensional array name, you can obtain the memory space occupied by the entire two-dimensional array

5.3. 3 application case 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

languagemathematicsEnglish
Zhang San100100100
Li Si9050100
Wang Wu607080

Reference answer:

int main() {

	int scores[3][3] =
	{
		{100,100,100},
		{90,50,100},
		{60,70,80},
	};

	string names[3] = { "Zhang San","Li Si","Wang Wu" };

	for (int i = 0; i < 3; i++)
	{
		int sum = 0;
		for (int j = 0; j < 3; j++)
		{
			sum += scores[i][j];
		}
		cout << names[i] << "The total score of students is: " << sum << endl;
	}

	system("pause");

	return 0;
}

6 function

6.1 general

**Function: * * encapsulate a piece of frequently used code to reduce repeated code

A large program is generally divided into several program blocks, and each module realizes specific functions.

6.2 definition of function

The definition of a function generally consists of five steps:

1. Return value type

2. Function name

3. Parameter table column

4. Function body statement

5. return expression

Syntax:

Return value type function name (parameter list)
{

       Function body statement

       return expression

}
  • Return value type: a function can return a value. In function definition
  • Function name: give the function a name
  • Parameter list: the data passed in when using this function
  • Function body statement: the code in curly braces and the statement to be executed in the function
  • Return expression: linked to the return value type. After the function is executed, the corresponding data is returned

**Example: * * define an addition function to add two numbers

//Function definition
int add(int num1, int num2)
{
	int sum = num1 + num2;
	return sum;
}

6.3 function call

**Function: * * use defined function

Syntax: function name (parameter)

Example:

//Function definition
int add(int num1, int num2) //Num1 and num2 in the definition are called formal parameters, or formal parameters for short
{
	int sum = num1 + num2;
	return sum;
}

int main() {

	int a = 10;
	int b = 10;
	//Call the add function
	int sum = add(a, b);//a and b at the time of calling are called actual parameters, which are referred to as actual parameters for short
	cout << "sum = " << sum << endl;

	a = 100;
	b = 100;

	sum = add(a, b);
	cout << "sum = " << sum << endl;

	system("pause");

	return 0;
}

Summary: the parentheses in the function definition are called formal parameters, and the parameters passed in during function call are called arguments

6.4 value transfer

  • The so-called value passing means that the real parameter passes the value to the formal parameter when the function is called
  • When a value is passed, if a formal parameter occurs, the argument is not affected

Example:

void swap(int num1, int num2)
{
	cout << "Before exchange:" << endl;
	cout << "num1 = " << num1 << endl;
	cout << "num2 = " << num2 << endl;

	int temp = num1;
	num1 = num2;
	num2 = temp;

	cout << "After exchange:" << endl;
	cout << "num1 = " << num1 << endl;
	cout << "num2 = " << num2 << endl;

	//return ;  When a function is declared, there is no need to return a value. You can not write return
}

int main() {

	int a = 10;
	int b = 20;

	swap(a, b);

	cout << "mian Medium a = " << a << endl;
	cout << "mian Medium b = " << b << endl;

	system("pause");

	return 0;
}

Summary: formal parameters cannot modify arguments when passing values

6.5 common styles of functions

There are four common function styles

  1. No reference, no return
  2. There is no return
  3. Return without participation
  4. Participation and return

Example:

//Common styles for functions
//1. No reference, no return
void test01()
{
	//void a = 10; // No type. Cannot create variable because memory cannot be allocated
	cout << "this is test01" << endl;
	//test01();  function call
}

//2. There is no return
void test02(int a)
{
	cout << "this is test02" << endl;
	cout << "a = " << a << endl;
}

//3. Return without participation
int test03()
{
	cout << "this is test03 " << endl;
	return 10;
}

//4. Participation and return
int test04(int a, int b)
{
	cout << "this is test04 " << endl;
	int sum = a + b;
	return sum;
}

6.6 function declaration

Function: tell the compiler the function name and how to call the function. The actual body of a function can be defined separately.

  • A function can be declared multiple times, but a function can only be defined once

Example:

//You can declare multiple times and define only once
//statement
int max(int a, int b);
int max(int a, int b);
//definition
int max(int a, int b)
{
	return a > b ? a : b;
}

int main() {

	int a = 100;
	int b = 200;

	cout << max(a, b) << endl;

	system("pause");

	return 0;
}

6.7 function sub file preparation

**Function: * * make the code structure clearer

Function sub file writing generally has four steps

  1. Create the suffix h header file
  2. Create the suffix cpp source file
  3. Write the declaration of the function in the header file
  4. Write the definition of the function in the source file

Example:

//swap.h file
#include<iostream>
using namespace std;

//A function declaration that implements the exchange of two numbers
void swap(int a, int b);

//swap.cpp file
#include "swap.h"

void swap(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
}
//main function file
#include "swap.h"
int main() {

	int a = 100;
	int b = 200;
	swap(a, b);

	system("pause");

	return 0;
}

7 pointer

7.1 basic concept of pointer

Function of pointer: memory can be accessed indirectly through pointer

  • The memory number starts from 0 and is generally represented by hexadecimal digits

  • Pointer variables can be used to save addresses

7.2 definition and use of pointer variables

Pointer variable definition syntax: data type * variable name;

Example:

int main() {

	//1. Definition of pointer
	int a = 10; //Define integer variable a
	
	//Pointer definition syntax: data type * variable name;
	int * p;

	//Pointer variable assignment
	p = &a; //The pointer points to the address of variable a
	cout << &a << endl; //Address of print data a
	cout << p << endl;  //Print pointer variable p

	//2. Use of pointers
	//Memory pointed to by * operation pointer variable
	cout << "*p = " << *p << endl;

	system("pause");

	return 0;
}

Difference between pointer variable and ordinary variable

  • Ordinary variables store data, and pointer variables store addresses
  • Pointer variables can operate the memory space pointed to by pointer variables through the "*" operator. This process is called dereference

Summary 1: we can get the address of the variable through the & symbol

Summary 2: use the pointer to record the address

Summary 3: dereference the pointer variable and operate the memory pointed to by the pointer

7.3 memory space occupied by pointer

Question: pointer is also a data type. How much memory does this data type occupy?

Example:

int main() {

	int a = 10;

	int * p;
	p = &a; //The pointer points to the address of data a

	cout << *p << endl; //*Dereference
	cout << sizeof(p) << endl;
	cout << sizeof(char *) << endl;
	cout << sizeof(float *) << endl;
	cout << sizeof(double *) << endl;

	system("pause");

	return 0;
}

Summary: all pointer types are 4 bytes under 32-bit operating system

7.4 null pointer and wild pointer

Null pointer: pointer variable points to the space numbered 0 in memory

**Purpose: * * initialize pointer variable

**Note: * * the memory pointed to by the null pointer is inaccessible

Example 1: null pointer

int main() {

	//The pointer variable p points to the space with memory address number 0
	int * p = NULL;

	//Error accessing null pointer 
	//Memory numbers 0 ~ 255 are the memory occupied by the system and are not allowed to be accessed by users
	cout << *p << endl;

	system("pause");

	return 0;
}

Wild pointer: pointer variable points to illegal memory space

Example 2: field pointer

int main() {

	//The pointer variable p points to the space with the memory address number 0x1100
	int * p = (int *)0x1100;

	//Error in accessing field pointer 
	cout << *p << endl;

	system("pause");

	return 0;
}

Conclusion: null pointer and wild pointer are not the space we apply for, so do not access.

7.5 const modifier pointer

const modifier pointer has three cases

  1. const modifier pointer - constant pointer
  2. const modifier constant - pointer constant
  3. const modifies both pointers and constants

Example:

int main() {

	int a = 10;
	int b = 10;

	//const modifies the pointer. The pointer can be changed, and the value pointed to by the pointer cannot be changed
	const int * p1 = &a; 
	p1 = &b; //correct
	//*p1 = 100;   report errors
	

	//const is a constant. The pointer cannot be changed, and the value pointed to by the pointer can be changed
	int * const p2 = &a;
	//p2 = &b; // error
	*p2 = 100; //correct

    //const modifies both pointers and constants
	const int * const p3 = &a;
	//p3 = &b; // error
	//*p3 = 100; // error

	system("pause");

	return 0;
}

Tip: look at 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 pointer constant

7.6 pointers and arrays

**Function: * * use pointer to access elements in array

Example:

int main() {

	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };

	int * p = arr;  //Pointer to array

	cout << "First element: " << arr[0] << endl;
	cout << "Pointer to access the first element: " << *p << endl;

	for (int i = 0; i < 10; i++)
	{
		//Traversing arrays with pointers
		cout << *p << endl;
		p++;
	}

	system("pause");

	return 0;
}

7.7 pointers and functions

**Function: * * use pointers as function parameters to modify the value of arguments

Example:

//pass by value
void swap1(int a ,int b)
{
	int temp = a;
	a = b; 
	b = temp;
}
//Address delivery
void swap2(int * p1, int *p2)
{
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}

int main() {

	int a = 10;
	int b = 20;
	swap1(a, b); // Value passing does not change the argument

	swap2(&a, &b); //Address passing changes the arguments

	cout << "a = " << a << endl;

	cout << "b = " << b << endl;

	system("pause");

	return 0;
}

Summary: if you don't want to modify the argument, pass it by value. If you want to modify the argument, pass it by address

7.8 pointers, arrays, functions

**Case description: * * encapsulates a function that uses bubble sorting to sort integer arrays in ascending order

For example, array: int arr [10] = {4,3,6,9,1,2,10,8,7,5};

Example:

//Bubble sort function
void bubbleSort(int * arr, int len)  //int * arr can also be written as int arr []
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - 1 - i; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

//Print array function
void printArray(int arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << endl;
	}
}

int main() {

	int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
	int len = sizeof(arr) / sizeof(int);

	bubbleSort(arr, len);

	printArray(arr, len);

	system("pause");

	return 0;
}

Summary: when an array name is passed into a function as an argument, it is degenerated into a pointer to the first element

8 structure

8.1 basic concept of structure

Structures are user-defined data types, allowing 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 as you define the structure

Example:

//Structure definition
struct student
{
	//Member list
	string name;  //full name
	int age;      //Age
	int score;    //fraction
}stu3; //Structure variable creation method 3 


int main() {

	//Structure variable creation method 1
	struct student stu1; //The struct keyword can be omitted

	stu1.name = "Zhang San";
	stu1.age = 18;
	stu1.score = 100;
	
	cout << "full name:" << stu1.name << " Age:" << stu1.age  << " fraction:" << stu1.score << endl;

	//Structure variable creation method 2
	struct student stu2 = { "Li Si",19,60 };

	cout << "full name:" << stu2.name << " Age:" << stu2.age  << " fraction:" << stu2.score << endl;


	stu3.name = "Wang Wu";
	stu3.age = 18;
	stu3.score = 80;
	

	cout << "full name:" << stu3.name << " Age:" << stu3.age  << " fraction:" << stu3.score << endl;

	system("pause");

	return 0;
}

Summary 1: the keyword used to define a structure is struct, which cannot be omitted

Summary 2: when creating structural variables, the keyword struct can be omitted

Summary 3: structural variables use the operator '.' Access member

8.3 structure array

**Function: * * put the user-defined structure into the array for easy maintenance

Syntax: struct structure name array name [number of elements] = {{}, {} {} }

Example:

//Structure definition
struct student
{
	//Member list
	string name;  //full name
	int age;      //Age
	int score;    //fraction
}

int main() {
	
	//Structure array
	struct student arr[3]=
	{
		{"Zhang San",18,80 },
		{"Li Si",19,60 },
		{"Wang Wu",20,70 }
	};

	for (int i = 0; i < 3; i++)
	{
		cout << "full name:" << arr[i].name << " Age:" << arr[i].age << " fraction:" << arr[i].score << endl;
	}

	system("pause");

	return 0;
}

8.4 structure pointer

**Function: * * access members in a structure through a pointer

  • Using the operator - > you can access structure properties through the structure pointer

Example:

//Structure definition
struct student
{
	//Member list
	string name;  //full name
	int age;      //Age
	int score;    //fraction
};


int main() {
	
	struct student stu = { "Zhang San",18,100, };
	
	struct student * p = &stu;
	
	p->score = 80; //Members can be accessed through the pointer - > operator

	cout << "full name:" << p->name << " Age:" << p->age << " fraction:" << p->score << endl;
	
	system("pause");

	return 0;
}

Summary: structure pointers can access members in a structure through the - > operator

8.5 nested structures

Action: a member in a structure can be another structure

**For example: * * each teacher tutors a student. In the structure of a teacher, record the structure of a student

Example:

//Definition of student structure
struct student
{
	//Member list
	string name;  //full name
	int age;      //Age
	int score;    //fraction
};

//Definition of teacher structure
struct teacher
{
    //Member list
	int id; //Employee number
	string name;  //Teacher name
	int age;   //Teacher age
	struct student stu; //Substructure student
};


int main() {

	struct teacher t1;
	t1.id = 10000;
	t1.name = "Lao Wang";
	t1.age = 40;

	t1.stu.name = "Zhang San";
	t1.stu.age = 18;
	t1.stu.score = 100;

	cout << "Teacher employee No.: " << t1.id << " full name: " << t1.name << " Age: " << t1.age << endl;
	
	cout << "Name of trainee: " << t1.stu.name << " Age:" << t1.stu.age << " Test score: " << t1.stu.score << endl;

	system("pause");

	return 0;
}

**Summary: * * in a structure, another structure can be defined as a member to solve practical problems

8.6 function parameters of structure

**Function: * * pass the structure to the function as a parameter

There are two delivery methods:

  • pass by value
  • Address delivery

Example:

//Definition of student structure
struct student
{
	//Member list
	string name;  //full name
	int age;      //Age
	int score;    //fraction
};

//pass by value
void printStudent(student stu )
{
	stu.age = 28;
	cout << "Name in subfunction:" << stu.name << " Age: " << stu.age  << " fraction:" << stu.score << endl;
}

//Address delivery
void printStudent2(student *stu)
{
	stu->age = 28;
	cout << "Name in subfunction:" << stu->name << " Age: " << stu->age  << " fraction:" << stu->score << endl;
}

int main() {

	student stu = { "Zhang San",18,100};
	//pass by value
	printStudent(stu);
	cout << "Name in main function:" << stu.name << " Age: " << stu.age << " fraction:" << stu.score << endl;

	cout << endl;

	//Address delivery
	printStudent2(&stu);
	cout << "Name in main function:" << stu.name << " Age: " << stu.age  << " fraction:" << stu.score << endl;

	system("pause");

	return 0;
}

Summary: if you do not want to modify the data in the main function, pass it by value, otherwise pass it by address

8.7 const usage scenario in structure

**Function: * * const is used to prevent misoperation

Example:

//Definition of student structure
struct student
{
	//Member list
	string name;  //full name
	int age;      //Age
	int score;    //fraction
};

//const usage scenario
void printStudent(const student *stu) //Add const to prevent misoperation in function body
{
	//stu->age = 100; // The operation failed because of the const modifier
	cout << "full name:" << stu->name << " Age:" << stu->age << " fraction:" << stu->score << endl;

}

int main() {

	student stu = { "Zhang San",18,100 };

	printStudent(&stu);

	system("pause");

	return 0;
}

8.8 structural case

8.8. 1 case 1

Case description:

The school is working on the completion project. Each teacher leads 5 students, with a total of 3 teachers. The needs are as follows

Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members

Students' members have names and test scores. Create an array to store 3 teachers, and assign values to each teacher and students through functions

Finally, print out the teacher data and the student data brought by the teacher.

Example:

struct Student
{
	string name;
	int score;
};
struct Teacher
{
	string name;
	Student sArray[5];
};

void allocateSpace(Teacher tArray[] , int len)
{
	string tName = "teacher";
	string sName = "student";
	string nameSeed = "ABCDE";
	for (int i = 0; i < len; i++)
	{
		tArray[i].name = tName + nameSeed[i];
		
		for (int j = 0; j < 5; j++)
		{
			tArray[i].sArray[j].name = sName + nameSeed[j];
			tArray[i].sArray[j].score = rand() % 61 + 40;
		}
	}
}

void printTeachers(Teacher tArray[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << tArray[i].name << endl;
		for (int j = 0; j < 5; j++)
		{
			cout << "\t full name:" << tArray[i].sArray[j].name << " fraction:" << tArray[i].sArray[j].score << endl;
		}
	}
}

int main() {

	srand((unsigned int)time(NULL)); //Random number seed header file #include < CTime >

	Teacher tArray[3]; //Teacher array

	int len = sizeof(tArray) / sizeof(Teacher);

	allocateSpace(tArray, len); //Create data

	printTeachers(tArray, len); //print data
	
	system("pause");

	return 0;
}

8.8. 2 case 2

Case description:

Design a hero structure, including member name, age and gender; Create a structure array, in which 5 heroes are stored.

Through the bubble sorting algorithm, the heroes in the array are sorted in ascending order according to their age, and the sorted results are finally printed.

The information of the five heroes is as follows:

		{"Liu Bei",23,"male"},
		{"Guan Yu",22,"male"},
		{"Fei Zhang",20,"male"},
		{"Zhao Yun",21,"male"},
		{"army officer's hat ornaments",19,"female"},

Example:

//Hero structure
struct hero
{
	string name;
	int age;
	string sex;
};
//Bubble sorting
void bubbleSort(hero arr[] , int len)
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - 1 - i; j++)
		{
			if (arr[j].age > arr[j + 1].age)
			{
				hero temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}
//Print array
void printHeros(hero arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << "full name: " << arr[i].name << " Gender: " << arr[i].sex << " Age: " << arr[i].age << endl;
	}
}

int main() {

	struct hero arr[5] =
	{
		{"Liu Bei",23,"male"},
		{"Guan Yu",22,"male"},
		{"Fei Zhang",20,"male"},
		{"Zhao Yun",21,"male"},
		{"army officer's hat ornaments",19,"female"},
	};

	int len = sizeof(arr) / sizeof(hero); //Get the number of array elements

	bubbleSort(arr, len); //sort

	printHeros(arr, len); //Print

	system("pause");

	return 0;
}

Topics: C++