top of page

What is an Array?

  • Writer: Siddharth Sharma
    Siddharth Sharma
  • Nov 4, 2024
  • 4 min read
  1. What is an Array?

An array is a data structure that stores a fixed-size sequence of elements of the same data type. For instance, if you need to store a list of integers, you could use an array of integers. Instead of declaring multiple variables to store each value, you can use one array to store all values, which makes your code more organized and manageable.


2. Why Use Arrays?

Arrays offer a way to store large amounts of data with a single variable name. This has several benefits:


  • Efficiency: Accessing elements in an array is fast, as all elements are stored in contiguous memory locations.

  • Simplicity: With a single variable name, you can loop through the elements, perform calculations, and store results without declaring multiple variables.

  • Data Management: Arrays make it easier to handle lists, sequences, or tables of values, especially when dealing with repetitive data.


3. Array Syntax in C

The syntax for declaring, initializing, and accessing arrays in C involves several important concepts:


Declaring an Array

To declare an array, specify:

  • The data type (e.g., int, float, char)

  • The array name

  • The array size (inside square brackets [ ] )

Example:

int numbers[10]; // Declares an integer array of 'numbers' that can store 
10 elements 
float prices[5]; // Declares a float array 'prices' that can store 5 elements 
char name[20]; // Declares a character array 'name' that can store a string of 20 characters

Initializing an Array

You can initialize arrays when declaring them, by providing values in curly braces {}:


int numbers[5] = {1, 2, 3, 4, 5}; // Initializes the array with 5 integers
float scores[3] = {92.5, 88.0, 79.5}; // Initializes the array with 3 float values

You don’t have to initialize all elements explicitly. If fewer values are provided, remaining elements are set to zero by default.

int numbers[5] = {1, 2}; // Remaining elements will be {1, 2, 0, 0, 0}

Accessing Array Elements

To access elements, use the array name followed by the index in square brackets:

printf("%d", numbers[2]); // Accesses the third element (index 2)

Note: Array indexes start at 0. If an array has n elements, the indices are 0 to n-1.


4. Types of Arrays

Arrays in C can be categorised based on their dimensionality.


a) One-dimensional Arrays

A one-dimensional array is a simple list of elements. It’s often used for storing sequences of values, like marks, scores, or even strings of characters.

Example:

int ages[5] = {21, 22, 23, 24, 25}; // Array of 5 integers

b) Multi-dimensional Arrays

Multi-dimensional arrays are arrays of arrays. The most common multi-dimensional array is the two-dimensional array, which can represent a matrix or table. A 2D array requires two indices, one for the row and one for the column.

Example:

int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

In this example:

  • matrix[0][0] is 1

  • matrix[1][2] is 6

  • matrix[2][1] is 8

Two-dimensional arrays are useful for applications like matrices, tables, or grid-based data.


5. Common Array Operations

With arrays, you can perform various operations, such as:

Traversing

Loop through an array to read or update each element:

for (int i = 0; i < 5; i++) { 
	printf("%d ", numbers[i]); 
}

Searching

Look for a specific element in the array:

int target = 3;
int found = -1;
for (int i = 0; i < 5; i++) { 
	 if (numbers[i] == target) { 
		found = i;
		break; }
} 
	if (found != -1) 
		printf("Element found at index %d\n", found); 
	else 
		printf("Element not found\n");

Updating Elements

Change the value of specific elements by accessing their index:

numbers[2] = 100; // Sets the third element to 100

Sorting

Sorting an array is often useful, for instance, arranging numbers in ascending or descending order. C provides functions in the standard library to do this, like qsort().


6. Advantages and Limitations of Arrays

Advantages:

  • Efficient: Arrays provide a simple way to store and access large quantities of data.

  • Ease of Use: Handling data with arrays makes code simpler and easier to read when compared to using multiple variables.

Limitations:

  • Fixed Size: Array size is fixed at declaration and cannot be changed dynamically.

  • Homogeneity: All elements in an array must be of the same data type.

  • Memory Consumption: Arrays can consume a large amount of memory if large sizes are allocated but underutilized.


7. Example Program Using Arrays

Here's a full C program that demonstrates using an array to store and print student scores:

#include <stdio.h>
int main() {
    int scores[5]; // Array to store scores of 5 students
    int sum = 0;

   // Input scores from the user
    for (int i = 0; i < 5; i++) {
        printf("Enter score for student %d: ", i + 1);
        scanf("%d", &scores[i]);
    }

    // Calculate the sum of all scores
    for (int i = 0; i < 5; i++) {
        sum += scores[i];
    }
    // Calculate average score
    float average = sum / 5.0;

    // Print each score and the average
    printf("\nScores: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", scores[i]);
    }

    printf("\nAverage score: %.2f\n", average);

    return 0;
}

Summary

In C, arrays are a fundamental data structure used for storing collections of values of the same type. They allow efficient access and management of large data sets, especially with looping constructs. However, they are limited in size and type, which is why for dynamic sizes, other data structures or libraries are sometimes preferred.

 
 
 

Comments


bottom of page