Learn arrays, this one is enough

"It is not the incident itself that hurts people, but his views on the incident." Dale Carnegie-"The Weakness of Human Nature"

Today, we invited a boss, don’t think he is just a person, he can hold more things than you.
Insert picture description here

What's the name of the boss, wait a minute, you can't say the boss's name casually

Introduction of the boss:

(Array) is a series of identical values ​​stored in order, which can be 10 char type characters or 15 int type values. That's right, the boss is an array. The boss still has many younger brothers. What is the last name of these younger brothers? There is a special name called Element. That's right, the entire array has an array name, and individual items or elements in the array are accessed through integer subscripts.

How to define an array:

**

int name[10];//说明可存储10个int类型整数的数组
char name[10];//说明可存储10个字符的数组

**

The boss is almost done, so next is to introduce the younger brother (the elements in the array). The kid is very powerful, it can be any data type.

We refer to the numbers used to identify array elements as subscripts, index (indice), or offset (offset). It should be noted that the subscript must be an integer. The integer in the subscript also represents how many elements there are in the array, and it must be counted from 0. There are also pitfalls in subscripts, because for fear of affecting the execution speed, the C compiler will not check whether the subscripts of the array are correct. And the elements of the array are sequentially stored in adjacent locations in the memory.

**

int name[10];//元素为name[0]~name[9]
name[10]=55;//这个便是错的,该数组元素不存在

**

Note: each int is 2 bytes, and char is 1 byte. By the way, expand the relationship between bit, word, byte and KB:

KB 1KB=1024B

MB 1MB=1024KB

GB 1GB=1024MB

TB 1TB=1024GB

The usage of int type array elements is similar to that of int type variables. For example, to read the int type variable name, you should write like this

**

scanf("%d",&name);//读取变量
scanf("%d",&name[n]);//读取数组

**

Yesterday we used a lot of for loops. Some friends told me that so many fors can be written independently. I personally do not recommend independent for loops. Combining for loops into one loop can make the program more compact, but we also have to follow the principle of modularity. Modularization is mainly to divide the program into some independent units, each unit performs a task, which can also improve the readability of the program. More importantly, the modularization makes the different parts of the program independent of each other, which facilitates the modification of the program in the future.

When we define the array, how to assign it:

**

int name[5]={
    
    1,2,3,4,5};
int name[5]={
    
    1,2,3,4};

**

If we look carefully, we will find the difference between the first line and the second line. The first line assigns 5 values ​​to name, but the second line only has 4 values. What if there is one missing? Don't be afraid, the compiler will add 0 for it, but it can only add 0.

Next, we will introduce arrays in more detail:

Initialize the array

Arrays are usually used to store data needed by programs. For example, an array containing 12 integer elements can store the number of days in 12 months. In this case, it is better to initialize the array at the beginning of the program. Do you know what a scalar variable is? Simply put, a variable that only stores a single value. Next we initialize this variable:

**

float flax=PI*2;/*PI已定义为宏*/
初始化数组:
int main()
{
    
    int name[5]={
    
    1,2,3,4,5};
...}

**

As shown above, we initialize the array with a comma-separated list of values ​​(enclosed in curly braces), each value is separated by a comma, and there can be spaces between the comma and the value. The above initialization is to assign 1 to the first element of the array (name[0]).
Let's show you a simple program:

**

#include<stdio.h>
int main()
{
    
     const int days[]={
    
    31,28,31,30,31,30,31,31,30,31};
int index;
for(index=0;index<sizeof day/sizeof days[0];index++)
printf("Month %2d has %d days.\n",index+1,days[index]);
return 0;
}

**

The results of the operation are shown in the figure:

Insert picture description here

Note the following points here:

NO.1 When we initialize the array above, we omit the numbers in square brackets, and the compiler will determine the size of the array according to the number of items in the initialization list.

NO.2 The Sizeof operator gives it the size (in bytes) of the operand. Using Sizeof days is the size of the entire array, and Sizeof day[0] is the size of the elements in the array. The size of the entire array divided by the size of a single element is the number of array elements.

Specify initializer

C99 has a new feature: designated initializer. Use this feature to initialize the specified array element.

For example, you can use square brackets in the initialization list to indicate the elements to be initialized:

int shu[6]={[5]=55};//把shu[5]初始化为55

Generally speaking, after initializing an element, the uninitialized elements will be set to 0. Take the following program as an example:

**

#include<stdio.h>
#define months 12
int main ()
{
    
     int days[months]={
    
    31,28,[4]=31,30,31,[1]=29};
int i;
for(i=0;i<months;i++)
{
    
    printf("%2d %d\n",i+1,days[i]);}
return 0;
}

**

Run as follows:
Insert picture description here

The program needs to pay attention to the following points (you need to think more):

NO.1 If there are more values ​​after the specified initializer, such as the fragment in the initialization list in this example: [4]=31,30,31, then these latter values ​​will be used to initialize 30 and 31.

NO.2 If the specified element is initialized again, the last initialization will replace the previous initialization. For example, at the beginning of the initialization list in the above program, days[1] is initialized to 28, but days[1] is initialized to 29 by the following designated initialization [1]=29.

Speaking of NO.3, what if the element size is not specified? as follows:

**

int shu[]={1,[6]=2};//该数组有7个元素
int shu[]={1,[6]=2,3};//该数组有8个元素

**

That is: the compiler will set the size of the array to a value large enough to be initialized.

Array boundary

When we use an array, we must prevent the array subscript from crossing the boundary. Simply put, it is to ensure that the subscript is a valid value. such as:

int you[20];
When using this array, you need to pay attention to the array subscript used in the program in the range of 0~19, and the compiler will not detect this error. I have also mentioned it before.

Therefore, using an out-of-bounds array index will cause the program to change the value of other variables. The results of running the program with different compilers may be different, and some may even cause the program to abort abnormally.

One thing to remember is that the numbering of array elements starts from 0. It is best to use symbolic constants to indicate the size of the array when declaring the array.

Array subscript

The C99 standard allows a new type of declaration:

int a1[n];//This was not allowed before c99.
This creates a new type of array called a variable length array. Referred to as VLA (C11 abandoned this initiative and set VLA as optional, not a language-required feature)

C99 introduced variable-length arrays mainly to make C a better numerical computing language.

Note: Variable-length arrays refer to arrays declared or defined with integer variables or expressions, not that the length of the array will change at any time. The length of variable-length arrays during their lifetime is also fixed.

Multidimensional Arrays

The above introduction of arrays is almost the same, so the following will introduce two-dimensional and multi-dimensional arrays. We can imagine a one-dimensional array as a row of data, a two-dimensional array as a data table, and a three-dimensional array as a stack of data tables.

Now use a project to explain the two-dimensional array:

If a weatherman wants to collect precipitation data for each month for 5 years, how does he represent the data? One solution is to create 60 variables, and each variable stores a data item. Obviously this method is too troublesome. Then we can use a two-dimensional array to solve, that is, to create a main array, the main array contains 5 elements, each element is an array containing 12 elements (each element represents a month).

Declare the array as follows:

float rain[5][12];
//内含5个数组元素的数组,每个数组元素内含12个float类型的元素
float rain[5][12]  //颜色部分是指rain是一个内含5个元素的数组;非颜色部分则是指一个含有12个float类型元素的数组。

This shows that the type of each element is float[12]. Simply put, each element of rain is an array containing 12 float type values. Then rain[0] is an array, the first element is rain[0][0], the second is rain[0][1], and so on.

The project code is as follows:

#include<stdio.h>
#define months 12//12个月
#define years 5//年数
int main()
{
    
    const float rain[years][months]={
    
    
{
    
    4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
{
    
    4.1,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
{
    
    4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
{
    
    4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
{
    
    4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
};//初始化时可省略内部的花括号,只要保证初始化的数值个数正确
int year,month;
float subtot,total;
printf("year    rainfall   (inches)\n");
for (year=0,total=0;year<years;year++)//每一年,各月的降水量总和
{
    
     for(month=0,subtot=0;month<months;month++)
subtot+=rain[year][month];
printf("%5d %15.1f\n",2015+year,subtot);
total+=subtot;} //5年的总降水量
printf("\nThe yearly average is %.1f inches.\n\n",total/years);
printf("monthly averages:\n\n");
printf("Jan Feb Mar Apr May Jun Jul Aug Sep Oct");
printf("Nov Dec\n");
for(month=0;month<months;month++){
    
    
for(year=0,subtot=0;year<years;year++)
subtot+=rain[year][month];
printf("%4.1f",subtot/years);
}
printf("\n");
return 0;
}

The results are as follows:

Insert picture description here

This program calculates the total annual precipitation, annual average precipitation and monthly average precipitation.

This program uses two nested for loops. The first is the inner loop of the nested for loop. When the year is unchanged, it traverses month to calculate the total precipitation in a certain year; the outer loop changes the value of year , Repeatedly traverse the month, calculate the total precipitation for five years.

Here we can see that processing two-dimensional arrays requires two-fold nested loops. Generally speaking, three-dimensional arrays require three-fold nested loops, and four-dimensional arrays require four-fold nested loops.

Many of the contents of the two-dimensional arrays we talk about are applicable to three-dimensional or multi-dimensional arrays. For example, declare a three-dimensional array as follows:

int name [3][3][3];

最后的话

I believe you have learned more or less about arrays. If you want to understand arrays better, it is recommended to read it several times. This is also the most important knowledge points in the array after reading books many times. Hope everyone has a better understanding of arrays after reading this article.

Public account: Programmer Bob
is a college student who is studying, welcome to pay attention and communicate with me!
Like and follow~ Thank you

Guess you like

Origin blog.csdn.net/m0_46259251/article/details/104706657