How to Iterate through an Array in C

C-Array

In this article, we are going to learn How to Iterate through an Array in C language. We can use the printf statement to print the elements of the array by just iterating over the array.

Different loops to iterate through an array in C language


  • Iterate over an array using for loop.
  • Iterate over an array using while loop.
  • Iterate over an array using do while loop.

C Program to Iterate through an Array in C using for loop


In this example, we are iterating over the array in C by using the for a loop. using for loop we can start at the index 0 which is the starting index of an array in C language. We can iterate this for a loop until we reach the max index which is n-1. n is the max size of the array.

In our example, we already know the size as 5, but if we don’t know the size then we can calculate the size first before we iterate.If you try to iterate beyond the maximum size of the array it will throw out of limit exception.

#include <stdio.h>
int main()
{
  int arr[] = {1, 2, 3, 4, 5};
  
  printf("The elements of the array are: ");
  for(int i=0; i<5; i++) 
  {
     printf("%d ", arr[i]);
  }

  return 0;
}

Output

The elements of the array are: 1 2 3 4 5 

C Program to Iterate through an Array using while loop


In this example, we are iterating over the array in C by using the while loop. Using for loop we can start at the index 0 which is the starting index of an array in C language. We can iterate this for a loop until we reach the max index which is n-1. n is the max size of the array.

#include <stdio.h>
int main()
{
  int arr[] = {1, 2, 3, 4, 5};
  
  printf("The elements of the array are: ");
  int i = 0;
  while(i<5) 
  {
     printf("%d ", arr[i]);
     i++;
  }

  return 0;
}

Output

The elements of the array are: 1 2 3 4 5 

C Program to iterate through an Array using do while loop


In this example, we are iterating over the array in C by using the do-while loop. Using for loop we can start at the index 0 which is the starting index of an array in C language. We can iterate this for a loop until we reach the max index which is n-1. n is the max size of the array.

#include <stdio.h>
int main()
{
  int arr[] = {1, 2, 3, 4, 5};
 
  
  printf("The elements of the array are: ");
  int i = 0;
  do {
     printf("%d ", arr[i]);
     i++;
  } while(i<5);

  return 0;
}

Output

The elements of the array are: 1 2 3 4 5