C Array Traversal: 3 Methods Explained

There are several methods to iterate over an array in the C language.

  1. 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]);
}
  1. 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++;
}
  1. 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));
}
  1. 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.

bannerAds