C Arrays

C Arrays

In C programming, arrays are like containers that help us store lots of things of the same type together. Imagine you have a bunch of numbers, characters, or other stuff you want to keep together neatly – arrays are your go-to tool. They’re simple to use, and in this guide, we’ll show you how to use them step by step. Whether you’re just starting out or you’re already a pro, you’ll find this introduction to C arrays helpful and easy to follow. Let’s get started

What is Array in C?

An array in C is a collection of data items of the same type, stored in a fixed-size, consecutive block of memory. It’s versatile and can store various data types, including primitive types like int, char, and float, as well as more complex types like pointers and structures. Arrays are a fundamental data structure in C, enabling efficient storage and retrieval of data.

C Array Declaration

In C, you need to declare an array just like any other variable before you can use it. When declaring an array, you specify its name, the data type of its elements, and the size of its dimensions. When the array is declared, the compiler allocates a block of memory of the specified size to hold the elements of the array. This allocation of memory allows you to store and manipulate data efficiently within the array.

Syntax

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

N referred as the Number of dimensions

Example

// 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;
}

C Array Initialization

Initialization in C involves assigning initial values to variables. When an array is declared or memory is allocated for it, the elements of the array typically contain garbage values. To make the array useful and meaningful, you need to initialize it with specific values. There are multiple methods available for initializing arrays in C, allowing you to set the initial content to values that are relevant to your program’s logic and requirements.

1. Array Initialization with Declaration

In this method, you initialize the array when you declare it. You provide an initializer list, which is a collection of values enclosed within curly braces {} and separated by commas. These values are used to set the initial values of the array’s elements. This approach is convenient and efficient, especially when you know the exact values that your array should contain right from the start.

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

2. Array Initialization with Declaration without Size

When you initialize an array using an initializer list in C, you can omit specifying the size of the array explicitly because the compiler can automatically determine the size based on the number of elements in the initializer list. This feature simplifies the process of declaring and initializing arrays and ensures that you don’t have to manually count the elements to determine the array’s size.

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

The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)

This approach allows you to set specific values for each element of the array and is particularly useful when you need to calculate or retrieve values dynamically. You can use loops like for, while, or do-while to iterate through the array and assign values as needed.’

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

Example



// 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;
}

Access Array Elements

To access a specific element of an array, you use the array subscript operator [] followed by the index value of the element you want to access. The index value represents the position of the element in the array, and it starts from 0 for the first element.

array_name [index];

In C, array indexing always starts with 0. This means that the first element of an array is at index 0, and the last element is at index N – 1, where N is the total number of elements in the array. It’s a fundamental concept to keep in mind when working with arrays in C, as it ensures that you access the correct elements in the array and avoid off-by-one errors. For example, if you have an array with 5 elements, the indices of the elements will be 0, 1, 2, 3, and 4.

Example of Accessing  Array Elements using Array Subscript Operator


// 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;
}

Output

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

Update Array Element

To update the value of an element at a specific index in an array in C, you use the array subscript operator [] to access the element, and then you can use the assignment operator = to assign a new value to it.

array_name[i] = new_value;

C Array Traversal

Traversal is the process of visiting and inspecting each element of a data structure. In the context of C arrays, traversal involves going through each element of the array one by one. To accomplish this, you can use loops, such as for, while, or do-while, to iterate through the elements of the array and perform actions on them.

Array Traversal using for Loop

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

How to use Array in C?

// 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;
}

Output

Elements in Array: 10 20 100 40 50 

Types Of Array

There are 2 types of arrays based on the dimension

  1. One Dimensional Arrays (1D Array)
  2. Multidimensional Arrays

1. One Dimensional Array in C

One-dimensional arrays in C, often referred to as 1-D arrays, are arrays that have only one dimension. These arrays store elements in a single line or row, and each element can be accessed using a single index. One-dimensional arrays are the most common type of arrays in C and are used to store collections of elements of the same data type in a linear sequence.

For example, an integer array of size 5 is a one-dimensional array that can hold five integer values in a linear fashion, and you can access each element using indices like array[0], array[1], array[2], array[3], and array[4].

Syntax

array_name [size];

Example


// 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;
}

Output

Elements of Array: 1 0 1 4 9 

Array of Characters (Strings)

In C, strings are just words or sentences made up of characters. We store these strings as arrays of characters, where each character is like a letter in a row. At the end of the string, we put a special character called NULL to say, “This is the end.” So, in C, strings are really just arrays of characters with a special marker at the end.


// C Program to illustrate strings
#include <stdio.h>
 
int main()
{
 
    // creating array of character
    char arr[6] = { 'S', 'k', 'i', 'l', 'l', '\0' };
 
    // printing string
    int i = 0;
    while (arr[i]) {
        printf("%c", arr[i++]);
    }
    return 0;
}

Output

Skill

2. Multidimensional Array in C

Multi-dimensional arrays in C are arrays that have more than one dimension. Two of the most commonly used multi-dimensional arrays are 2D arrays and 3D arrays. While it’s possible to declare arrays with more than three dimensions, they tend to become very complex and can occupy a significant amount of memory. As a result, such high-dimensional arrays are often avoided in practice due to their complexity and the resources they require.

A. Two-Dimensional Array in C

A two-dimensional array, often referred to as a 2D array in C, is an array that has precisely two dimensions. These arrays can be thought of as a grid or table, where data is organized in rows and columns on a two-dimensional plane. This structure is useful for representing data that naturally fits into a grid-like format, such as matrices, tables, or images.

Syntax

array_name[size1] [size2];

Example

// 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;
}

Output

2D Array:
10 20 30 
40 50 60

B. Three-Dimensional Array in C

A three-dimensional array, commonly known as a 3D array in C, consists of exactly three dimensions. You can imagine it as a collection of 2D arrays stacked on top of each other, creating a third dimension. This structure is valuable for representing data that has three levels of organization or can be thought of as layers within layers. It’s especially useful in applications like 3D graphics, where you’re dealing with data that extends in three directions.

Syntax

array_name [size1] [size2] [size3];

Example

// 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;
}

Output

10 20 
30 40 

 
50 60 
0 0 

Relationship between Arrays and Pointers

The array name effectively acts as a constant pointer to the first element of the array. You can use this pointer to access and manipulate array elements.

When you pass an array as an argument to a function, it “decays” into a pointer to its first element. This means that the function receives a pointer to the array’s data, not a full copy of the array. This can be more efficient for working with large arrays.


// C Program to demonstrate the relation between arrays and
// pointers
#include <stdio.h>
 
int main()
{
 
    int arr[5] = { 10, 20, 30, 40, 50 };
    int* ptr = &arr[0];
 
    // comparing address of first element and address stored
    // inside array name
    printf("Address Stored in Array name: %p\nAddress of "
           "1st Array Element: %p\n",
           arr, &arr[0]);
 
    // printing array elements using pointers
    printf("Array elements using pointer: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", *ptr++);
    }
    return 0;
}

Output

Address Stored in Array name: 0x7ffce72c2660
Address of 1st Array Element: 0x7ffce72c2660
Array elements using pointer: 10 20 30 40 50 

Passing an Array to a Function in C

In C, when you pass an array to a function, it indeed “decays” into a pointer to its first element. This means that the function receives a pointer to the starting memory location of the array, not a full copy of the array. This behavior is why you often see function parameters declared as pointers when they are meant to accept arrays as arguments.


// C Program to pass an array to a function
#include <stdio.h>
 
void printArray(int arr[])
{
    printf("Size of Array in Functions: %d\n", sizeof(arr));
    printf("Array Elements: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ",arr[i]);
    }
}
 
// driver code
int main()
{
 
    int arr[5] = { 10, 20, 30, 40, 50 };
 
    printf("Size of Array in main(): %d\n", sizeof(arr));
    printArray(arr);
    return 0;
}

Output

Size of Array in main(): 20
Size of Array in Functions: 8
Array Elements: 10 20 30 40 50

Return an Array from function In C

In C, a function can indeed return only a single value. However, when you need to return multiple values or elements, you can use pointers effectively. One common approach is to return an array from a function by returning a pointer to its first element. This allows you to effectively pass back a collection of values to the calling code.

// C Program to return array from a function
#include <stdio.h>
 
// function
int* func()
{
    static int arr[5] = { 1, 2, 3, 4, 5 };
 
    return arr;
}
 
// driver code
int main()
{
 
    int* ptr = func();
 
    printf("Array Elements: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", *ptr++);
    }
    return 0;
}

Properties of Array in C

1. Fixed Size

In C, arrays are fixed in size and must have their size known at compile time. Once declared, you can’t change their size during program execution. Arrays are allocated statically, meaning the memory for the entire array is reserved from the start.

2. Homogenous Collection

Arrays can only store elements of a single data type. While you can have as many elements as needed, all elements within an array must be of the same data type. This constraint ensures that arrays are homogeneous collections, providing consistent and efficient storage for a specific type of data.

3. Indexing In Array

In C, the array index always starts from 0. This means that the index of the first element in an array is 0, and the index of the last element is one less than the total number of elements in the array, which is typically represented as N – 1. Understanding this indexing convention is crucial for correctly accessing and manipulating elements in C arrays.

4. Dimensions of an Array

In an array, a dimension represents the number of indexes needed to access an individual element within the array. It’s essentially the number of directions in which you can extend or traverse the array. For example, in a one-dimensional array, you need only one index to access elements. In a two-dimensional array, you require two indices (row and column) to pinpoint an element. Each dimension adds an extra level of organization and access to the array’s elements.

5. Contiguous Storage

In C, all elements in an array are stored sequentially and continuously in memory. This contiguous storage is a fundamental property of arrays, and it enables efficient random access to individual elements within the array. Because elements are stored one after another, the memory locations for each element can be easily calculated, allowing for direct access using indices. This property makes arrays well-suited for tasks that require quick and direct access to elements, such as searching or sorting algorithms.

6. Random Access

Arrays in C indeed provide random access to their elements. This means that you can access any element within an array directly by using its index, and the time it takes to access an element is constant, or O(1), complexity. In other words, regardless of the array’s size, you can access any element with the same efficiency, making arrays an efficient data structure for tasks that require quick and direct access to elements by their positions.

7. No Index Out of Bounds Checking

In C and C++, there is no built-in index out-of-bounds checking for arrays. The compilers do not automatically check whether you’re accessing an element beyond the valid range of the array. While this allows for more efficient code, it also means that if you access an element outside the array’s bounds, it can lead to undefined behavior, which may manifest as unexpected output, crashes, or memory corruption.

Developers need to be careful when working with arrays in C/C++ to ensure that they do not access elements outside the defined range of the array to prevent such issues. It’s a responsibility placed on the programmer to write code that respects the array’s boundaries.

// This C program compiles fine
// as index out of bound
// is not checked in C.
 
#include <stdio.h>
 
int main()
{
    int arr[2];
 
    printf("%d ", arr[3]);
    printf("%d ", arr[-2]);
 
    return 0;
}

Output

211343841 4195777 

Example- The program given below-compiles fine and shows just a Warning

#include <stdio.h>
int main()
{
 
    // Array declaration by initializing it 
    // with more elements than specified size.
    int arr[2] = { 10, 20, 30, 40, 50 };
 
    return 0;
}

Output

prog.c: In function 'main':
prog.c:7:25: warning: excess elements in array initializer
  int arr[2] = { 10, 20, 30, 40, 50 };
                         ^
prog.c:7:25: note: (near initialization for 'arr')
prog.c:7:29: warning: excess elements in array initializer
  int arr[2] = { 10, 20, 30, 40, 50 };
                             ^
prog.c:7:29: note: (near initialization for 'arr')
prog.c:7:33: warning: excess elements in array initializer
  int arr[2] = { 10, 20, 30, 40, 50 };
                                 ^
prog.c:7:33: note: (near initialization for 'arr')

Examples of Array in C

We will use scanf() and print() functions in order to get the input and print output for the array.

// C Program to perform input and output on array
#include <stdio.h>
 
int main()
{
 
    // declaring an integer array
    int arr[5];
 
    // taking input to array elements one by one
    for (int i = 0; i < 5; i++) {
        scanf("%d", &arr[i]);
    }
 
    // printing array elements
    printf("Array Elements: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Input

5 7 9 1 4

Output

Array Elements: 5 7 9 1 4

Example 2: C Program to print the average of the given list of numbers

To calculate the average of numbers stored in an array through this program

// C Program to the average to two numbers
#include <stdio.h>
 
// function to calculate average of the function
float getAverage(float* arr, int size)
{
 
    int sum = 0;
    // calculating cumulative sum of all the array elements
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
 
    // returning average
    return sum / size;
}
 
// driver code
int main()
{
 
    // declaring and initializing array
    float arr[5] = { 10, 20, 30, 40, 50 };
    // size of array using sizeof operator
    int n = sizeof(arr) / sizeof(float);
 // printing array elements
    printf("Array Elements: ");
    for (int i = 0; i < n; i++) {
        printf("%.0f ", arr[i]);
    }
 
    // calling getAverage function and printing average
    printf("\nAverage: %.2f", getAverage(arr, n));
    return 0;
}

Output

Array Elements: 10 20 30 40 50 
Average: 30.00

Example 3: C Program to find the largest number in the array

// C Program to find the largest number in the array.
#include <stdio.h>
 
// function to return max value
int getMax(int* arr, int size)
{
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (max < arr[i]) {
            max = arr[i];
        }
    }
    return max;
}
 
// Driver code
int main()
{
 
    int arr[10]
        = { 135, 165, 1, 16, 511, 65, 654, 654, 169, 4 };
 
    printf("Largest Number in the Array: %d",
           getMax(arr, 10));
 
    return 0;
}

Output

Largest Number in the Array: 654

Advantages Of Array In C

  1. Random and Fast Access: Arrays allow for quick and direct access to elements using the array index. This property makes it efficient to access any element by its position within the array.
  2. Concise Code: Arrays enable the storage of multiple elements using just one data structure, leading to more compact and efficient code compared to using individual variables for each element.
  3. Simplified Traversal: You can traverse through all elements of an array conveniently using a single loop, simplifying tasks that involve processing or examining each element.
  4. Ease of Sorting: Arrays make sorting operations more straightforward. You can implement sorting algorithms with fewer lines of code because of the uniform structure of arrays, which makes comparisons and swaps more manageable.

Disadvantages of Array in C

  1. Fixed Size: Arrays in C have a fixed size, which means you must decide and declare the number of elements you need at compile time. This lack of dynamic sizing can be a limitation when you need to work with variable amounts of data.
  2. Not Dynamic: Unlike data structures like linked lists, arrays are not dynamic, meaning their size cannot be changed during program execution. Once an array is declared, its size remains constant.
  3. Costly Insertion and Deletion: Inserting or deleting elements in the middle of an array can be costly in terms of time and memory because it often requires shifting elements to accommodate the change. This can lead to performance overhead in certain situations.

FAQ- C Arrays

Q1.What is an array in C with example?

Ans. To create an array in C, specify the data type (like int) and give it a name followed by square brackets []. You can insert values into it using curly braces {} with a comma-separated list. For instance, int myNumbers[] = {25, 50, 75, 100}; creates an array of four integers with the specified values.

Q2. What is 1 array in C?

Ans. A one-dimensional array in C is like a list where each element holds a single value, whether it’s an int, char, float, or another data type. To declare a one-dimensional array, you usually need to specify three things: the data type, the array name, and the number of elements that the array can contain. This combination defines the array’s type and size, allowing you to work with lists of values efficiently.

Q3. What is the syntax of an array?

Ans. For 1D arrays: int arr[n];
For 2D arrays: int arr[m][n];
In these syntax examples, int represents the data type, arr is the name of the array, and n and m are the sizes or dimensions of the array. This syntax is used to declare and define arrays in C, specifying their data type and size

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment