Iterate Over Arrays using Loops in C
In C, we can iterate over an array using loops such as for
, while
, and do-while
. Looping through an array allows us to access each element and perform operations like printing, modifying, or computing values. In this tutorial, we will explore different ways to iterate over an array with detailed explanations and examples.
Examples to Iterate Over Arrays
1. Iterating Over an Array Using a for
Loop
In this example, we will use a for
loop to traverse an integer array and print all its elements.
main.c
</>
Copy
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
// Loop through the array using for loop
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
Explanation:
- We declare an integer array
numbers[]
containing 5 elements. - We calculate the size of the array using
sizeof(numbers) / sizeof(numbers[0])
, which determines the number of elements. - We use a
for
loop wherei
starts at 0 and iterates up tosize - 1
. - Inside the loop, we use
printf()
to print each array element.
Output:
10 20 30 40 50
2. Iterating Over an Array Using a while
Loop
In this example, we will use a while
loop to iterate through an array and print its elements.
main.c
</>
Copy
#include <stdio.h>
int main() {
int numbers[] = {5, 15, 25, 35, 45};
int size = sizeof(numbers) / sizeof(numbers[0]);
int i = 0;
// Loop through the array using while loop
while (i < size) {
printf("%d ", numbers[i]);
i++;
}
return 0;
}
Explanation:
- We declare an integer array
numbers[]
with 5 elements. - We calculate the number of elements using
sizeof()
. - We initialize
i
to 0 before thewhile
loop. - The
while
loop runs as long asi
is less thansize
. - Inside the loop, we print the element at index
i
and then incrementi
.
Output:
5 15 25 35 45
3. Iterating Over an Array Using a do-while
Loop
In this example, we will use a do-while
loop to iterate through an array and print its elements.
main.c
</>
Copy
#include <stdio.h>
int main() {
int numbers[] = {2, 4, 6, 8, 10};
int size = sizeof(numbers) / sizeof(numbers[0]);
int i = 0;
// Loop through the array using do-while loop
do {
printf("%d ", numbers[i]);
i++;
} while (i < size);
return 0;
}
Explanation:
- We declare an integer array
numbers[]
with 5 elements. - We determine the size using
sizeof()
. - We initialize
i
to 0 before thedo-while
loop. - The loop executes at least once, printing the element at
i
, then incrementsi
. - The condition
i < size
is checked after each iteration.
Output:
2 4 6 8 10
Conclusion
In this tutorial, we explored different ways to iterate over arrays using loops in C:
for
Loop: Best for iterating when the number of elements is known.while
Loop: Useful when iteration depends on a condition.do-while
Loop: Ensures at least one iteration.