C Language Arrays: The Magical Container for Organizing Data

C Language Arrays: The Magical Container for Organizing Data

Hello everyone! Today we are going to talk about a very important concept in C language—arrays. If you are learning C language, then arrays are definitely one of the fundamental knowledge you must master. Today we will learn about C language’sarrays—like putting data into “containers” to neatly arrange and manage large amounts of data! Once you master arrays, you can easily handle bulk data! 🚀

1. Introduction to Arrays: What is an Array?

An array can be understood asa collection of data of the same type, which is stored continuously in memory. It is like a row of neatly arranged lockers, where each locker has a number (index) and can store items (data).

Characteristics of Arrays:

  1. Same Type: All elements in an array must be of the same data type (e.g., all integers or all floating-point numbers)

  2. Continuous Storage: Array elements are stored continuously in memory

  3. Index Access: You can quickly access any element in the array using its index (subscript)

Why Do We Need Arrays?

Imagine a class with 30 students. If we want to record each student’s math score, defining variables one by one (like score1, score2, score3…score30) would be very cumbersome. This is where arrays come in handy!

// Without using arrays (cumbersome!)
int score1=90;
int score2=85;
int score3=92;
int score4=78;
int score5=88;
...
// Using arrays (concise!)
int scores[30] = {90, 85, 92, 78, 88,...};

When the amount of data reaches 100 or 1000, the advantages of arrays become even more apparent!

Basic Concepts of Arrays

  • Element: Each piece of data stored in the array (e.g., each student’s score)

  • Subscript: The number assigned to each element (starting from 0, like locker numbers)

  • Length: The number of elements in the array (which cannot be changed once defined)

2. One-Dimensional Arrays: Simple Linear Arrangement

A one-dimensional array is like a row of lockers, with only one row, and you can find the corresponding element using a unique subscript.

Definition and Initialization

Method 1: Define with Length and Initialize

int numbers[5] = {10, 20, 30, 40, 50};

Method 2: Length can be omitted during initialization (the compiler will calculate it automatically)

int ages[] = {15, 16, 14, 15, 17};

Method 3: Only initialize some elements (uninitialized ones will automatically be 0)

int scores[5] = {90, 85};  // Equivalent to {90, 85, 0, 0, 0}

Method 4: Define then Assign

float weights[3];
weights[0] =52.5;
weights[1] =48.3;
weights[2] =55.8;

Accessing and Modifying

Array elements are accessed using “array_name[subscript]”, and the array’s subscript starts from0, so for an array of length n, the subscript range is from 0 to n-1.

Example Code:

#include <stdio.h>

int main() {
        // Correct example: integer array
    int numbers[5] = {10, 20, 30, 40, 50};

    // Access elements
    printf("First element (index 0): %d\n", numbers[0]);  // 10
    printf("Third element (index 2): %d\n", numbers[2]);  // 30

    // Modify elements
    numbers[1] =200;  // Change the second element to 200
    printf("Modified second element: %d\n", numbers[1]);     // 200

    return 0;
}

Traversing Arrays

Traversing means accessing all elements in the array one by one, usually implemented with a for loop:

#include <stdio.h>

int main() {
    int scores[5] = {90, 85, 92, 78, 88};
    int sum=0;
     // Traverse all scores in the array
    for (int i=0; i<5; i++) {
        printf("Score of student %d: %d\n", i+1, scores[i]);
     }

    return 0;
}

Output:

Score of student 1: 90
Score of student 2: 85
Score of student 3: 92
Score of student 4: 78
Score of student 5: 88
Total score: 433
Average score: 86.6

Additionally, you can use loops to initialize array element values:

#include <stdio.h>

int main() {
    int s[10];
    int y[10];
    // Use loop to assign values to the array
    for (int i=0; i<10; i++) {
        s[i] =i+1; // Store 1-10
    }
    
    // Loop to input array element values
    for(int i=0;i<10;i++){
        scanf("%d",&y[i]);
    }
    
    // Use loop to print the array
    printf("s array element values:\n");
    for (int i=0; i<10; i++) {
        printf("%d ", s[i]);
    }
    
    printf("\ny array element values:\n");
    for (int  i=0; i<10; i++) {
        printf("%d ", y[i]);
    }
    return 0;
}

Common Problem Analysis

1. Sum and Average

Calculating the sum or average of all elements in an array is one of the most common array operations, which is very useful in scenarios like statistics of student scores and calculating average scores. The steps are as follows:

  1. Define a variable to store the sum (initial value is 0)

  2. Traverse the array, adding each element to the sum variable

  3. Average = Sum ÷ Number of Elements (note the need to retain decimal cases)

Example Code:

#include <stdio.h>

int main() {
    int scores[] = {85, 92, 78, 90, 88};
    int sum=0;
    int length=sizeof(scores) /sizeof(scores[0]);// Calculate array length

    for(int i=0; i<length; i++) {
        sum+=scores[i];// Accumulate sum
    }
    
    double avg=1.0*sum/length;// Average
    
    printf("Total score: %d\n", sum);
    printf("Average score: %.2lf\n", avg);// Retain two decimal places

    return 0;
}

2. Maximum and Minimum Values

Another common array operation is to find the maximum or minimum value in the array. This is useful in many practical applications, such as finding the highest and lowest scores.

The method to find the maximum or minimum value in the array is similar, with the following steps:

  1. Assumethe first element of the array is the extreme value (max or min)

  2. Traverse the array, comparing each element with the current extreme value

  3. If a larger (or smaller) element is found, update the extreme value

Example Code:

#include <stdio.h>

int main() {
    int scores[5] = {90, 85, 92, 78, 88};
    int max, min;       // Store maximum and minimum values
    int n=sizeof(scores) /sizeof(scores[0]);
    
    // Initialize: assume the first element is the extreme value
    max=scores[0];
    min=scores[0];
    
    // Traverse the array to find the extreme value
    for (int i=1; i<n; i++) {  // Start comparing from the second element
        // Check if a number greater than max appears
        if (scores[i] >max) {
            max=scores[i];// Update maximum value
        }
        
        // Check if a number less than min appears
        if (scores[i] <min) {
            min=scores[i];// Update minimum value
        }
    }
    
    printf("Score list:");
    for (int i=0; i<n; i++) {
        printf("%d ", scores[i]);
    }
    printf("\n");
    
    printf("Highest score: %d\t", max);
    printf("Lowest score: %d\n", min);
    
    return 0;
}

Output:

Score list: 90 85 92 78 88
Highest score: 92   Lowest score: 78

Notes on Arrays

1. Index Out of Bounds: Cannot access indices beyond the length of the array (e.g., for an array of length 5, the maximum index is 4)

int arr[3] = {1,2,3};
printf("%d", arr[3]);  // Error! Index out of bounds, may cause program crash

2. Fixed Length of Arrays: Once defined, the length cannot be changed

3. Array Name is an Address: The array name represents the address of the first element, and cannot be directly assigned

int a[3] = {1,2,3};
int b[3];
b=a;  // Error! Cannot directly assign arrays

3. Two-Dimensional Arrays: Array in Tabular Form

So far, we have discussed one-dimensional arrays, which are linear arrangements of data. However, sometimes we need to handle data in a tabular form, which requires the use of two-dimensional arrays.

A two-dimensional array is like a table or matrix, with rows and columns, and requires two subscripts (row subscript and column subscript) to access elements, just like seats in a classroom (which row and which column).

<span>a[0][0]</span> <span>a[0][1]</span> <span>a[0][2]</span>
<span>a[1][0]</span> <span>a[1][1]</span> <span>a[1][2]</span>
<span>a[2][0]</span> <span>a[2][1]</span> <span>a[2][2]</span>

Declaration

The syntax for declaring a two-dimensional array is:

data_type array_name[row_count][column_count];

For example:

int matrix[3][4]; // Declare a 3-row 4-column two-dimensional array

Note:When declaring a two-dimensional array in function parameters, the number of columns must be specified, but the number of rows can be omitted.

Initialization

Method 1: Complete Definition (3 rows 2 columns)

int matrix[3][2] = {
    {1, 2},   // Row 0
    {3, 4},   // Row 1
    {5, 6}    // Row 2
};

Method 2: Simplified Initialization (assign values in order)

int scores[2][3] = {90, 85, 92, 78, 88, 95};
// Equivalent to:
// {
//   {90, 85, 92},
//   {78, 88, 95}
// }

Method 3: Partial Initialization (uninitialized will be 0)

int table[2][2] = {{1}, {3}};
// Equivalent to:
// {
//   {1, 0},
//   {3, 0}
// }

Accessing and Traversing

Accessing a two-dimensional array requires specifying both the row subscript and column subscript, both starting from 0:

#include <stdio.h>

int main() {
    // Define a 3-row 3-column two-dimensional array (multiplication table)
    int m[3][3] = {
        {1, 2, 3},
        {2, 4, 6},
        {3, 6, 9}
    };
    // Access a single element (2nd row 3rd column, note that subscripts start from 0)
    printf("Element at 2nd row 3rd column: %d\n", m[1][2]);  // 6

    // Traverse the two-dimensional array (requires nested loops)
    printf("\nPrinting the entire multiplication table:\n");
    for (int i=0; i<3; i++) {  // Row loop
        for (int  j=0; j<3; j++) {  // Column loop
            printf("%d\t", m[i][j]);
        }
        printf("\n");  // New line after each row
    }

    return 0;
}

Output:

Element at 2nd row 3rd column: 6

Printing the entire multiplication table:
1	2	3	
2	4	6	
3	6	9	

Applications of Two-Dimensional Arrays

Two-dimensional arrays are particularly suitable for representing data with row and column structures:

  • Student score tables (each row is a student, each column is a subject)

  • Board games (like tic-tac-toe, gomoku boards)

  • Matrix operations (matrix addition and multiplication in mathematics)

4. Comprehensive Case Studies

Case 1: Statistics of Exam Scores

#include <stdio.h>

int main() {
    int scores[100];
    int s_count=0;
    int sum=0;
    float average;
    int max, min;

    printf("Please enter the number of students (up to 100): ");
    scanf("%d", &s_count);

    if(s_count>100) {
        printf("Exceeds maximum number of students allowed!\n");
        return 1;
    }

    // Input student scores and calculate total score
    for(int i=0; i<s_count; i++) {
        printf("Please enter the score of student %d: ", i+1);
        scanf("%d", &scores[i]);
        sum+=scores[i];
    }

    // Calculate highest and lowest scores
    max=scores[0];
    min=scores[0];

    for(int i=1; i<s_count; i++) {
        
        if(scores[i] >max) {
            max=scores[i];
        }
        if(scores[i] <min) {
            min=scores[i];
        }
    }

    average= (float)sum/s_count;

    // Output results
    printf("\nScore statistics results:\n");
    printf("Total score: %d\n", sum);
    printf("Average score: %.2f\n", average);
    printf("Highest score: %d\n", max);
    printf("Lowest score: %d\n", min);

    return 0;
}

Case 2: Tic-Tac-Toe Board Initialization

#include <stdio.h>

int main() {
    // Define a 3x3 tic-tac-toe board, initialized to spaces
    char board[3][3] = {
        {' ', ' ', ' '},
        {' ', ' ', ' '},
        {' ', ' ', ' '}
    };
    // Place pieces in some positions
    board[0][0] ='X';  // Place X in the first row first column
    board[1][1] ='O';  // Place O in the second row second column
    board[2][2] ='X';  // Place X in the third row third column

    // Print the board
    printf(" \t0\t1\t2\n");  // Column numbers
    printf("---------------------------\n");  // Column numbers
    for (int i=0; i<3; i++) {
        printf("%d:\t", i);  // Row number
        for (int j=0; j<3; j++) {
            printf("%c\t", board[i][j]);
        }
        printf("\n");
    }

return 0;
}

Output:

    0   1   2
--------------
0:  X   
1:      O  
2:          X

5. Fun Exercises

1. Array Reversal

Write a program to reverse an array containing 5 integers (e.g., [1,2,3,4,5] becomes [5,4,3,2,1]).

2. Find Element Position

Input n numbers and save them in an array, let the user input a number x, and the program finds the position of that number x in the array; if it does not exist, prompt “Not found”.[Example]

Input:

5
10 20 30 40 50
30

Output:

Position of 30 is 3

3. Transpose of a Two-Dimensional Array

Transpose a 2×3 two-dimensional array into a 3×2 array (rows become columns, columns become rows).[Example]

Input:

1 2 3
4 5 6

Output:

1 4
2 5
3 6

4. Enhanced Score Statistics

Define a 3×4 two-dimensional array representing the scores of 3 students in 4 subjects, and calculate:

  • The average score of each student

  • The average score of each subject

  • The overall average score of all students

Conclusion

Having learned about arrays as “data containers”, in the next issue we will explore more advancedstring processing techniques! Learn how to manipulate character arrays, use string function libraries, and implement interesting text processing programs!

Coding Philosophy:

Arrays are powerful tools for handling bulk data, remember:1️⃣ Index starts from 02️⃣ Loops are the best partners for arrays3️⃣ Two-dimensional arrays are row-first then column

Arrays are one of the most basic and important data structures in C language. Mastering arrays will lay a solid foundation for learning more complex data structures (like linked lists, trees, etc.) in the future.

I hope this article helps you understand the concept and usage of arrays in C language. If you have any questions, feel free to leave a comment for discussion! Don’t forget to practice the exercises we provided; only by writing more code can you truly master programming skills.

Programming Tip: Learning programming is like learning a new language; reading more, writing more, and practicing more is the fastest way to improve. Don’t be afraid of encountering problems; the process of debugging is also a learning process!

Leave a Comment