Different ways to loop through an array in C

Feb 10, 2024#c#arrays

In C programming, an array is a collection of elements of the same data type that are stored in contiguous memory locations. Each element in the array is identified by an index or a key, which represents its position in the array. The array provides a convenient way to store and access multiple values under a single variable name.

// Declaring an integer array with 5 elements
int arr[5]; 

// Declaration with initialization
int nums[] = {1, 2, 3, 4, 5};

// Declaring and initializing a 2D array (matrix)
int matrix[3][3] = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};

There’s no direct built-in mechanism to retrieve the length of an array in C. You typically need to calculate the length based on the size of the array and the size of an individual element.

int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);

Keep in mind that this method assumes that the array is not a pointer and that it’s not a multi-dimensional array. If the array is a pointer or a multi-dimensional array, the calculation of length becomes more complex.

There are several ways to loop through an array in C, and the choice often depends on the specific requirements of your program.

Using a for loop

This is the most common and widely used approach. You use a counter variable to iterate from the beginning to the end of the array, accessing each element by its index.

#include <stdio.h>

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int length = sizeof(arr) / sizeof(arr[0]);

  for (int i = 0; i < length; i++) {
    printf("%d ", arr[i]);
  }

  return 0;
}

Using a while loop

You can also loop through an array using a while loop. The key is to increment the loop variable within the loop body until the desired condition is met.

#include <stdio.h>

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int length = sizeof(arr) / sizeof(arr[0]);

  int i = 0;
  while (i < length) {
    printf("%d ", arr[i]);
    i++;
  }

  return 0;
}

This method is suitable when the number of iterations is unknown beforehand. You can use a condition like reaching a specific value within the array to terminate the loop.

Using a do-while loop

The do-while loop is similar to the while loop, but it guarantees that the loop body is executed at least once before the condition is checked.

#include <stdio.h>

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int length = sizeof(arr) / sizeof(arr[0]);

  int i = 0;
  do {
    printf("%d ", arr[i]);
    i++;
  } while (i < length);

  return 0;
}

Using pointer arithmetic

While less readable than loops, this method directly manipulates pointers to access elements, potentially offering performance benefits.

#include <stdio.h>

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int length = sizeof(arr) / sizeof(arr[0]);

  int *ptr = arr;
  for (int i = 0; i < length; i++) {
    printf("%d ", *(ptr + i));
  }

  return 0;
}