C Language - Array (Notes)

Keywords: C#

  One-dimensional array

1. Array action: Arrays are often used to store data needed by programs.

2. Composition: Arrays consist of a series of elements of the same data type.

3. Array use: When an array is required, tell the compiler how many elements are contained in the array and what type of these elements are by declaring the array. The compiler correctly creates arrays based on this information. Types that can be used for ordinary variables, and array elements can be used.

/* Array declaration*/ 
int main(void) 
{
 float candy[365]; /* Array containing 365 float type elements */ 
 char code[12]; /*Array containing 12 char type elements*/
 int states[50]; /*Array containing 50 elements of type int */
 ... 
}
//Square brackets ([]) indicate that candy, code, and states are arrays, and the numbers in square brackets indicate the number of elements in the array.

  4. How to access arrays: To access elements in an array, use the array subscripts (also known as indexes) to represent the elements in the array. The number of the array element starts at 0, so candy[0] represents the first element of the candy array, and candy[364] represents the 365 element, which is the last element.

5. Initialize Array:

int main(void)
{
int powers[8] = {1,2,4,6,8,16,32,64}; /* This initialization is supported starting with ANSI C */
...
}
As shown above, a comma-separated list of values (enclosed in curly brackets) initializes the array, with values separated by commas. Spaces can be used between commas and values. From the above initialization, assign 1 to the first element of the array (powers[0]), and so on.
eg: demo program:
/* day_mon1.c -- Print days per month */ 
#include <stdio.h> 
#define MONTHS 12
int main(void) 
{
  int days[MONTHS] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 
  int index;
  for (index = 0; index < MONTHS; index++) {
  printf("Month %2d has %2d days.\n", index + 1, days[index]); }
  return 0;  
}
/*The output of the program is as follows: 
Month 1 has 31 days. 
Month 2 has 28 days. 
Month 3 has 31 days. 
Month 4 has 30 days. 
Month 5 has 31 days. 
Month 6 has 30 days. 
Month 7 has 31 days. 
Month 8 has 31 days. 
Month 9 has 30 days. 
Month 10 has 31 days. 
Month 11 has 30 days. 
Month 12 has 31 days.*/

#define MONTHS 12     Called a macro definition

Keep in mind that the number of an array element starts at 0 and exceeds the bounds called array subscript!!!

6. Use const Declare the role of arrays: Sometimes you need to make arrays read-only. In this way, the program can only retrieve values from the array and cannot write new values to the array. To create a read-only array, const should be used Declare and initialize arrays. Therefore, the above example The initialization array should be changed to: const int days [MONTHS] = {31,28,31,30,31,30,31,31,31,30,31,31}; This way, the program cannot modify the contents of the array while it is running.
Note: If the array is partially initialized, the remaining elements will be initialized to zero.
            If the number of items in the initialization list is more than the number of array elements, the compiler will treat it as an error.
7. If the number in square brackets is omitted when the array is initialized, the compiler determines the size of the array based on the number of items in the initialization list.

eg: demo program

/* day_mon2.c -- Let the compiler calculate the number of elements */
#include <stdio.h> 
int main(void) 
{
  const int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31 };
  int index; 
  for (index = 0; index < sizeof days / sizeof days[0]; index++) //index is the meaning of array subscript
  printf("Month %2d has %d days.\n", index + 1, days[index]); 
  return 0; 
}

Program explanation: sizeof is not a variable but an operator that gives the size of its object in bytes. So sizeof days is the size of the entire array in bytes, and sizeof day[0] is the size of the first element in the array in bytes. The size of the entire array divided by the size of a single element is the number of elements in the array.

8. How to assign an array element: After declaring an array, you can assign an array element with the aid of an array subscript (or index). For example, the following program segment assigns values to all elements of an array:

/* Assigning values to elements of an array */
#include <stdio.h>
#define SIZE 50 
int main(void) 
{
  int counter, evens[SIZE]; 
  for (counter = 0; counter < SIZE; counter++) 
  evens[counter] = 2 * counter; 
  ... 
}
Be careful: This code uses elements that loop through the array to assign values in turn. C Assigning an array as a unit to another array is not allowed, and assignments in the form of curly bracket lists are not allowed except for initialization.
The following code snippet demonstrates some incorrect assignments:
/* Some invalid array assignments */ 
#include <stdio.h>
#define SIZE 5 
int main(void) 
{
  int oxen[SIZE] = {5,3,2,8}; /* Initialization OK */
  int yaks[SIZE]; yaks = oxen; /* Not allow */
  yaks[SIZE] = oxen[SIZE]; /* subscript out of bounds */
  yaks[SIZE] = {5,3,2,8}; /* Not working */ 
···
}

Notice that the array subscript is out of bounds: the last element of the oxen array is oxen[SIZE-1], so both oxen[SIZE] and yaks[SIZE] exceed the end of both arrays.

9. Specify the size of the array:  

int n = 5; 
int m = 8; float a1[5]; // Yes? 
float a2[5*2 + 1]; //Yes?
float a3[sizeof(int) + 1]; //Yes? 
float a4[-4]; // No, the size of the array must be greater than 0 
float a5[0]; // No, the size of the array must be greater than 0 
float a6[2.5]; // No, the array size must be an integer 
float a7[(int)2.5]; // Yes, it has been cast to an integer constant 
float a8[n]; // Not allowed until C99 
float a9[m]; // Not allowed until C99
When referencing array elements, the following issues should be noted:
(1) The value of a subscript expression must be an integer, which can be an integer constant, an integer variable, or an expression whose result is an integer.
(2) Only elements in the array can be used individually, not the entire array (except character arrays).
(3) Array subscripts in C start with 0, so the range of subscripts for arrays is 0 to L-1, where L is the length of the array. Arrays are not cross-checked in C. Array a contains six elements, if there is a statement a[10]=2;, Errors are compiled, but can cause errors in other variables or programs.
 

2-D Array

1. General format for type descriptions of two-dimensional arrays: type specifier   Array name [Constant expression 1] [Constant expression 2]; Constant expression 1 defines the number of rows in the array and constant expression 2 defines the number of columns in the two-dimensional array x.

As defined, the two-dimensional array x consists of three rows, three columns and nine elements. Element row and column subscripts start at 0. The nine elements are
x[0] [0]  x[0] [1]  x[0] [2]
x[1] [0]  ×[1] [1]  x[1] [2]                                                                                                                      x[2] [0]  x[2] [1]  x[2] [2]

2. Initialization of a two-dimensional array:                                                                                                                            < 1. Assign initial values to all elements
    (1) Assign initial values by row. For example:int   a[2]   [3]={(1,2,3), (4,5,6)};
    (2) Assign values by storage structure, all data in one curly bracket.                                                                             For example:int   a[2][3]={1, 2, 3, 4, 5, 6};  / _Equivalent to line assignment/
   < 2. Initial values are given to some elements, and values of unassigned elements are 0.
    (1) Assign initial values by row. For example:int   a[2][3]={(1, 2, 3), (4)}; Then a[1][1],   The value of a[1][2] is 0.                                   (2) Assign values by storage structure, all data in one curly bracket. For example:int   al2][3]=(1,2,3,4);                                   Again a[1][1],   The value of a[1][2] is 0.
   < 3. Omit the number of rows in a two-dimensional array; do not omit the number of columns in a two-dimensional array.                                                                             (1) Assign initial values by row. For example:int   A[][3]={(1, 2, 3), (4)}; The system automatically defines the number of rows of array a to be 2.                       (2) According to the storage structure eye value, the number of rows of the array is the number of elements in curly brackets divided by the number of columns in the teaching group.                         For example:int   A[][3]={1,2,3,4}; Curly brackets contain four elements, rounded up by four-thirds, the system automatically defines the rows of array a       The number is 2.

3. Reference to a two-dimensional array: Once a two-dimensional array has been defined, each element of the two-dimensional array can be referenced in the following format.                   Array name [subscript] [subscript]     For example:
int c[3] [2];
c[1] [1]=2;
c[1] [2]=C[1] [1]*2;

Demonstrate a more complex code

/* rain.c -- Calculate annual total precipitation, annual average precipitation, and monthly average precipitation over 5 years */ 
#include <stdio.h>
#define MONTHS 12 //Year Months 
#define YEARS 5 //year 
int main(void) 
{// Initialize the array with precipitation data for 2010-2014 
  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 },
  { 8.5, 8.2, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 7.3 }, 
  { 9.1, 8.5, 6.7, 4.3, 2.1, 0.8, 0.2, 0.2, 1.1, 2.3, 6.1, 8.4 }, 
  { 7.2, 9.9, 8.4, 3.3, 1.2, 0.8, 0.4, 0.0, 0.6, 1.7, 4.3, 6.2 }, 
  { 7.6, 5.6, 3.8, 2.8, 3.8, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 5.2 }}; 
  int year, month;
  float subtot, total;
  printf(" YEAR RAINFALL (inches)\n");
  for (year = 0, total = 0; year < YEARS; year++) 
  { // Total precipitation for each year and month 
   for (month = 0, subtot = 0; month < MONTHS; month++) subtot += rain[year][month]; 
  printf("%5d %15.1f\n", 2010 + year, subtot); 
  total += subtot; // Total precipitation over 5 years 
  }
  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++)
  { // Total precipitation per month, 5 years 
   for (year = 0, subtot = 0; year < YEARS; year++) subtot += rain[year][month]; 
  printf("%4.1f ", subtot / YEARS); }printf("\n"); 662
  return 0; 
}
/*The following is the output of the program: 
YEAR RAINFALL (inches) 
2010 32.4 
2011 37.9 
2012 49.8 
2013 44.0 
2014 32.9 
The yearly average is 39.4 inches. MONTHLY AVERAGES: 
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 
7.3 7.3 4.9 3.0 2.3 0.6 1.2 0.3 0.5 1.7 3.6 6.7 */
Procedure explanation:   The program uses two nested for Cycle. No. 1 Nested for The inner loop of a loop, in year Traverse month without changing Calculate the total precipitation of a year; And the outer cycle, change year Value of, iterate over month , calculate 5 Total precipitation in the year. This nested loop structure is often used to handle two-dimensional arrays, the first of which is handled by a loop Subscript number, another loop handles the number of arrays 2 Subscripts:
for (year = 0, total = 0; year < YEARS; year++)
{ // Processing data for each year
for (month = 0, subtot = 0; month < MONTHS; month++)
...// Processing monthly data
...//Processing data for each year
}

The second nested for loop has the same structure as the first, but the inner loop traverses year and the outer loop traverses month. Remember that every time an outer loop is executed, the inner loop is fully traversed. Therefore, before changing the month, traverse through the year to get the average precipitation over a period of five years in a month, and so on:

for (month = 0; month < MONTHS; month++)
{ // Processing monthly data
for (year = 0, subtot =0; year < YEARS; year++)
...// Processing yearly data
...// Processing monthly data
}

Multidimensional Array

1. Declare a three-dimensional array: int box[10][20][30]: similar to a two-dimensional array.
Note: 3-nested loops are used for three-dimensional arrays and 4-nested loops for four-dimensional arrays. For other multidimensional arrays, and so on.

Posted by Iron Bridge on Sat, 04 Dec 2021 10:25:42 -0800