To iterate over an array in C, you can use a for loop to access each element of the array. The loop runs from the first index (0) to the last index (size-1) of the array, allowing you to perform operations on each element.
In this example,
arr
with integer values.sizeof
operator.#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
printf("%d\n", arr[i]);
}
return 0;
}
1 2 3 4 5
In this example,
arr
with string values.sizeof
operator.#include <stdio.h>
int main() {
char *arr[] = {"apple", "banana", "cherry"};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
printf("%s\n", arr[i]);
}
return 0;
}
apple banana cherry
In this tutorial, we learned How to Iterate Over an Array in C language with well detailed examples.