Arrays are fundamental data structures in C programming that allow you to store and manipulate a collection of elements of the same data type. In this article, we will provide a comprehensive introduction to arrays in C, covering their uses, declaration, initialization, and providing practical examples with code and output. Arrays are versatile data structures in C that allow you to work with collections of elements efficiently. By understanding how to declare, initialize, and access array elements, you’ll have a solid foundation for working with more complex data structures and solving a wide range of programming problems.
What Are Arrays?
An array is a collection of elements, all of the same data type, stored in contiguous memory locations. Each element in an array can be accessed by its index, which starts from 0 for the first element.
Declaring Arrays
To declare an array in C, you specify the data type of its elements, followed by the array’s name and its size enclosed in square brackets []
. For example:
int numbers[5]; // Declares an integer array of size 5
Initializing Arrays
You can initialize an array at the time of declaration or later using a list of values enclosed in curly braces {}
.
int numbers[5] = {10, 20, 30, 40, 50}; // Initializes an integer array with values
Accessing Array Elements
You can access individual elements of an array using their indices. The index of the first element is 0, and the index of the last element is one less than the array’s size.
int firstNumber = numbers[0]; // Accesses the first element (10)
int secondNumber = numbers[1]; // Accesses the second element (20)
Example: Finding the Sum of Array Elements
Let’s look at a practical example where we find the sum of elements in an array.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int sum = 0;
// Calculate the sum of array elements
for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++) {
sum += numbers[i];
}
printf("The sum of elements is: %d\n", sum);
return 0;
}
In this example, we declare and initialize an integer array numbers
. We then use a for
loop to iterate through the elements of the array, adding each element to the sum
variable. The output of this program will be:
The sum of elements is: 150