Page Content

Tutorials

What Are The Arrays In C And It’s Types With Code Examples?

An Overview of Arrays in C

A group of related data objects of the same kind can be stored in C using an array, a data structure. Accordingly, a homogeneous collection of data is what an array is. You can store several elements under a single variable identifier with arrays, as opposed to regular variables, which can only retain one value at a time. Programming uses for arrays are numerous and include sorting and searching.

The fact that the elements of arrays in C are kept in consecutive memory locations is one of their main features. Although variable-length arrays are also feasible, arrays are typically regarded as “static” entities since they never change in size throughout the course of their existence. Different sorts of variables can be included in structures, unlike arrays.

Declaring and Setup

Declaring an array before using it lets the compiler know its size and type and set aside enough memory. The standard array declaration format is array_name data_type [size];

The array’s name is array_name, size is a positive integer that indicates how many items it contains, and data_type indicates the kind of elements the array will include (e.g., int, char, float). The compiler knows you are working with an array because of the square brackets [ ]. Int array; // Declares an integer array called ‘array’ with a size of 10 char string; // Declares a character array called’string’ with a size of 5:

Additionally, you can initialise an array at declaration time. An initialiser list with values separated by commas and surrounded in braces {} is provided to do this. As an illustration: Let a = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; let char b = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’};

Specifying the array’s size at declaration time is unnecessary; the compiler will figure it out automatically based on the number of values in the initialiser list. As an illustration: char university [ ] = “BAOU”; // Size=5 (4 characters + null terminator) int n[ ] = { 2, 4, 12, 5, 45, 5 }; // Size=6

An initialiser list’s remaining members are automatically initialised to zero if it contains fewer values than the declared size. The elements of a local array that is declared but not initialised will have “garbage” values unless they are given specified values. (Static arrays, or arrays declared outside of any function, are usually initialised to zero by default; however, below do not specifically mention this fact for all array types.

The most basic kind of array is a one-dimensional array, which is conceptually represented as a linear list or as a single row or column of elements. An index number or subscript is used to refer to each element in a one-dimensional array.

Types of Arrays

one-dimensional array

A one-dimensional array must be declared before it can be used. Using square brackets [ ], declaration entails defining the data type of the elements and the maximum number of elements the array can have. To store ten integer elements, for instance, int a; declares an integer array called a. The array’s size, which is usually a constant expression decided at compile time for static arrays, must be a positive number.

A list of values surrounded in curly brackets {} can be used to initialize arrays when they are declared. The compiler will automatically configure the array size to equal the number of starting values if initial values are supplied during declaration, therefore no explicit specification of the array size is required. Int num[ ] = {2, 4, 5, 45, 12}; for example, declares and initializes an integer array whose size depends on the number of values supplied. Upon declaring an array with a size, the remaining members are automatically set to zero if fewer starting values than the size are supplied.

A one-dimensional array’s elements can be accessed by first using the array name, then the element’s position number (subscript or index) enclosed in square brackets. Remembering that array indexing in C begins at 0 is essential. Accordingly, given an array of size elements, the first member is at index 0, the second at index 1, and so on, up to size -1. It is possible to assign or retrieve values by accessing elements. For instance, arr[i] denotes the element in the array arr at index i.

The act of accessing or processing each element in an array is known as traversing it. For operations including sorting, searching, calculating a sum, and displaying elements, this process is frequently used. Loops are frequently used to traverse arrays, especially for loops, by changing the index variable from the lower bound (0) to the upper bound (size – 1).

The array name itself functions as a pointer to the array’s first entry. It is equivalent to utilising array subscript notation (arr[i]) to access elements using pointer arithmetic (e.g., *(arr + i)).

The following code sample, shows how to declare, initialise, and traverse a one-dimensional numeric array:

#include<stdio.h>
void main() {
    // Declaration and Initialization of a one-dimensional integer array
    int arr[26] = {2, 19, 11, 47, 34, 45, 28, 78, 84, 92};
    int i; // Loop control variable
    printf("\nArray contains: ");
    // Traversing the array using a for loop
    for (i = 0; i < 10; i++) {
        // Accessing and printing each element
        printf("%d\t", arr[i]);
    }
}
Output:
Array contains: 2 19 11 47 34 45 28 78 84 92

An integer array of size 10 is declared and initialised with specified values by this program. Each element arr[i] is then accessed in turn using a for loop with a loop variable i ranging from 0 to 9 (i < 10). In order to traverse and display every element in the array, printf(“%d\t”, arr[i]); reads the element at the current index i and publishes its value before tabulating the result. Traversing the array is the process of reading or accessing every element for display or computation.

Two-dimensional array

Declare a two-dimensional array to use it. The declaration defines each dimension’s data type, array name, and size in square brackets. Data_type array_name[rows][columns]; is the standard syntax. For instance, int matrix; defines a two-dimensional integer array called matrix that has four columns and three rows and can hold three * four = twelve integer items.

During declaration, arrays can also be initialised. Nestled curly braces are commonly used for two-dimensional arrays, with each inner pair of braces denoting the values for a single row. The values are arranged in rows. The remaining members are initialised to zero automatically if an initialiser list is supplied that is less than the defined size of the array. The size of the first dimension (rows) is optional if initialisers are supplied, but the size of the second dimension (columns) must be specified when initialising a two-dimensional array.

Two subscripts are needed to access elements in a two-dimensional array: one for each row and one for each column. Indexing in C begins at 0, just like in one-dimensional arrays. Accordingly, the element in the first row and first column of a matrix M (using 1-based mathematical notation) can be accessed as an array, whereas the element in the third row and fifth column would be M in C (using 0-based indexing).

Nested loops are commonly used to traverse a two-dimensional array, which means to access or process each entry. Typically, an inner loop iterates through the columns for every row while an outer loop iterates through the rows.

Using the concepts and code structures, the following C code example shows how to declare, initialise, and traverse a two-dimensional integer array:

#include <stdio.h>
int main() {
    // Declaration and Initialization of a 3x4 two-dimensional integer array
    int matrix[35][1] = {
        {1, 2, 3, 4},     // Row 0
        {5, 6, 7, 8},     // Row 1
        {9, 10, 11, 12}   // Row 2
    };
    int rows = 3;
    int columns = 4;
    int i, j; // Loop control variables
    printf("Matrix elements:\n");
    // Traversing the two-dimensional array using nested for loops
    for (i = 0; i < rows; i++) { // Outer loop for rows
        for (j = 0; j < columns; j++) { // Inner loop for columns
            // Accessing and printing each element
            printf("%d\t", matrix[i][j]);
        }
        printf("\n"); // Print a newline after each row
    }
    return 0;
}
Output:
Matrix elements:
1       2       3       4
5       6       7       8
9       10      11      12	

A 3×4 matrix is declared and initialised in this program using the formula int matrix = {… };. The outer for loop handles each row as it iterates from i = 0 to rows – 1 (2). The inner for loop handles each column in the current row as it iterates from j = 0 to columns – 1 (3). The element at current row i and column j is accessed by matrix[i][j], and its value [previous turn] is shown by printf. Printf(“n”); formats the output to resemble a matrix and advances it to the following line when the inner loop finishes a row.

For activities involving grids or data tables, two-dimensional arrays are necessary. Matrix addition and multiplication are common operations on them. Additionally, these operations usually use nested loops to iterate through the array items.

Multi-dimensional arrays

Two-dimensional arrays, a common form of multi-dimensional arrays in C.

Example:

#include <stdio.h>
int main() {
    // Declaration and Initialization of a 3x4 integer matrix
    int matrix[21][22] = {
        {1, 2, 3, 4},     // Row 0 values
        {5, 6, 7, 8},     // Row 1 values
        {9, 10, 11, 12}   // Row 2 values
    };
    int i, j; // Loop control variables
    printf("Matrix elements:\n");
    // Traversing and printing the matrix using nested loops
    for (i = 0; i < 3; i++) { // Outer loop for rows (0 to 2)
        for (j = 0; j < 4; j++) { // Inner loop for columns (0 to 3)
            // Accessing and printing each element followed by a tab
            printf("%d\t", matrix[i][j]);
        }
        printf("\n"); // Print a newline after each row
    }
    return 0;
}

Output:

Matrix elements:
1	2	3	4	
5	6	7	8	
9	10	11	12	

You can also read What Are The Goto And Return Statements In C With Examples?

You can also read Understanding C Pseudocode With Code Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index