OneBite.Dev - Coding blog in a bite size

iterate over an array in C

Code snippet on how to iterate over an array in C

  int array[] = {1, 2, 3, 4, 5}; 
  int i, size; 
  size = sizeof(array)/sizeof(array[0]);  
 
  // Iterate over all array elements 
  for(i = 0; i < size; i++) { 
    printf("array[%d] = %d\n", i, array[i]); 
  }

In this code snippet, we are declaring an array of type integer, called “array” with five elements. We then set a variable “size” to be the number of elements in the array. The “for loop” then begins - it goes from 0 all the way up to the number of elements in the array. For each iteration, it prints out the index of the element and its value. Finally, the for loop ends when it reaches the last element in the array.

c