Follow us to get updates regarding Latest posts. Follow Now!

Chapter 7 - Array

Array

An array in C is a collection of elements that are stored in contiguous memory locations. Elements in an array are of the same data type, and each element can be accessed using its index, which is an integer value that starts at 0.

In C, arrays can be declared using the syntax:




data_type array_name[size];



For example, to declare an array of 10 integers, we can use the following code:




int myArray[10];



It's also possible to initialize an array with values at the time of declaration, like this:




int myArray[5] = {1, 2, 3, 4, 5};



or




int myArray[] = {1, 2, 3, 4, 5};



To access an element in an array, we can use the array name followed by the index of the element in square brackets. For example, to access the third element in the array 'myArray', we can use the following code:




printf("Third element: %d", myArray[2]);



C also supports multi-dimensional arrays, which are arrays of arrays. A two-dimensional array can be declared as:




data_type array_name[row_size][column_size];



For example, to declare a 2-dimensional array of 3 rows and 4 columns, we can use the following code:




int my2DArray[3][4];



To access an element in a 2-dimensional array, we can use multiple sets of square brackets. For example, to access the element at the second row and third column of the array 'my2DArray', we can use the following code:




printf("Element at 2nd row and 3rd column: %d", my2DArray[1][2]);



In C, arrays are passed to functions by reference, meaning that the function receives a pointer to the first element of the array. This means that any changes made to the array inside the function will be reflected outside the function as well. For example:




void modifyArray(int arr[], int size) {
arr[0] = 10;
}
int main() {
int myArray[5] = {1, 2, 3, 4, 5};
modifyArray(myArray, 5);
printf("First element: %d", myArray[0]);
return 0;
}



The output of the above code will be "First element: 10" because the function 'modifyArray' changed the value of the first element of the array 'myArray'

In this blog, we have covered the basics of arrays in C. Arrays are powerful and versatile data structures that are widely used in various applications, from simple programs to complex systems. Understanding how to use arrays in C is an essential skill for any C programmer.














Post a Comment

© testsiteweb | All rights reserved

Developed by Jago Desain