Arrays (Lesson)

Arrays: Storing Collections

An array is a collection of data items of the same data type stored in contiguous memory locations.

13.1 One-Dimensional Arrays

Declaration and Initialization

int marks[5]; // Declaration of size 5
int primes[] = {2, 3, 5, 7, 11}; // Initialization

Accessing Elements

Array indices start from 0. An array of size N has indices from 0 to N-1.

int first = primes[0]; // 2
primes[1] = 4; // Update value

13.2 Memory Representation

If an integer takes 4 bytes and the array starts at address 1000:

Index0123
Value10203040
Address1000100410081012

13.3 Multi-Dimensional Arrays (2D)

A 2D array is often visualized as a table or a matrix with rows and columns. Syntax: type name[rows][columns];

int matrix[2][3] = {
    {1, 2, 3}, // Row 0
    {4, 5, 6}  // Row 1
};

Accessing row 1, column 0: matrix[1][0] (Value: 4).


13.4 Passing Arrays to Functions

When you pass an array to a function, you are actually passing the address of the first element.

void printArray(int arr[], int size) {
    for(int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
}

Example: Finding Average of Array Elements

#include <stdio.h>

int main() {
    int n, i;
    float num[100], sum = 0.0, avg;

    printf("Enter number of elements (1 to 100): ");
    scanf("%d", &n);

    for (i = 0; i < n; ++i) {
        printf("%d. Enter number: ", i + 1);
        scanf("%f", &num[i]);
        sum += num[i];
    }

    avg = sum / n;
    printf("Average = %.2f", avg);

    return 0;
}

Refer to the Lecture Slides for Row-Major and Column-Major memory storage details.

PREVIOUS
Functions Continued
NEXT
Pointers