C Array Traversal: 3 Methods Explained
There are several methods to iterate over an array in the C language.
- Traverse through the array elements using a for loop.
int arr[5] = {1, 2, 3, 4, 5};
int i;
for(i = 0; i < 5; i++){
printf("%d ", arr[i]);
}
- Traverse array elements using a while loop.
int arr[5] = {1, 2, 3, 4, 5};
int i = 0;
while(i < 5){
printf("%d ", arr[i]);
i++;
}
- Traverse array elements using pointers.
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;
int i;
for(i = 0; i < 5; i++){
printf("%d ", *(ptr + i));
}
- Iterate over array elements using a foreach loop (requires C11 standard or higher):
int arr[5] = {1, 2, 3, 4, 5};
for(int num : arr){
printf("%d ", num);
}
These are some common methods for traversing arrays, choose the method that suits you to traverse the array.