Entry level teaching of C + + from 0 to 1 - array

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: the array is composed of continuous memory locations

5.2 one dimensional array

5.2.1 definition of one-dimensional array

To create an array, use a declaration statement. The array declaration should point out the following three points:

  • The type of value stored in each element
  • Array name
  • Number of elements in the array

There are three ways to define a one-dimensional array:

  • Data type array name [array length];
  • Data type array name [array length] = {value 1, value 2...};
  • Data type array name [] = {value 1, value 2...};

[Note: let the compiler do it; usually, like the third definition, it is a bad practice for the compiler to count the number of elements, because its count may not be the same as we think.]

Array features:

  1. In a contiguous memory space
  2. Each element in the array is of the same data type

Index of array:

The use of arrays is based on the fact that array elements can be accessed separately. The method is to use a subscript or index to number the elements. C + + arrays are numbered from 0, which is not negotiable. That is, arr[0].

Importance of valid subscript values:

The compiler does not check whether the subscript used is valid. For example, if you assign a value to an element that does not exist, such as

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

Then the compiler will not point out errors.

However, after the program runs, this assignment may cause problems. It may destroy data or code, or cause the program to terminate abnormally. Therefore, it must be ensured that the program only uses valid subscript values.

Example:

#include <iostream>
using namespace std;
int main()
{
	/*1,Data type array name [array length]; 

	2,Data type array name [array length] = {value 1, value 2...}; 

	3,Data type array name [] = {value 1, value 2...}; */

	//1. Data type array name [array length]
	//int arr[5];
	//Assign values to elements in the array
	//The subscripts of array elements are indexed from 0
	/*arr[0] = 10;
	arr[1] = 20;
	arr[2] = 30;
	arr[3] = 40;
	arr[4] = 50;*/

	//Accessing data elements
	/*cout << arr[0] << endl;
	cout << arr[1] << endl;
	cout << arr[2] << endl;
	cout << arr[3] << endl;
	cout << arr[4] << endl;*/

	//2. Data type array name [array length] = {value 1, value 2...}
	//If all the data is not initialized when initializing the data, the initial value of the uninitialized value is 0
	int arr2[5] = { 10,20,30,40,50 };
	/*cout << arr2[0] << endl;
	cout << arr2[1] << endl;
	cout << arr2[2] << endl;
	cout << arr2[3] << endl;
	cout << arr2[4] << endl;*/
	for (int i = 0; i < 5; i++) 
	{
		cout << arr2[i] << endl;
	}

	//3. Data type array name [] = {value 1, value 2...};
	int arr3[] = { 100,90,80,70,60,50,40,30,20,10 };
	for (int i = 0; i < 10; i++) 
	{
		cout << arr3[i] << endl;
	}
    system("pause");
	return 0;
}

[summary 1: the naming standard of array name is consistent with that of variable name, and do not duplicate the name of variable]

[summary 2: the index in the array starts from 0]

5.2.2 initialization rules of array

C + + has several rules for initializing arrays. They limit the time of initialization and determine that the number of elements in the array and the number of values in the initializer will be sent when they are different.

Generally speaking, when we define an array, we will initialize it, that is:

int cards[4] = {3,6,8,10}

However, there are exceptions. However, if you don't initialize when defining, you can't initialize later. If you specify the number of elements of the array in square brackets, it's easy to say that if you don't initialize it, it will fill you with 0 by default,; But if you don't even specify the number of elements of the array, the array will be confused: it knows nothing about who I am and what I'm doing. Therefore, in order to enable you to initialize when defining, visual studio does a very good job, as follows:

It is worth mentioning that unlike java, C + + cannot assign an array to another array, which is not allowed.

int cards[4] = {3,6,8,10};
int hand[4];
hand = cards;

In the compiler, the compiler will prompt you that the expression must be a modifiable lvalue.

If you specify the number of array elements when initializing the array, but do not fully initialize and only initialize part of the values, then other elements that do not specify initialization values will default to 0

One dimensional array name 2.5

Purpose of one-dimensional array name:

  1. You can count the length of sizeof(arr) of the entire array in memory
  2. You can get the first address of the array in memory cout < < arr < < endl

Example:

#include <iostream>
using namespace std;
int main()
{
	//Array name usage
	//1. The memory size occupied by the whole array can be counted by the array name
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	cout << "The space occupied by the whole array name is:" << sizeof(arr) << endl;
	cout << "The memory space occupied by each element is:" << sizeof(arr[0]) << endl;
	cout << "The number of elements in the array is:" << sizeof(arr) / sizeof(arr[0]) << endl;

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

	//The array name is a constant and cannot be assigned
	//arr = 10;

	system("pause");
	return 0;
}

[Note: in fact, arr generally means & arr [0], that is, you refer to an array, which is generally the address of the head element of the index group]

5.2.4 exercise case 1: weigh five piglets

Case description:

Record the weight of five piglets in an array, such as int arr [5] = {300350200400250}, find and print the heaviest piglet weight.

Core idea:

Example:

#include <iostream>
using namespace std;
int main()
{
	int arr[5] = { 300,350,200,400,250 };
	int max = 0;
	int test = 0;
	for (int i = 0; i < 5; i++) 
	{
		test = arr[i];
		if (max < test) {
			max = test;
		}
	}
	cout << "The heaviest of the five piglets weighed:" << max << endl;
	system("pause");
	return 0;
}

5.2.5 exercise case 2: 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)

Core idea:

Example:

#include <iostream>
using namespace std;
int main()
{
	//1. Before creating an array
	int arr[5] = { 1,3,2,5,4 };
	int start = 0;
	int end = sizeof(arr) / sizeof(arr[0]) - 1;
	
	cout << "The array before inversion is:" << endl;
	for (int i = 0; i < 5; i++) {
		cout << arr[i] << endl;
	}

	//Create intermediate variable element
	int temp = 0;

	//Realize inversion
	while (start<end) {
		temp = arr[start];
		arr[start] = arr[end];
		arr[end] = temp;
		start++;
		end--;
	}

	cout << "The inverted array is:" << endl;
	for (int i = 0; i < 5; i++) {
		cout <<	arr[i] << endl;
	}


	system("pause");
	return 0;
}

5.2.5 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 larger than the second, exchange them
  2. Do the same work for each pair of adjacent elements. After execution, find a maximum value
  3. Repeat the above steps for - 1 times each time until no comparison is needed

Core idea:

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

#include <iostream>
using namespace std;
int main()
{
	//Using bubble sorting to realize ascending arrangement
	int arr[9] = { 4,2,8,0,5,7,1,3,9 };

	cout << "Before sorting:" << endl;
	for (int i = 0; i < 9; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;

	//Start bubble sort
	//The total number of sorting rounds is - 1
	for (int i = 0; i < 9 - 1; i++) 
	{
		//Comparison of inner circulation
		for (int j = 0; i < 9 - i - 1; j++) 
		{
			if (arr[j] > arr[j + 1]) 
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[ j + 1 ] = temp;
			}
		}
	}
	//Sorted results
	cout << "After sorting:" << endl;
	for (int i = 0; i < 9; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}

5.3 string type

There is a reason to move string type to this chapter, because it actually uses the idea of array.

5.3.1 style

String function: used to represent a string of characters

Two styles

  • C style string: char variable name [] = "string value";
  • C + + style string: string variable name = "string value"

If you use a C-style string to represent a string:

char dog[8] = { 'b', 'e', 'a', 'u', 'x', ' ', 'I', 'I'};  // not a string!
char cat[8] = {'f', 'a', 't', 'e', 's', 's', 'a', '\0'};  // a string!

Because in C + + regulations, C-style strings end with a null character, which is written as \ 0, which is used to mark the end of the string. Both of the above are char arrays, but in fact, only the second array is a string, for the reason we mentioned earlier. Cout displays the seven characters in front of the cat above, and stops when an empty character is found; If you do not add a null character, such as dog, cout will print out all the subsequent bytes in the memory until it encounters a null character; Therefore, empty characters are very important.

However, if you use the array form of C-style string to represent the string, you have to write so many single quotation marks and add empty characters. He doesn't bother me. Therefore, in order to save everyone's worry, a string that can be enclosed in quotation marks appears in C + +, which is called string constant or string literal value.

char bird[11] = "Mr. Cheeps";    // the \0 is understood
char fish[] = "Bubbles";         // let the compiler count

Strings enclosed in quotation marks implicitly include empty characters at the end, so you don't have to write them anymore.

Use graphics to show what I said earlier is:

Of course, regardless of the implicit display, you need to know that when you use sizeof to check the size of the string written in this way, it will count in the empty characters, as shown in the following figure:

Note that we said that character constants use single quotation marks instead of double quotation marks; Similarly, string constants can only use double quotation marks, not single quotation marks.

If you want to explain, you need to know that character constants are generally a character enclosed in single quotation marks is a number in ASCII, while we write string constants enclosed in double quotation marks are generally the memory address of the corresponding string. So, if you write the following code:

char shirt_size = 'S';

It just assigns 83 in ASCII to shirt_size is a character constant, so it becomes a character; And if you write the following code:

char shirt_size = "S"; 

So this is actually: the memory address of "S" is assigned to shirt_size. The two have completely different meanings.

Therefore, when you come to C + +, the char string type can be equated with the string string type, and the string string also implicitly contains a \ 0.

5.3.2 splicing string constants

In the examples in the previous chapters, in fact, we have used this knowledge more or less. Here, we can explain the principle.

We can combine the strings enclosed in two quotation marks into one, that is:

int i = 1;
cout<<"i love you"<<i<<"day"<<endl

The above code is allowed, which is very similar to java, ha ha.

But looking back at the principle, each string implicitly contains a \ 0, that is, when splicing, the \ 0 in the first string will be replaced by the first character or other types of the following string.

5.3.3 using strings in arrays

There are two most common ways to store strings in an array - initialize the array as a string constant and read keyboard or file input into the array. Let's take a look at an example.

Examples

#include <iostream>
#include <cstring>
using namespace std;
/**
	Make a conversation and greet each other
*/
int main()
{
	const int Size = 15;
	//Use an array to store the C-style string type, which is used to display the other party's name
	char name1[Size];
	char name2[Size] = "C++owboy";

	cout << "Howdy!I'm" << name2;
	cout << "!What's your name?\n";
	
	//Enter the other party's name
	cin >> name1;
	cout << "Well," << name1 << ",your name has";
	
	//Used to count the length of each other's name
	cout << strlen(name1) << "letters and is stored\n";
	
	//Used to count the number of bytes occupied by the other party's name
	cout << "in an array of" << sizeof(name1) << "bytes.\n";

	//It is used to give the header element in the array where the opposite name is stored, that is, the first letter
	cout << "Your initial is" << name1[0] << ".\n";
	name2[3] = '\0';
	cout << "Here are the first 3 characters of my name:";
	cout << name2 << endl;
	return 0;
}

In the above example, the sizeof operator indicates the bytes occupied by the entire array: 15, but the strlen() function returns the length of the string stored in the array, not the length of the array itself. In addition, strlen () only calculates visible characters and does not count null characters.

The index is also used here. At the end of the program, because the fourth element of name2 is modified to an empty character, cout can only output the first three elements, which is actually in full compliance with our previous knowledge.

5.3.4 string input

The program demonstrated in 5.3.3 actually has a bug, which is covered up by our program qualification. Let's look at a program:

#include <iostream>
using namespace std;
int main()
{
	const int ArSize = 20;
	char name[ArSize];
	char dessert[ArSize];

	cout << "Enter your name:\n";
	cin >> name;
	cout << "Enter you favorite dessert:\n";
	cin >> dessert;
	cout << "I have some delicious " << dessert;
	cout << " for you," << name << ".\n";
	return 0;
}
result:
Enter your name:
Misaki
Enter you favorite dessert:
cake
I have some delicious cake for you,Misaki.

The above program is very simple. Read the user name of your keyboard and the pastries you like, and then display these information.

Here are two details:

  1. cin converts the character entered by the keyboard into a string and puts it into the array. We don't type out \ 0, but it will automatically add \ 0 when it is put into the array.
  2. The length of the array for storing strings is specified by ourselves, that is, when using cin to read keyboard characters, it is likely that too many characters will be read by cin, resulting in the string not being placed in the array.

In many programs, it depends on the input of string. Now these problems are very big. Therefore, we must use the higher-level features of cin, which will be mentioned later.

5.4. Two dimensional array

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

5.3.1 definition method of two-dimensional array

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

  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: among the above four definitions, the second one is more intuitive to improve the readability of the code.]

Example:

#include <iostream>
using namespace std;

int main()
{
	//1. Data 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;

	/*cout << arr[0][0] << endl;
	cout << arr[0][1] << endl;
	cout << arr[0][2] << endl;
	cout << arr[1][0] << endl;
	cout << arr[1][1] << endl;
	cout << arr[1][2] << endl;*/

	for (int i = 0; i < 2; i++) 
	{
		for (int j = 0; j < 3; j++) 
		{
			cout << arr[i][j] << " ";
		}
		cout << endl;
	}
	
	
	//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} };
	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 << arr3[i][j] << " ";
		}
		cout << endl;
	}

	//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 };
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			cout << arr4[i][j] << " ";
		}
		cout << endl;
	}
	
	system("pause");
	return 0;
}

5.3.2 array name of two-dimensional array

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

Example:

#include <iostream>
using namespace std;

int main()
{
	//1. View the amount of memory occupied
	int arr[2][3] = { {1,2,3} ,{4,5,6} };
	cout << "The memory space occupied by the two-dimensional array is:" << sizeof(arr) << endl;
	cout << "The space occupied by the first row of two-dimensional array is:" << sizeof(arr[0]) << endl;
	cout << "The memory occupied by the first element of the two-dimensional array is:" << sizeof(arr[0][0]) << endl;

	//Through the above codes, you can count the number of rows and columns of a two-dimensional array
	cout << "The number of rows of the two-dimensional array is:" << sizeof(arr) / sizeof(arr[0]) << endl;
	cout << "The number of columns of the two-dimensional array is:" << sizeof(arr[0]) / sizeof(arr[0][0]) << endl;

	//2. Get the first address of the two-dimensional array
	cout << "First address of two-dimensional array:" << (int)arr << endl;
	cout << "The address at the beginning of the first line of the two-dimensional array is:" << (int)arr[0] << endl;
	cout << "The address at the beginning of the second line of the two-dimensional array is:" << (int)arr[1] << endl;
	
	cout << "The first address of the first element of the two-dimensional array is:" << (int)&arr[0][0] << endl;
	cout << "The first address of the second element of the two-dimensional array is:" << (int)&arr[0][1] << endl;

	system("pause");
	return 0;
}

5.3.3 application cases of two-dimensional array

Test score statistics

Case description: there are three students (Zhang San, Li Si and Wang Wu). Their scores in one exam are shown in the table below. Please output the total scores of the three students respectively.

Zhang San100100100
Li Si9050100
Wang Wu607080

Example:

#include <iostream>
#include <string>
using namespace std;

int main() 
{
	//Two dimensional array case - test result case

	//1. Create a 2D array
	int scores[3][3] = {
		{100,100,100},
		{90,50,100},
		{60,70,80}
	};

	string students[3] = { "Zhang San","Li Si","Wang Wu" };
	//2. Count everyone's total score
	for (int i = 0; i < 3; i++) {
		int sum = 0;//Count the sum of everyone's scores
		for (int j = 0; j < 3; j++) 
		{
			sum += scores[i][j];
			/*cout << scores[i][j] << " ";*/
		}
		cout << students[i]<<"The total score is:"<<sum << endl;
	}



	system("pause");
	return 0;
}

Tags: C++

Posted by brauchi on Sat, 16 Apr 2022 20:02:18 +0930