[C++] Array Basics for Getting Started with C++ 1


Preface

This chapter mainly talks about the difference between data types and data structures, as well as simple array-related content.

Learning route: C++ learning route from entry to NOI

Study Outline: C++ National Youth Olympiad in Informatics (NOI) Entry Level - Outline

Previous stop: An exhaustive introduction to C++ algorithms

Next stop:


1. Data structure concept

We mentioned the concept of data types in " Introduction to C++ Programming III" , and today we are going to learn data structures.

Start by reviewing the following data types.

Data type refers to the type of object processed by the computer. It defines how the data is stored and the operations that can be performed. Data types in C++ include integer, floating point, character, etc. Data types are used to define the type of variables used to store and manipulate data in a program.

Please add image description
It can be understood that in order for the computer to distinguish different variables, we put a vest called data type on the variable, and different data types will receive different " services ".

Passerby: Oh, what is a data structure?

Data structure refers to the organizational form of data, which describes the relationship between data and how to store data. Data structures are used to organize and manage large amounts of data for more efficient manipulation and processing.
Insert image description here
For example, we used to use a variable to record a student's score in one subject, and then we could create several more variables to record all his scores, and through calculations we could get his average score, etc.

But now you are asked to calculate the average score of all the students in the class and find out the outstanding subject scores? If there are 20 students whose grades need to be calculated, do we need to define 20 variables? If there are 100 students whose grades need to be calculated, do we need to define 100 variables?

Obviously this approach won't work. Smart programmers also thought of this problem, so the data structure was invented.

In short, data types describe the attributes of data , while data structures describe the relationships and organization of data .

Data structures can be divided into two categories: linear data structures and non-linear data structures. The array we are learning today is a linear data structure.

A linear data structure is a sequential data structure in which there is a one-to-one relationship between data elements.

A C++ array is a data structure used to store multiple elements of the same type. We can imagine that there is a sports meeting, there is a group of players, they wear the same vests, and then line up in order. They have a famous name called "Jiangnan Leather Factory".

Insert image description here

2. Creation of Array

The creation of C++ arrays can be achieved in the following two ways:

Static array : A static array is an array whose size is determined at compile time. Its size is determined when it is declared and cannot be changed.

The method to create a static array in C++ is as follows:

  1. Declare the array type and array name:
dataType arrayName[arraySize];

Among them, dataType represents the data type of the elements in the array, arrayName is the name of the array, and arraySize is the size of the array.

For example:

int arr[5];

This will create a static array containing 5 integers.

  1. Initialize array elements:
int arr[5] = {
    
    1, 2, 3, 4, 5};

This will create a static array of 5 integers and initialize it to the given value.

提示:静态数组的声明和初始化可以在同一行完成,也可以分开进行。

Dynamic array : A dynamic array is an array whose size is determined at runtime, and its size can be dynamically allocated and released as needed. To create a dynamic array, you need to use the new keyword to allocate memory space and the delete keyword to release the memory space.

The method to create a one-dimensional dynamic array in C++ is as follows:

  1. Use the new keyword to allocate memory space and specify the size of the array.
  2. Assign the returned pointer to a pointer variable for subsequent use.

The steps to turn off a one-dimensional dynamic array are as follows:

  1. Use the delete keyword to release previously allocated memory space.
  2. Set the pointer variable to nullptr to avoid dangling pointer problems.

Demonstrates how to create and close a one-dimensional dynamic array:

#include <iostream>
using namespace std;

int main() {
    
    
    int size;
    cout << "请输入数组的大小:";
    cin >> size;

    // 创建一维动态数组
    int* arr = new int[size];

    // 为数组赋值
    for (int i = 0; i < size; i++) {
    
    
        cout << "请输入第 " << i+1 << " 个元素的值:";
        cin >> arr[i];
    }

    // 输出数组的值
    cout << "数组的值为:";
    for (int i = 0; i < size; i++) {
    
    
        cout << arr[i] << " ";
    }
    cout << endl;

    // 关闭一维动态数组
    delete[] arr;
    arr = nullptr;

    return 0;
}

3. Use of arrays

If you want to learn how to use arrays, you need to know what are array subscripts?

C++ array subscripting refers to accessing elements in an array through index values. In C++, array indexes start from 0 and increase sequentially. Specific elements in an array can be accessed and modified by using the array name and index value.

Insert image description here

  1. Access array elements:
int x = arr[2];

This will access the element at index 2 in the array and assign it to the variable x.

Insert image description here

  1. Modify array elements:
arr[3] = 10;

This will modify the element at index 3 in the array to have a value of 10.
Insert image description here

  1. Traverse the array:
length=7;
for (int i = 0; i < length; i++) {
    
    
    cout << arr[i] << " ";
}

This will loop through the array and print each element.
Insert image description here

注意:长度为 n 的数组,下标从 0~n-1,不能超过这个范围访问数组元素,如果超过就是错的,语法上叫“越界”了!

4. Explanation of sample questions

Question 1: 1423 - Simple statistics of test scores

The final exam is over. Teacher Wang wants to know how many students have excellent grades in this exam (a test score greater than or equal to 90 means excellent grades). Please program to help Teacher Wang calculate the number of outstanding students.

Insert image description here

1. Analyze the problem

  1. Known: the scores of n individuals.
  2. Unknown: How many students have excellent grades.
  3. Relationship: greater than or equal to 90 indicates excellent performance.

2. Define variables

Define variables as needed based on the known and unknown of the analysis.
n: Achievements of n individuals.
a[100]: array, storing specific score values.
count: The number of students with excellent grades.

	//二、数据定义 
	int n,a[100],count=0; 

3. Enter data

Through traversal, student scores are entered in a loop.

//三、数据输入
	cin>>n;
	for(int i=0;i<n;i++){
    
    
		cin>>a[i];
	}

4.Data calculation

Greater than or equal to 90 means excellent results, just count the number.

//四、数据计算
if(a[i]>=90){
    
    
	count++;
}

5. Output results

#include<iostream>
using namespace std;
int main(){
    
    
	//一、分析问题
	//已知:n个人的成绩
	//未知:成绩优秀的同学有多少人
	//二、数据定义 
	int n,a[100],count=0; 
	//三、数据输入
	cin>>n;
	for(int i=0;i<n;i++){
    
    
		cin>>a[i];
		//四、数据计算
		if(a[i]>=90){
    
    
			count++;
		}
	}
	 

	//五、输出结果 
	cout<<count<<endl;
	return 0;	
}

Question Two: 1153 - Find the "Support Number"

Among a known set of integers, there is such a strange number. They are not the first or the last, and they happen to be larger than the adjacent numbers on the left and right. Can you find them?

Insert image description here

1. Analyze the problem

  1. Known: a set of integers
  2. Unknown: number of supports
  3. Relationship: A number that is greater than the adjacent numbers on the left and right

2. Define variables

Define variables as needed based on the known and unknown of the analysis.
n: n integers
a[100]: used to store n integer values.

	//二、数据定义 
	int n,a[100]; 

3. Enter data

Read from the keyboard.

	//三、数据输入 
	cin>>n;
	for(int i=0;i<n;i++){
    
    
		cin>>a[i];
	}

4.Data calculation

At the same time, it satisfies that it is larger than the adjacent numbers on the left and right. Note that there is no number on the left of the first number (index is 0), so the judgment should start from the second number (index is 1).

//四、数据计算 
	for(int i=1;i<n-1;i++){
    
    
		if(a[i-1]<a[i]&&a[i]>a[i+1]){
    
    
			
		}
	}

5. Output results

#include<iostream>
using namespace std;
int main(){
    
    
	//一、分析问题
	//已知:一组整数
	//未知:刚好都比左边和右边相邻的数大的数 
	
	//二、数据定义 
	int n,a[100]; 

	//三、数据输入 
	cin>>n;
	
	for(int i=0;i<n;i++){
    
    
		cin>>a[i];
	}
	//四、数据计算 
	for(int i=1;i<n-1;i++){
    
    
		if(a[i-1]<a[i]&&a[i]>a[i+1]){
    
    
			//五、输出结果 
			cout<<a[i]<<endl;
		}
	}
	
	return 0;	
}

Question three: 1156 - Excluding alien genes

After the Shenzhou spacecraft returned to Earth after completing its space exploration mission, astronaut Zhang San felt unwell and went to the hospital for examination. The doctor's diagnosis revealed that the genes in Zhang San's body had been changed, and the original human gene sequence had been infiltrated into the outside world. The planet has unknown alien genes, but the good news is that these alien genes all have a common feature, that is, the remainder of the square of the gene number divided by 7 is 1. They must be eliminated as soon as possible, otherwise it will harm the entire human race. hurry up.

Insert image description here

1. Analyze the problem

  1. Known: Human genetic sequence
  2. Unknown: Alien Gene
  3. Relationship: Whether the remainder of the square of the gene number divided by 7 is equal to 1

2. Define variables

Define variables as needed based on the known and unknown of the analysis.

//二、数据定义 
int n,a[200];

3. Enter data

Read from the keyboard.

//三、数据输入 
	cin>>n;
	
	for(int i=0;i<n;i++){
    
    
		cin>>a[i];
		
	}
	

4.Data calculation

The remainder of the square of the gene number divided by 7 is equal to 1, which is an alien gene.

//四、数据计算
if(a[i]*a[i]%7!=1){
    
    
			
}

5. Output results

The normal sequence after removing the abnormal gene, separated by spaces.

#include<iostream>
using namespace std;
int main(){
    
    
	//一、分析问题
	//已知:人体基因序列
	
	//未知:该基因序号的平方除以 7 的余数是否等于 1
	
	//二、数据定义 
	int n,a[200];
	
	//三、数据输入 
	cin>>n;
	
	for(int i=0;i<n;i++){
    
    
		cin>>a[i];
		//四、数据计算
		if(a[i]*a[i]%7!=1){
    
    
			//五、输出结果
			cout<<a[i]<<"\t";
		}
	}
	
	return 0;	
}

Question 4: 1155 - Find who is taller than the average height of the family

Find out who is taller than the average height of the family.
There are n people in the family. The input and output data are as follows: (the average height is kept to one decimal place).

Insert image description here

1. Analyze the problem

  1. Known: The height of the whole family.
  2. Unknown: Who is taller than the average height of the family.
  3. Relationship: average height = height/number of people in the family.

2. Define variables

Define variables as needed based on the known and unknown of the analysis.
ave: average height.

	//二、数据定义 
	int n,a[100];
	double ave=0;

3. Enter data

Read from the keyboard.
First add up the heights of the whole family.

//三、数据输入 
	cin>>n;
	for(int i=0;i<n;i++){
    
    
		cin>>a[i];
		ave+=a[i];
	}

4.Data calculation

The first line is the average height of the whole family (keep one decimal);
and determine whose height exceeds the average height of the whole family.

//四、数据计算 
	ave/=n;
	printf("AVE=%.1f\n",+ave);
	for(int i=0;i<n;i++){
    
    
		if(a[i]*1.0 > ave){
    
    
			
		}
	}

5. Output results

The second line contains several numbers, which are the height in centimeters of a person who is above the average height.

#include<iostream>
using namespace std;
int main(){
    
    
	//一、分析问题
	//已知:全家的身高
	//未知:谁的身高超过全家的平均身高
	
	//二、数据定义 
	int n,a[100];
	double ave=0;

	//三、数据输入 
	cin>>n;
	for(int i=0;i<n;i++){
    
    
		cin>>a[i];
		ave+=a[i];
	}
	
	//四、数据计算 
	ave/=n;
	printf("AVE=%.1f\n",+ave);
	for(int i=0;i<n;i++){
    
    
		if(a[i]*1.0 > ave){
    
    
			//五、输出结果 
			cout<<i+1<<":"<<a[i]<<" ";
		}
	}
	return 0;	
}

5. Practice

Question 1: 1231 - Distribution of test scores

The final exam is over. Xiao Ming’s Chinese teacher wants to know the distribution of scores in this exam. It mainly calculates the following data: average score, the total number of people with ≥ average score, and the total number of people with < average score. Please write a program to help Xiao Ming. Chinese teacher, let’s do the math!

Insert image description here
1231 - Solution to the distribution of test scores

Question 2: 1160 - Discount

The shopping mall has a big weekend discount, which stipulates that when the purchase exceeds 100 yuan, the portion exceeding 100 yuan will be discounted at 10%.
Xiao Xiong and his mother purchased a large number of items together. Can you help him calculate the final payment due?

Insert image description here
1160 - Solution to Discount Offer

Question Three: 1316 - Weighing Oranges

The school bought a large box of oranges, with m pieces (100≤m≤1000). The oranges were relatively uniform in size. The school wanted to weigh the total weight, but found that the large scale was broken and had not been repaired, and there was only a small spring scale. The school doesn't want to weigh them separately, as that would be too slow.
Xiao Ming thought of a way. Since the sizes of oranges are relatively uniform, n oranges can be taken out (5≤n≤20). The weight of these n oranges can be weighed by the spring scale. With the weight of these n oranges, Calculate how much an average orange weighs, and you'll know how much the entire box weighs.
Please write a program to read the total number of oranges m from the keyboard, the number of oranges n weighed by Xiao Ming and the weight of these n oranges, and calculate the approximate weight of the box of oranges (the result is retained to one decimal place).

Insert image description here
1316 - Solution to Orange Weighing Problem

Question 4: 1388 - Tao Tao picking apples

There is an apple tree in the yard of Tao Tao's house. Every autumn, the tree will bear 10 apples. When the apples are ripe, Tao Tao will run to pick them. Taotao has a 30 cm high bench. When she cannot pick apples directly with her hands, she will step on the bench and try again.
Now that we know the height of 10 apples from the ground and the maximum height Taotao can reach when she straightens her hands, please help Taotao calculate the number of apples she can pick. If she touches the apple, the apple will fall.

Insert image description here
1388 - Solution to Tao Tao's apple picking problem

Question 5: 1174 - Sum

Input n (1≤n≤5000) positive integers, each number is between 1 and 20000; it is required to sum the odd and even numbers in these n numbers respectively.
Insert image description here
1174 - Solution to sum problem

Question 6: 1397 - a perfect even number?

A perfect even number means that if a number itself is an even number, and the number has an even number of digits, and each digit of the number is also an even number, then the number can be called a perfect even number; for example: 28 is a perfect even number, and 246 No, because 246 is a 3-digit number.
Please program to find out which of the n numbers read from the keyboard are perfect even numbers and output them.

Insert image description here
1397 - A perfect even number? answer

Question 7: 1158 - Output odd and even numbers

Input n integers and display the odd and even numbers respectively (1<n<30).
Insert image description here
1158 - Output odd and even solutions

Question 8: 1354 - What is the probability of getting a certain number?

The teacher puts some ping pong balls into an opaque paper bag. Each ping pong ball has a number. After the ball is put in, Xiao Ming asks Xiao Ming to randomly pick one out. After the ball is put in and before Xiao Ming draws it, the teacher wants you to help program and calculate first. What is the probability of getting a certain number x?
For example: the teacher puts 5 balls into the bag, and the corresponding numbers are 2 3 2 4 2. Then the probability of getting the number 2 is 3/5 = 0.6, and the probability of getting the number 3 is 1/5 = 0.2 .

Insert image description here
1354 - What is the probability of getting a certain number? answer

Question 9: 1357 - Which manufacturer's parts are more standard?

In statistical description, variance is used to calculate the difference between each variable (observation) and the population mean. For example: two manufacturers, A and B, produce a certain part. A batch of parts is required to have the same size if the size is qualified. The more consistent the size, the better. Due to problems with the production process, the parts produced by the parts manufacturer cannot be exactly the same.
Insert image description here
Insert image description here
Insert image description here

1357 - Which manufacturer's parts are more standard? answer

6. Summary

The above is the entire content of this section. Arrays are still used a lot in actual applications, but it is not difficult to learn. The creation of static arrays, the use of array subscripts, and array traversal must be mastered. Dynamic arrays can be understood study.

Guess you like

Origin blog.csdn.net/qq_39180358/article/details/135338305