Mastering Arrays in C: From Basics to Advanced Techniques

An array in C language is a homogeneous set of data with a fixed size, whose elements are stored sequentially and contiguously in the computer memory. The size of the array is not limited, but its value must be determined at the time of definition and cannot be changed. Arrays are one of the most widely used data structures in C. In general, the array data structure in programming is a simple and fast way to store several different values ​​under a common name. Array in C language is also used for the same purpose, i.e. array is used to store a sequence of elements with the same data type and fixed size. Although an array is used to store a set of data, it is usually better to think of it as a set of variables that contain data of the same type.

What are arrays in C language?

An array in the C programming language is a collection of data elements of the same type that are stored in consecutive spaces in memory. The values ​​of the array can be of the main types of C language such as Int, Float and Char types, and of user-defined types such as structures or pointers. In C language, the type of the elements stored in the array must be the same as the data type of the array itself.

arrays in c


Creating arrays in C language

Arrays in C language must be defined like other variables before use. An array can be defined by specifying its name, element type, and dimension size. In this language, when we issue the command to define an array, the compiler selects and allocates a certain space of the memory block to the required size of the array.

In the box below, I have shown two types of general syntax for defining arrays in C language.

data_type array_name [size];
data_type array_name [size1] [size2]...[sizeN];

The displayed syntaxes are used to define one-dimensional and multi-dimensional arrays, respectively, from top to bottom. The above codes have used several different parameters. I introduced all those parameters in the list below.

  • data_type: This parameter specifies the type that the array values ​​should be. Array does not accept values ​​of other types.
  • array_name: We write the name of the array in this place.
  • size: This parameter indicates the size of the array. The array size is unlimited.
  • [size1]: The number of these parameters indicates the number of dimensions of the array. Arrays can have many dimensions, but usually do not use more than 3 dimensions. The character N indicates the number of dimensions of the array.

c array declaration

C language arrays are inherently static, that is, the space required to be used by these arrays in memory is determined and allocated at compile time.

In the box below, I have written a simple program in C language in which the process of defining an array is displayed.

// C Program to illustrate the array declaration
#include <stdio.h>
int main()
{
    // declaring array of integers
    int arr_int[5];
    // declaring array of characters
    char arr_char[5];
    return 0;
}

Array Initialization

In the C language, array initialization is the process in which some initial values ​​are assigned to a C variable. Pay attention to the fact that at the beginning of defining the array and allocating a certain amount of memory to it, the elements of the array contain redundant values. So we need to fill the array cells with meaningful values.

Array initialization at definition time

In this method, at the same time as the array, we also specify values ​​to fit in its houses. That is, at first, we assign several different elements to the array using the initialization list. "Initializer List" is a list made up of values ​​enclosed in open and closed braces {}  . These values ​​are separated by commas.

In the syntax below, I have shown the method of defining and setting the array at the same time.

data_type array_name [size] = {value1, value2, ... valueN};

In the image below, you can see the order in which the elements are placed in the houses of the array after initializing the array.

c array initialization


Array initialization and definition without specifying the size

If we assign values ​​to an array using an initializer list, we can bypass the step of defining the size of the array because in this way, the compiler can automatically detect the size of the array. In these cases, the compiler must look at the initialization list to infer the size of the array. In fact, the compiler considers the size of the array equal to the number of elements specified in the initialization list.

In the syntax below, I've shown how to initialize an array without specifying the size directly.

data_type array_name[] = {1,2,3,4,5};

The size of the above array is equal to 5. The compiler automatically looks at the number of elements and determines the size of the array.

Use loop to initialize array after definition

The array can be initialized after defining it. For this purpose, values ​​must be assigned to each element in the array separately. To assign values ​​to array elements, you can use for loop, while loop and do-while loop in programming.

In the box below, I have shown the syntax for array initialization using the for loop in programming.

for (int i = 0; i < N; i++) {
    array_name[i] = valuei;
}

According to the above syntax, in the following code I have implemented an example of array initialization in C programming language. The example below contains all three initialization methods - using for, while and do-while loops.

// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
    // array initialization using initialier list
    int arr[5] = { 10, 20, 30, 40, 50 };
    // array initialization using initializer list without
    // specifying size
    int arr1[] = { 1, 2, 3, 4, 5 };
    // array initialization using for loop
    float arr2[5];
    for (int i = 0; i < 5; i++) {
        arr2[i] = (float)i * 2.1;
    }
    return 0;
}

Accessing elements of arrays in C language

By using the index related to the houses of the array, we can access all the elements inside those houses. For this purpose, we use open and closed brackets in front of the array name and the index number corresponding to the desired value.

array_name [index];

It should be noted that indexing in arrays always starts with zero. It means that the first element is always in index number "0". Meanwhile, when "N" is equal to the number of array elements, the index number of the last element is equal to "N-1".

In the box below, I have implemented an example of accessing different elements in an array. To access the elements in the example below, I use array indices.

// C Program to illustrate element access using array
// subscript
#include <stdio.h>
int main()
{
    // array declaration and initialization
    int arr[5] = { 15, 25, 35, 45, 55 };
    // accessing element at index 2 i.e 3rd element
    printf("Element at arr[2]: %d\n", arr[2]);
    // accessing element at index 4 i.e last element
    printf("Element at arr[4]: %d\n", arr[4]);
    // accessing element at index 0 i.e first element
    printf("Element at arr[0]: %d", arr[0]);
    return 0;
}

After executing the above code, the following output is produced and displayed in the C programming language console.

Element at arr[2]: 35
Element at arr[4]: 55
Element at arr[0]: 15

Update array element

The value in all elements of the array can be updated according to the specified address. This is similar to accessing the value in that element using the index and the assignment operator ( =  ) .

array_name[i] = new_value;

Traversing the elements of arrays in C language

Traversal is the process of visiting all the elements of the desired data structure one by one. We use types of loops to navigate the elements of arrays in C language. In general, learning how to work with C language is one of the methods after which the path of understanding and teaching other programming languages ​​becomes much easier. Because this language is the origin of newer programming languages ​​such as C++, Java and C#.

In the box below, I have shown the method of traversing the array using a for loop.

for (int i = 0; i < N; i++) {
    array_name[i];
}

In the code above, i is the counter parameter for this traversal and N is the number of houses to be traversed. The value of N is less than the total number of elements in the array.

How to use arrays in C language?

In the following program, I have shown how to use array in C programming language.

// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
    // array declaration and initialization
    int arr[5] = { 10, 20, 30, 40, 50 };
    // modifying element at index 2
    arr[2] = 100;
    // traversing array using for loop
  printf("Elements in Array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

After executing the above code, the following output will be displayed in the console as a result.

Elements in Array: 10 20 100 40 50 

One-dimensional arrays

One-dimensional arrays are also known as "1D" arrays. The structure of this type of array in C language is in a form that has only one dimension. To understand this, first pay attention to the syntax used to define them.

array_name [size];

In the image below, you can see a complete example with a hypothetical number of elements of a one-dimensional array.

1d array

This array has a very simple structure. In the box below, I have implemented a simple example of using a one-dimensional array.

// C Program to illustrate the use of 1D array
#include <stdio.h>
int main()
{
    // 1d array declaration
    int arr[5];
    // 1d array initialization using for loop
    for (int i = 0; i < 5; i++) {
        arr[i] = i * i - 2 * i + 1;
    }
    printf("Elements of Array: ");
    // printing 1d array by traversing using for loop
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

After executing the above code, the following output is generated and displayed to the user.

Elements of Array: 1 0 1 4 9 

Two-dimensional arrays

A 2D or two-dimensional array in C language is an array that consists of exactly two dimensions. These arrays can be displayed as rows and columns. To display these arrays, we need two-dimensional screens.

I have shown the basic syntax of defining two-dimensional arrays in the box below.

array_name[size1] [size2];

There are three important parameters in the above syntax. I have introduced all these parameters in the list below.

  • array_name : This parameter represents the name of the array.
  • size1 : This parameter indicates the size of the first dimension of the array.
  • size2 : The last parameter shows the size of the second dimension of the array.

You can see a simple example of a two-dimensional array in the image below.

2d array

// C Program to illustrate 2d array
#include <stdio.h>
int main()
{
    // declaring and initializing 2d array
    int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
  printf("2D Array:\n");
    // printing 2d array
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    return 0;
}

After executing the above code, the following output is generated and displayed to the user.

2D Array:
10 20 30 
40 50 60

3D arrays

Three-dimensional arrays are another widely used array in programming. 3D arrays have exactly three different dimensions. To draw these arrays, we can use a set of two-dimensional arrays that are stacked on top of each other. In this way, the third dimension is created.

array_name [size1] [size2] [size3];

In this part of the post, I have implemented an example where a 3D array of size 2x2x2 is defined. Then I loop through this array and finally display it.

// C Program to illustrate the 3d array
#include <stdio.h>
int main()
{
    // 3D array declaration
    int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };
    // printing elements
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                printf("%d ", arr[i][j][k]);
            }
            printf("\n");
        }
        printf("\n \n");
    }
    return 0;
}

After executing the above code, the following output is generated and displayed to the user.

10 20 
30 40
50 60 
0 0

[post: @brook.dev
On Hive Blocjchain]

Sort:  

Congratulations @brook.dev! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You received more than 50 upvotes.
Your next target is to reach 100 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

LEO Power Up Day - December 15, 2024