CS Engineering Gyan

Arrays in C

Imagine trying to store the weekly view counts for a YouTube channel using seven completely separate variables, one for each day. Not only would this quickly become unmanageable as the amount of data grows, but processing all seven values together, such as calculating a total or an average, would require repeating similar code seven separate times. Arrays solve this exact problem by allowing a group of related values to be stored under a single name.

An array is one of the most fundamental data structures in programming, and C's implementation of arrays forms the foundation for understanding more advanced structures you will encounter later, including strings, which are themselves simply arrays of characters. Learning arrays thoroughly also prepares you well for working with pointers, since arrays and pointers are closely related in C.

In this tutorial, you will learn what an array is, how to declare and initialize one-dimensional arrays, how to access and modify individual elements, how multidimensional arrays extend this idea into rows and columns, and how arrays can be passed to functions for further processing.


What is an Array?

An array is a collection of elements, all of the same data type, stored in contiguous memory locations and accessed using a single variable name combined with an index number. Instead of creating separate variables for each related value, an array groups them together, making it far easier to store, access, and process large amounts of similar data.

Example

#include <stdio.h>

int main() {

    int weeklyViews[5] = {1500, 1800, 2100, 1950, 2200};

    printf("Views on day 3: %d", weeklyViews[2]);

    return 0;

}

Output

Views on day 3: 2100

Here, a single array named weeklyViews stores five related values together, and any individual value can be accessed using its position, referred to as an index, inside square brackets.


Declaring and Initializing Arrays

Declaring an array involves specifying its data type, a name, and the number of elements it should hold. Initialization can happen at the same time as declaration, or values can be assigned to individual elements afterward.

Syntax

dataType arrayName[size];

Example

#include <stdio.h>

int main() {

    int ratings[4];

    ratings[0] = 5;

    ratings[1] = 4;

    ratings[2] = 5;

    ratings[3] = 3;

    printf("First rating: %d", ratings[0]);

    return 0;

}

Output

First rating: 5

In this example, the array is first declared with a fixed size of four elements, and each individual position is assigned a value separately afterward using its index.


Array Indexing

One of the most important concepts to understand about arrays in C is that indexing always begins at zero rather than one. This means the first element of an array is accessed using index 0, and the last element is accessed using an index that is one less than the total size of the array.

Array Size Valid Index Range
5 0 to 4
10 0 to 9

Attempting to access an index outside this valid range does not necessarily produce an error message during compilation, but it results in undefined behavior, since the program would be reading or writing memory outside the space actually reserved for the array.


Processing Arrays with Loops

Arrays and loops work together naturally, since a loop can iterate through every index of an array, allowing repeated operations to be performed on each element without writing separate code for every single position.

Example

#include <stdio.h>

int main() {

    int weeklyViews[5] = {1500, 1800, 2100, 1950, 2200};

    int total = 0;

    int i;

    for (i = 0; i < 5; i++) {

        total += weeklyViews[i];

    }

    printf("Total weekly views: %d", total);

    return 0;

}

Output

Total weekly views: 9550

This example demonstrates one of the most common patterns in C programming, using a for loop to visit every element of an array in sequence and accumulate a result, such as a running total.


Finding the Maximum Value in an Array

Another common task involving arrays is searching through the elements to find a particular value, such as the largest or smallest number in a dataset.

Example

#include <stdio.h>

int main() {

    int dailyUploads[6] = {2, 4, 1, 5, 3, 4};

    int maxUploads = dailyUploads[0];

    int i;

    for (i = 1; i < 6; i++) {

        if (dailyUploads[i] > maxUploads) {

            maxUploads = dailyUploads[i];

        }

    }

    printf("Highest number of uploads in a single day: %d", maxUploads);

    return 0;

}

Output

Highest number of uploads in a single day: 5

This pattern starts by assuming the first element is the largest, then compares every remaining element against the current maximum, updating it whenever a larger value is found.


Multidimensional Arrays

While a one-dimensional array represents a simple list of values, a multidimensional array organizes data into rows and columns, similar to a table or grid. The most common form is the two-dimensional array, which is particularly useful for representing structured data such as a grid of scores or a small table of values.

Syntax

dataType arrayName[rows][columns];

Example

#include <stdio.h>

int main() {

    int scores[2][3] = {

        {85, 90, 78},

        {88, 76, 95}

    };

    printf("Score of student 2, subject 3: %d", scores[1][2]);

    return 0;

}

Output

Score of student 2, subject 3: 95

Here, the array represents two students and three subjects, and a specific score is accessed by providing both a row index and a column index, corresponding to the desired student and subject.


Traversing a Two-Dimensional Array

Just as a one-dimensional array is typically processed using a single loop, a two-dimensional array is usually processed using two nested loops, one handling the rows and the other handling the columns.

Example

#include <stdio.h>

int main() {

    int scores[2][3] = {

        {85, 90, 78},

        {88, 76, 95}

    };

    int row, col;

    for (row = 0; row < 2; row++) {

        for (col = 0; col < 3; col++) {

            printf("%d ", scores[row][col]);

        }

        printf("\n");

    }

    return 0;

}

Output

85 90 78

88 76 95

The outer loop moves through each row, while the inner loop moves through each column within that particular row, together visiting every single element in the entire two-dimensional array exactly once.


Passing Arrays to Functions

Arrays can be passed to functions, allowing calculations and processing logic to be separated from the main program, which keeps code organized and reusable. When an array is passed to a function in C, it is effectively passed by reference, meaning the function works directly with the original array rather than a separate copy.

Example

#include <stdio.h>

int calculateAverage(int arr[], int size) {

    int sum = 0;

    int i;

    for (i = 0; i < size; i++) {

        sum += arr[i];

    }

    return sum / size;

}

int main() {

    int watchTimes[4] = {6, 8, 5, 9};

    int average = calculateAverage(watchTimes, 4);

    printf("Average watch time: %d minutes", average);

    return 0;

}

Output

Average watch time: 7 minutes

Notice that the function also receives the size of the array as a separate parameter, since an array passed to a function does not automatically carry information about its own length.


Arrays and Memory

Concept Explanation
Contiguous Storage All elements of an array are stored next to each other in memory, which allows fast access using an index.
Fixed Size The size of a standard array is fixed at the time of declaration and cannot be changed afterward.
Array Name as Address The name of an array represents the memory address of its first element, which is why array names behave differently from ordinary variables in certain contexts.

Best Practices When Working with Arrays


Common Mistakes Beginners Make

Mistake Correct Practice
Forgetting that array indexing starts at zero rather than one. Remember that the first element is always accessed using index 0, not 1.
Accessing an index beyond the array's declared size. Always ensure loop conditions and manual indices stay within the valid range of the array.
Assuming a function automatically knows the size of a passed array. Always pass the array's size as a separate parameter alongside the array itself.
Confusing rows and columns when working with multidimensional arrays. Double-check the order of indices, remembering that the first index typically refers to the row and the second to the column.

Frequently Asked Interview Questions

  1. What is an array in C?
    An array is a collection of elements of the same data type stored in contiguous memory locations and accessed using a single name with an index.
  2. What index does array numbering start from in C?
    Array indexing in C always starts from zero, meaning the first element is accessed using index 0.
  3. Can the size of an array be changed after it has been declared?
    No, a standard array in C has a fixed size that cannot be changed once it has been declared.
  4. What is a multidimensional array?
    A multidimensional array organizes data into multiple dimensions, such as rows and columns, commonly used to represent tables or grids of related values.
  5. How is an element accessed in a two-dimensional array?
    An element is accessed using two indices, one representing the row and the other representing the column of the desired value.
  6. What happens if a program accesses an array index outside its valid range?
    This results in undefined behavior, since the program would be accessing memory that was not actually reserved for the array.
  7. Why does a function need the array's size as a separate parameter?
    When an array is passed to a function, information about its total size is not automatically included, so it must be passed separately for the function to process it correctly.
  8. What does it mean that an array is passed by reference in C?
    It means the function operates directly on the original array's memory, rather than working with a separate copy of the data.
  9. What is the relationship between an array's name and memory addresses in C?
    An array's name represents the memory address of its first element, which is part of why array names behave differently from ordinary variables in certain expressions.
  10. Why are loops commonly used together with arrays?
    Loops allow every element of an array to be processed automatically using a single block of repeated code, rather than manually referencing each index one at a time.
  11. What is a common approach for finding the maximum value in an array?
    A common approach involves assuming the first element is the maximum, then comparing every remaining element against it, updating the maximum whenever a larger value is found.

Summary

Arrays provide an efficient way to store and organize multiple related values under a single name, eliminating the need for numerous individual variables and making it far easier to process large amounts of data using loops. One-dimensional arrays handle simple lists of values, while multidimensional arrays extend this concept to represent structured data such as grids and tables.

In this tutorial, you learned how to declare and initialize arrays, how indexing works in C, how to process array elements using loops, how multidimensional arrays are structured and traversed, and how arrays can be passed to functions for further processing. With arrays firmly understood, you are ready to move on to strings, which are themselves a specialized form of character array in C.


← Previous: Loops in C Next: Strings in C →

Home Visit Our YouTube Channel