Nearby lessons
60 of 124C - Array with Loop
Arrays and loops are made for each other. Learn the standard traversal patterns in C — filling, printing, searching, summing, copying, shifting and simple sorting — using for, while and do while.
The Three Loops, One Job
Any of C's loops can walk an array. The for loop wins because it keeps the counter, the limit and the step together:
Filling an Array
A loop can fill from a formula or from user input. Here both, side by side:
Copying an Array
b = a; is not legal C. Copy element by element — this is why the loop matters:
break and continue
break leaves the loop entirely; continue skips to the next element:
Shifting Elements
Deleting from the middle means shifting everything after it one place left — a classic loop exercise:
Nested Loops — Bubble Sort
Comparing every pair needs two loops. Bubble sort repeatedly swaps neighbours until the array is ordered:
Merging Two Arrays
Two loops, one destination index that keeps counting across both:
Frequency Counting
Use the value itself as the index of a counter array — a fast, loop-driven counting technique:
Common Mistakes
| Mistake | Effect |
|---|---|
i <= size | Reads one element past the end |
Forgetting i++ in a while | Infinite loop |
b = a; to copy | Compiler error — use a loop |
Shifting with i < size | Reads a[size], out of bounds |
Declaring i inside and using it outside | Out-of-scope error |
count[a[i]]++ only works if every value in a is a valid index into count. A single value of 15 in a 10-element counter array corrupts memory silently. Always know your value range before using this trick.- The for loop is the natural choice: init, condition, update in one line.
- Always loop with i < size.
- Copy arrays element by element — b = a does not work.
- Nested loops handle sorting and comparison of pairs.
- break exits early; continue skips one element.