Why Arrays + Loops Go Together?
Arrays and loops are taught together because loops make arrays useful.
Without loops, handling arrays is slow and messy.
1. Why Arrays + Loops Go Together
- Array stores many values
- Loop processes those values one by one
Think like this:
Array = data
Loop = worker that visits each data item
2. Core Idea
A loop is used to access, input, output, and process array elements using their index.
3. Visual Idea: Loop Traversing an Array
- Loop starts at index
0 - Moves step by step
- Stops at
size - 1
4. Basic Example: Print Array Elements
c
1
2#include <stdio.h>
3
4int main() {
5 int a[5] = {2, 8, 7, 6, 0};
6 int i;
7
8 for (i = 0; i < 5; i++) {
9 printf("%d ", a[i]);
10 }
11
12 return 0;
13}Output
2 8 7 6 05. Why i < 5 and NOT i <= 5
- Valid indexes:
0 to 4 a[5]is out of range
Correct rule:
for (i = 0; i < size; i++)6. Input Array Using Loop
c
1
2#include <stdio.h>
3
4int main() {
5 int a[5], i;
6
7 for (i = 0; i < 5; i++) {
8 scanf("%d", &a[i]);
9 }
10
11 return 0;
12}Loop automatically stores values in:
a[0], a[1], a[2], a[3], a[4]7. Processing Array Using Loop
Example: Sum of Elements
int sum = 0;
for (i = 0; i < 5; i++) {
sum = sum + a[i];
}This is impossible without loops in a clean way.
8. Array + Loop = Logic Building
Common operations done using loops:
- Sum
- Maximum / Minimum
- Searching
- Sorting
- Counting
All of these need loops.
9. Using Different Loops with Arrays
for loop (most common)
for (i = 0; i < n; i++)while loop
i = 0;
while (i < n) {
printf("%d ", a[i]);
i++;
}do–while loop
i = 0;
do {
printf("%d ", a[i]);
i++;
} while (i < n);