How to Iterate Over Array in C: Simple Syntax and Example
In C, you iterate over an array using a
for loop by running an index from 0 to the array's length minus one. Inside the loop, you access each element with array[index] to process or print it.Syntax
Use a for loop with an index variable starting at 0 and running up to one less than the array size. Access elements with array[index].
- index: loop counter starting at 0
- array_size: total number of elements in the array
- array[index]: element at current position
c
for (int index = 0; index < array_size; index++) { // Use array[index] here }
Example
This example shows how to print all elements of an integer array using a for loop.
c
#include <stdio.h> int main() { int numbers[] = {10, 20, 30, 40, 50}; int size = sizeof(numbers) / sizeof(numbers[0]); for (int i = 0; i < size; i++) { printf("Element at index %d is %d\n", i, numbers[i]); } return 0; }
Output
Element at index 0 is 10
Element at index 1 is 20
Element at index 2 is 30
Element at index 3 is 40
Element at index 4 is 50
Common Pitfalls
Common mistakes include:
- Using an index that goes beyond the array size, causing undefined behavior.
- Starting the index at 1 instead of 0, which skips the first element.
- Not calculating the array size correctly.
Always ensure the loop runs from 0 up to but not including the array size.
c
/* Wrong: index starts at 1, misses first element */ for (int i = 1; i < size; i++) { printf("%d\n", numbers[i]); } /* Correct: index starts at 0 */ for (int i = 0; i < size; i++) { printf("%d\n", numbers[i]); }
Quick Reference
| Concept | Description |
|---|---|
| Index Start | Always start at 0 to access first element |
| Loop Condition | Use < array size to avoid overflow |
| Access Element | Use array[index] inside the loop |
| Calculate Size | Use sizeof(array) / sizeof(array[0]) for static arrays |
Key Takeaways
Use a for loop with index from 0 to array size minus one to iterate arrays in C.
Access each element inside the loop with array[index].
Calculate array size correctly using sizeof for static arrays.
Avoid going beyond array bounds to prevent errors.
Starting index at 0 is essential to include all elements.