Unit 6: Arrays

Table of Contents

1. What are Arrays?

An Array is a fixed-size, sequenced collection of elements of the same data type. It is used to store multiple values in a single variable, rather than declaring separate variables for each value.

Key Concept: Arrays are used when we need to handle a large amount of related data of the same type (e.g., marks of 50 students).

2. Creating and Declaring Arrays

To declare an array in C, you specify the data type of the elements and the number of elements required by the array.

Syntax:

data_type array_name[array_size];

Example: int marks[5];
This tells the compiler to reserve space for 5 integers under the name 'marks'.

3. Initialization of Arrays

Initialization refers to assigning values to the array elements at the time of declaration.

4. Accessing Array Elements

Array elements are accessed using an index (also called a subscript). In C, array indexing always starts from 0 and ends at size - 1.

int marks[3] = {85, 90, 78};
printf("%d", marks[0]); // Output: 85
printf("%d", marks[2]); // Output: 78
    

5. Memory Representation of Arrays

Since arrays occupy contiguous memory, the address of any element can be calculated if the base address (address of the first element) is known.

Formula for address calculation:
Address of A[i] = Base Address + (i * size_of_data_type)

Example: If an integer array starts at address 1000 and each integer takes 4 bytes, then marks[2] would be at:
1000 + (2 * 4) = 1008.

6. Multidimensional Arrays (2D Arrays)

A 2D array is essentially an "array of arrays." It is commonly used to represent tables or matrices.

Syntax:

data_type array_name[rows][columns];

Example: int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
This creates a table with 2 rows and 3 columns.

7. Array-Related Functions and Operations

Common operations performed on arrays include:

8. Exam Focus Enhancements

Exam Tips

Common Mistakes

Frequently Asked Questions

Q: Why is it called a "Static" data structure?
A: Because the size of the array is fixed at compile-time and cannot be changed during the execution of the program.

Q: What is the base address?
A: The base address is the memory location of the very first element (index 0) of the array.