Array in C

Array in C

Introduction to Array

Written by: alam2107023

Wed, 13 Nov 2024

Array

The concepts we have learned so far

  • Data Types
  • Variables

A variable of a specific datatype stores a single value of that data type, for example:

int sub1 = 23;
char character = 'a';

But suppose we need to store the marks of 6 different courses for a student.

int sub1 = 85;
int sub2 = 81;
int sub3 = 79;
int sub4 = 89;
int sub5 = 87;
int sub6 = 93;

Using separate variables for each mark works but becomes inefficient when handling larger datasets. Solution: By using Loops and Arrays, we can simplify this process.


Array Here

An array allows us to store multiple values of the same type in a single variable.

Syntax
datatype array_name[array_size];

[Note: We can let the array size uninitialized if we initialize the array with the values directly. Otherwise, array size initialization is required.]


Examples of Array Declarations

Applying Arrays to Our Problem

Using an array, we can store the course marks more efficiently:

int CourseNumber[] = {85, 81, 79, 89, 87, 93};

Here, all marks are stored in a single array named CourseNumber. Since we initialized the values, we didn’t need to specify the array size.


Accessing Array Elements

Before accessing an array, we need to understand how elements are stored in memory.

Index012345
Value858179898793

Each element is assigned an index that’s allowing to access or modify array values directly.


Accessing and Modifying Elements

Example: Accessing Elements
int CourseNumber[] = {85, 81, 79, 89, 87, 93};
printf("%d ", CourseNumber[0]); 
printf("%d ", CourseNumber[1]); 
printf("%d ", CourseNumber[2]);

Output: 85 81 79

Example: Updating an Element
int CourseNumber[] = {85, 81, 79, 89, 87, 93};
printf("%d ", CourseNumber[2]); 
CourseNumber[2] = 95;
printf("%d ", CourseNumber[2]);

Output: 79 95


Printing All Elements with a Loop

To print all elements of an array, use a loop to iterate through each index:

for (int i = 0; i < 6; i++) {
 printf("%d ", CourseNumber[i]);
}

Output: 85 81 79 89 87 93

If we don’t initialize values at declaration, we need to specify the array size:

int CourseNumber[6];

[Note: If an array is declared with a specific size but initialized with more values than its capacity, the extra values will be stored in such memory locations that we cannot access using the defined array indexes. Conversely, if fewer values are assigned than the array’s capacity, the remaining cells may contain garbage values. These values may vary depending on the system or device in use. Similar problem arises if we try to output values more than array’s capacity.]


Finding the Size of an Array

The sizeof() operator in C returns the size, in bytes, of a data type or object in memory.

Example
printf("%d ", sizeof(double));
printf("%d ", sizeof(int)); 
int CourseNumber[] = {85, 81, 79, 89, 87, 93};
printf("%d ", sizeof(CourseNumber));

Output: 8 4 24


Determine the Length of an Array

In C, we can determine the number of elements in an array by dividing the total size of the array (in bytes) by the size of a single element (in bytes). This can be done using the sizeof() operator.

Example
int CourseNumber[] = {85, 81, 79, 89, 87, 93};
int length = sizeof(CourseNumber) / sizeof(CourseNumber[0]);
printf("%d", length);

Output: 6

What’s happening here?

  • sizeof(CourseNumber) gives the total size of the array in bytes.
  • sizeof(CourseNumber[0]) gives the size of one element (an int) in bytes.
  • Dividing the total size by the size of one element gives the number of elements in the array.

You can also calculate the length using the datatype:

int length = sizeof(CourseNumber) / sizeof(int);
printf("%d ", length);

Output: 6


Iterating Over the Array

Once we have the length of the array, we can use a loop to iterate over the elements. For example:

int CourseNumber[] = {85, 81, 79, 89, 87, 93};
int length = sizeof(CourseNumber) / sizeof(int);
for(int i = 0; i < length; i++) {
 printf("%d ", CourseNumber[i]);
}

Output: 85 81 79 89 87 93

2-Dimensional Arrays

Declaring and Initializing a 2D Array

A 2D array requires both the row and column sizes to be declared. Unlike 1D arrays, you cannot initialize a 2D array without specifying at least the column size.

Example
int array[2][3] = {{1, 2, 3}, {4, 5, 6}};

In this case, the array has:

  • 2 rows (array[0], array[1])
  • 3 columns per row (array[0][0], array[0][1], array[0][2])

Memory Layout of a 2D Array

The elements of a 2D array are stored in contiguous memory in row-major order, which means that the first row is stored first, followed by the second row, and so on. The indexing starts at [0][0].

Example Memory Layout:
Value123456
Index[0][0][0][1][0][2][1][0][1][1][1][2]

Accessing and Modifying 2D Array

You can access or modify the elements using their row and column indices.

  • To access the element array[0][0], you get the value 1.
  • To change the value at array[1][2] to 100, you use:
array[1][2] = 100;

Printing a 2D Array

To print a 2D array, we can use nested loops to iterate over the rows and columns.

Example
int array[2][3] = {{1, 2, 3}, {4, 5, 6}};
for(int i = 0; i < 2; i++) { 
 for(int j = 0; j < 3; j++) { 
 printf("%d ", array[i][j]);
 }
 printf("\n");
}

Output: 1 2 3 4 5 6

Important Notes:
  • You cannot declare a 2D array with an unspecified number of columns without defining at least the column size. For example, the following is incorrect:
 int array[3][]; //incorrect declaration
  • The row size can be omitted if the array is initialized with values, but the column size must always be specified.

Multi-Dimensional Arrays

We can also initialize 3D or higher-dimensional arrays just like the previous examples. These arrays can be initialized with the array size specified for all dimensions or directly with values. Here are some valid examples:

int array[][2][3] = {{{1, 2, 3}, {4, 5, 6}}};
int array[][2][2][2] = {{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}};

Capacity of a Multi-Dimensional Array

The total amount of values a multi-dimensional array can hold is calculated by multiplying the sizes of each dimension: int array[dim 1][dim 2][dim 3]…[dim n] capacity = dim 1×dim 2×dim 3⋯× dim n

Traversing Multi-Dimensional Arrays Using Loops

If we want to dynamically input values into an array, we’ll need as many loops as the array has dimensions. For example, with a 3D array, we would use 3 nested loops to iterate through each dimension for input or output. If values are not fully initialized, the array may display garbage values[zero or some hex. value] for unassigned cells.

User12024-11-02

This is a comment 1.

User12024-11-02

This is a comment 2.