An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow you to store and manage multiple values under a single variable name.
data_type array_name[size];
int
, float
, char
).int numbers[5];
One-Dimensional Arrays
A linear collection of elements.
Example:
int numbers[5] = {1, 2, 3, 4, 5};
Two-Dimensional Arrays
A table or matrix-like structure with rows and columns.
Example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Multi-Dimensional Arrays
Arrays with more than two dimensions.
Example:
int tensor[2][3][4];
Array elements are accessed using their index, which starts from 0
.
int numbers[5] = {10, 20, 30, 40, 50};
printf("%d", numbers[2]); // Outputs: 30
At Declaration:
int numbers[3] = {10, 20, 30};
Partially Initialized:
0
.int numbers[5] = {10, 20}; // Remaining elements: 0, 0, 0
Uninitialized:
int numbers[5];
Use loops to process all elements in an array.
int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
#include <stdio.h>
int main() {
int matrix[2][2];
// Input
printf("Enter 4 elements:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Output
printf("Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}