Arrays

An array is a collection of elements of the same data type, stored in contiguous memory locations. Each element can be accessed directly using an index.

  • Indexing starts from 0 in C.
  • The size must be declared at creation time (fixed size).
  • All elements are of the same type (e.g., all int or all float).

Memory Layout

If you declare:

int arr[5] = {10, 20, 30, 40, 50};

then memory looks like this:

Index01234
Value1020304050

Each element can be accessed as arr[0], arr[1], etc.

When to Use Arrays

Use arrays when:

  • The number of elements is known in advance and rarely changes.
  • You need fast, random access to elements using an index.
  • You are performing mathematical computations such as matrices or vectors.
  • You need to store and process data sequentially, such as reading sensor values.

When Not to Use Arrays

Avoid arrays when:

  • The size of data changes frequently (use a linked list instead).
  • You need frequent insertions or deletions in the middle (shifting elements is costly).
  • You need to store different data types (use structures).
  • You are dealing with large data and need dynamic resizing (use dynamic arrays with malloc() or vectors in C++).

Example in C

#include <stdio.h>

int main() {
    int arr[5]; // Declare an array of 5 integers
    int i;

    // Input 5 numbers
    printf("Enter 5 numbers:\n");
    for (i = 0; i < 5; i++) {
        scanf("%d", &arr[i]);
    }

    // Display the numbers
    printf("\nYou entered:\n");
    for (i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    // Example: Sum of all elements
    int sum = 0;
    for (i = 0; i < 5; i++) {
        sum += arr[i];
    }
    printf("\nSum = %d\n", sum);

    return 0;
}

Sample Output

Enter 5 numbers:
10 20 30 40 50

You entered:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

Sum = 150

Key Operations and Time Complexities

OperationDescriptionTime Complexity
AccessDirectly access using indexO(1)
SearchScan elements until foundO(n)
InsertionInsert at middle (shift elements)O(n)
DeletionRemove element and shiftO(n)

Advantages and Disadvantages

AdvantagesDisadvantages
Fast random accessFixed size (static)
Simple to useCostly insert/delete
Memory locality (cache-friendly)Homogeneous data only
Efficient iterationWastage if array size overestimated