How to read an array in the C language?
There are two common methods in C language for reading an array by iterating through each element.
- Traverse the array using a for loop.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i;
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
- Traverse the array using pointers.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;
int i;
for (i = 0; i < 5; i++) {
printf("%d ", *ptr);
ptr++;
}
return 0;
}
You can access elements in an array either by using the index or a pointer, regardless of the method used.