Chapter 17 of 37

Arrays

Suppose you want to store the marks of 5 students. You could create five separate variables:

int mark1 = 80;
int mark2 = 75;
int mark3 = 90;
int mark4 = 85;
int mark5 = 70;

But this becomes difficult to manage when you have hundreds of values.

That's where arrays come in.

What is an Array?

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

For example:

int marks[5] = {80, 75, 90, 85, 70};

Here, marks can store 5 integers.

You can imagine it like this:

Index:    0    1    2    3    4
         ┌───┬───┬───┬───┬───┐
marks →  │80 │75 │90 │85 │70 │
         └───┴───┴───┴───┴───┘

Array Index

C arrays use zero-based indexing, which means the first element is at index 0.

printf("%d", marks[0]);

Output:

80

Similarly:

marks[2]

gives:

90

So, for an array of 5 elements, the indexes are:

0  1  2  3  4

Not 1 to 5.

Declaring an Array

The basic syntax is:

data_type array_name[size];

For example:

int numbers[5];

This creates an array that can store 5 integers.

We can also initialize it immediately:

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

Accessing Array Elements

We use the index to access or modify an element.

int numbers[3] = {10, 20, 30};

printf("%d", numbers[1]);

Output:

20

We can also change a value:

numbers[1] = 50;

Now the array becomes:

10  50  30

Arrays and Loops

Arrays are commonly used with loops because we can process multiple elements easily.

int marks[5] = {80, 75, 90, 85, 70};

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

Output:

80
75
90
85
70

This is much cleaner than writing five separate printf() statements.

Types of Arrays

Arrays can have one or more dimensions.

One-Dimensional Array

int numbers[5];

It stores values in a single sequence.

Two-Dimensional Array

int matrix[2][3];

It can be visualized like a table:

10  20  30
40  50  60

We will learn multidimensional arrays separately.

Important Points

  • All elements of an array have the same data type.

  • Array indexing starts from 0.

  • The size determines how many elements the array can hold.

  • Array elements can be accessed using their index.

  • Arrays are stored in contiguous memory locations.

In Simple Words

An array allows us to store multiple values of the same data type under a single name.

For example:

int marks[5] = {80, 75, 90, 85, 70};

Instead of managing five different variables, we can manage all five marks using one array called marks.