Introduction to arrays
In C programming, an array is a collection of elements of the same data type, grouped together under a single name. Arrays provide a way to store multiple values of the same type in contiguous memory locations. They are widely used to store and manipulate collections of data efficiently.
To declare an array in C, you need to specify the data type of the elements it will hold and the number of elements it can store. The general syntax for declaring an array is as follows:
datatype arrayName[arraySize];
Here, `datatype` represents the data type of the elements, `arrayName` is the name given to the array, and `arraySize` specifies the number of elements the array can hold.
For example, to declare an array of integers with 5 elements, you can use the following statement:
int numbers[5];
Once an array is declared, you can access its individual elements using an index, which starts from 0 and goes up to `arraySize - 1`. The index is enclosed in square brackets `[]` and is placed after the array name.
Here's an example that demonstrates how to declare and access elements in an array:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
printf("Element at index 0: %d\n", numbers[0]); // Output: 10
printf("Element at index 2: %d\n", numbers[2]); // Output: 30
numbers[3] = 60; // Modifying element at index 3
printf("Modified element at index 3: %d\n", numbers[3]); // Output: 60
return 0;
}
In this example, an array `numbers` is declared with 5 elements. The elements are initialized with values 10, 20, 30, 40, and 50. The program then accesses and prints the values at index 0 and 2. It also modifies the element at index 3 and prints the modified value.
Arrays in C have several properties, including:
- Elements of an array are stored in contiguous memory locations.
- The size of the array is fixed once it is declared and cannot be changed during runtime.
- Arrays can be of any data type, including integers, floating-point numbers, characters, and user-defined types.
- Arrays are passed to functions by reference, allowing functions to modify their contents.
- Arrays can be used to implement various data structures and algorithms, such as sorting and searching.