In C, an array is a collection of variables of the same data type that are stored in contiguous memory locations. Arrays allow you to store multiple values in a single variable, which makes handling large datasets much easier!
An array is defined by the following syntax:
data_type array_name[array_size];
Where:
int
, char
, float
, etc.).Here's how you can declare and initialize an array in C:
#includeint main() { int arr[5] = {1, 2, 3, 4, 5}; // Declare and initialize array // Printing array elements for(int i = 0; i < 5; i++) { printf("%d ", arr[i]); // Accessing each element by index } return 0; }
arr
holds five integer elements. The for
loop is used to print each element of the array by accessing it through its index (starting from 0).
In C, arrays are zero-indexed. This means that the first element of an array is accessed using index 0
, the second element with index 1
, and so on. Here's an example:
int arr[5] = {10, 20, 30, 40, 50}; printf("First element: %d\n", arr[0]); // Output: 10 printf("Third element: %d\n", arr[2]); // Output: 30
In C, you can also declare multidimensional arrays. These are arrays of arrays. Here's how you can declare a 2D array:
#includeint main() { int arr[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2D array initialization // Accessing and printing 2D array elements for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { printf("%d ", arr[i][j]); } printf("\n"); } return 0; }
arr
has 2 rows and 3 columns. The nested for
loop is used to access each element in the 2D array.
Arrays are one of the most fundamental data structures in C. They're efficient for storing multiple items of the same type and can be used for a variety of operations. Mastering arrays opens the door to understanding more complex data structures like linked lists, stacks, and queues.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!