HOME HTML EDITOR C JAVA PHP

C Arrays: Grouping Related Data

An **Array** is a fixed-size, sequenced collection of elements of the same data type. It is one of the most important data structures in C because it allows you to store multiple values in a single variable name, making data management much more efficient.

1. Why Use Arrays?

Imagine you need to store the marks of 5 students. Without arrays, you would need to create five separate variables: mark1, mark2, mark3, mark4, mark5. With an array, you can simply create one variable: int marks[5];. This makes it easier to perform operations like sorting, searching, or calculating averages using loops.

2. Declaring and Initializing Arrays

To declare an array, you specify the data type, the name of the array, and the number of elements it will hold inside square brackets [].

// Declaration
int myNumbers[5];

// Declaration with Initialization
int myNumbers[5] = {10, 20, 30, 40, 50};

// Initialization without specifying size (Compiler calculates it)
int myNumbers[] = {10, 20, 30, 40, 50};

3. Accessing Array Elements

Array elements are accessed using an **Index Number**. In C, array indexing always starts at 0. This means the first element is at index 0, the second is at index 1, and the last element is at index size - 1.

int myNumbers[] = {25, 50, 75, 100};

printf("%d", myNumbers[0]); // Prints 25 (First element)

// Changing an element
myNumbers[1] = 99;
printf("%d", myNumbers[1]); // Prints 99

4. Looping Through an Array

The most efficient way to work with arrays is by using a for loop. Since we know the size of the array, we can use the loop counter as the index to access each element.

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

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

5. Multidimensional Arrays (2D Arrays)

C also supports multidimensional arrays. The most common is the **2D Array**, which can be thought of as a table with rows and columns. This is particularly useful for representing matrices or game boards.

// A 2D array with 2 rows and 3 columns
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };

// Accessing element in Row 0, Column 2
printf("%d", matrix[0][2]); // Prints 3

6. Technical Specifications

Concept Description
Memory Calculation Total size = Number of elements × Size of one element.
Array Bounds C does not check if an index is out of bounds (Runtime crash risk).
Base Address The name of the array points to the address of the 0th element.

7. Common Mistakes to Avoid

Pro Tip: To find the number of elements in an array automatically, you can use the sizeof operator: int length = sizeof(arr) / sizeof(arr[0]);. This makes your loops safer and more flexible!