An array in C is a collection of elements of the same type stored in contiguous memory locations. It allows you to store multiple values of the same data type under a single variable name.
Important Points of Array
1. All elements in an array must be of the same type (e.g., all integers, all characters, etc.).
2. The array size must be fixed when it is declared (though it can be a constant).
3. Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.
Syntax: to declare a Array
type arrayName[size];
Explanation:
- type: The data type of the array elements (e.g., int, float, char).
- arrayName: The name of the array.
- size: The number of elements the array will hold.
Syntax: to access a Array element
// declare a index of Array element
// First array element start from 0 index and so on increment by 1.
arrayName[index];
Example:
#include <stdio.h>
int main() {
// Declare an array of integers with 5 elements
int arr[5] = {10, 20, 30, 40, 50};
// Access and print each element
printf("First element: %d\n", arr[0]); // Output: 10
printf("Second element: %d\n", arr[1]); // Output: 20
printf("Third element: %d\n", arr[2]); // Output: 30
printf("Fourth element: %d\n", arr[3]); // Output: 40
printf("Fifth element: %d\n", arr[4]); // Output: 50
return 0;
}
Explanation:
- int arr[5]: Declares an array of integers with 5 elements.
- {10, 20, 30, 40, 50}: Initializes the array with values.
- To Accesses individual elements of the array: by index like arr[0], arr[1], arr[2], arr[3], arr[4]