An array in C is a collection of elements of the same type, stored at contiguous memory locations. Arrays can store primitive types such as int, char, double, float, and derived types like pointers and structures. Arrays are a fundamental data structure that allows efficient storage and access of multiple items of the same type using an index.
1. Same Data Type: Each element of an array is of the same data type and occupies the same amount of memory.
2. Contiguous Memory Locations: Elements are stored in contiguous memory locations.
3. Random Access: Elements can be accessed directly using their index.
1.Code Optimization: Less code is required to access and manipulate data.
2. Ease of Traversing: Elements can be easily retrieved using loops.
3. Ease of Sorting: Sorting elements requires minimal code.
4. Random Access: Any element can be accessed directly using its index.
1. Fixed Size: The size of the array is fixed at the time of declaration and cannot be changed.
An array is declared by specifying the data type, array name, and size.
data_type array_name[array_size];
int marks[5];
An array can be initialized using index values.
int marks[5] = {90, 85, 78, 92, 88};
If you want to initialize an array without specifying values for all elements, the remaining elements will be initialized to zero.
int marks[5] = {90, 85}; // marks[2] to marks[4] will be 0
#include <stdio.h>
int main() {
int marks[5] = {90, 85, 78, 92, 88};
for (int i = 0; i < 5; i++) {
printf("Mark of subject %d is %d\\n", i+1,
marks[i]);
}
return 0;
}
Mark of subject 1 is 90
Mark of subject 2 is 85
Mark of subject 3 is 78
Mark of subject 4 is 92
Mark of subject 5 is 88
A two-dimensional (2D) array is an array of arrays, organized in a matrix of rows and columns. It is useful for representing data in tabular form.
data_type array_name[rows][columns];
int matrix[4][3];
Unlike 1D arrays, at least the second dimension must be specified during declaration and initialization.
int matrix[4][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
#include <stdio.h>
int main() {
int matrix[4][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
printf("Element at
[%d][%d] is %d\\n", i, j, matrix[i][j]);
}
}
return 0;
}
Element at [0][0] is 1
Element at [0][1] is 2
Element at [0][2] is 3
Element at [1][0] is 4
Element at [1][1] is 5
Element at [1][2] is 6
Element at [2][0] is 7
Element at [2][1] is 8
Element at [2][2] is 9
Element at [3][0] is 10
Element at [3][1] is 11
Element at [3][2] is 12