An array in C is a collection of elements of the same data type. Each element in the array has a unique index, which allows you to access and manipulate individual elements within the array. Arrays are fixed in size, meaning you specify the number of elements the array can hold when you declare it.
data_type array_name[array_size];
data_type: The data type of the elements you want to store in the array (e.g., int, float, char,
etc.).
- array_name: The name of the array variable.
- array_size: The number of elements the array can hold.
Example of Declaring an Array:
int numbers[5]; // Declares an integer array named "numbers" with space for 5 elements
int numbers[5] = {1, 2, 3, 4, 5};
You access individual elements in an array using square brackets and an index. The index starts at 0 for the first element, so the second element is at index 1, the third element is at index 2, and so on.
Loops are often used to iterate through the elements in an array. A common choice is a `for`loop.
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
#include <stdio.h>
int main() {
// Declare an array of integers
int numbers[5];
// Initialize the array with values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Access and print the elements of the array
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}