C Looping Through Arrays
In this page:
Looping Through an Array with for
The standard way to loop through an array in C is a for loop whose index variable runs from 0 up to, but not including, the array's length, accessing one element per iteration with square-bracket indexing.
Example: Looping Through an Array with for
#include <stdio.h>
int main() {
int arr[4] = {5, 10, 15, 20};
for (int i = 0; i < 4; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing All Elements
Looping through an array to print its contents visits each element in order, using the loop index both to access the array element and, often, to label or number the output.
Example: Printing All Elements
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
for (int i = 0; i < 3; i++) {
printf("Item %d: %d\n", i, arr[i]);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Summing Array Elements
A running total variable, initialized before the loop and updated inside it, is the standard pattern for summing every element in an array, which can then be divided by the count to compute an average.
Example: Summing Array Elements
#include <stdio.h>
int main() {
int arr[4] = {1, 2, 3, 4};
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += arr[i];
}
printf("%d", sum);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Finding a Value in an Array
Searching an array for a specific value loops through its elements checking each one against the target, and break is commonly used to stop the loop immediately once a match is found rather than continuing needlessly.
Example: Finding a Value in an Array
#include <stdio.h>
int main() {
int arr[4] = {5, 10, 15, 20};
int target = 15;
for (int i = 0; i < 4; i++) {
if (arr[i] == target) {
printf("Found at index %d", i);
break;
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying Elements in a Loop
A loop can modify an array's elements in place by both reading and writing to the same index within its body, which is how operations like doubling every value or clamping negative values are applied across an entire array.
Example: Modifying Elements in a Loop
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
for (int i = 0; i < 3; i++) {
arr[i] *= 2;
}
printf("%d %d %d", arr[0], arr[1], arr[2]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: