We will learn about arrays.
- concept
It is a data structure that stores multiple pieces of data of the same type in a contiguous memory space. Access each element through index
- one-dimensional array
type name[size];
- declare: int arr[5];
- Init: int arr[5] = {1,2,3,4,5};
- Default: garbage if not initialized
- two-dimensional array
type name[rows][columns];
-
- Declaration and initialization: int mat[2][3] = {{1,2,3}, {4,5,6}};
- Memory: row-major order
- example
#include <stdio.h>
int main(void) {
int arr[5] = {10,20,30,40,50};
printf("One-dimensional array: ");
for (int i = 0; i < 5; i++)
printf("%d ", arr[i]);
printf("\n");
int mat[2][3] = {{1,2,3},{4,5,6}};
printf("Two-dimensional array:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
return 0;
}
I think it would be good to try this in simple practice.