Traversal
Beginner · 6 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Traversal means visiting every item in a list exactly once, usually from the first to the last, so you can print it, total it, filter it or check it. It is the most common move in everyday programming, and doing it well is the foundation of every loop you write.
Practical use cases
- Web app: Totalling an invoice with many lines. An invoice page shows 40 line items and a grand total. The code walks through the lines once, adding price times quantity to a running total, and prints each row on the way. One pass gives both the table and the total, so there is no need for a second loop.
- Web app: Exporting orders to CSV. An admin clicks Download CSV for last month's orders. The script walks through every order once, writing one line per order into the file. Done in a single pass and written as it goes, even 100,000 orders export without loading everything into memory at once.
- System: Image and log processing. A photo is a long list of pixels and a server log is a long list of lines. Brightening a photo or counting the errors in a log means walking through each item once. Every image filter and log analyser starts with this same simple walk from first to last.
The story: Ramesh and the Long Corridor
Every morning Ramesh the tiffin-wala climbed to the fifth floor of Shanti Apartments. The corridor had flats in one straight line, 0, 1, 2, 3, 4, and each door had a little note: how many tiffins that family ordered.
On his first day Ramesh jumped around. He did flat 3, then flat 0, then flat 4, and forgot flat 2 completely. A hungry uncle in flat 2 was not amused. His boss told him, "Do not be clever. Start at the first door, finish at the last, and never skip."
From then on Ramesh walked in order, kept a small counter of tiffins delivered, and nobody went hungry. In the evening he collected empty boxes by walking the corridor backward, and on busy days he served only every second flat first.
That simple walk, visiting each item of a list in a planned order, is called traversal. Almost every array algorithm begins with it.
How to spot this problem, and where you need it
You need to look at, total, transform or collect something from every item in a list, and want to do it cleanly in one pass without missing items or visiting them twice.
Signs you need it
- The task says for each, all items, every row, total, print, count, or collect, and no item can be skipped.
- You are nesting loops or calling a counting function repeatedly on the same list when a single pass could collect everything.
- Off-by-one bugs: the first or last item is missing from your report, or you see a blank entry at the end.
Where to use it in a project
- Rendering lists and tables on a page, such as cart lines, search results or the rows of an admin report.
- Exports, totals, statistics and validations that must read all records, for example a nightly billing job.
The solution
Decide the direction and the start and end positions. Create the variables you need, like a total, a counter or a result array, before the loop. Then step through the list one position at a time, updating everything you need in that single pass. Stop exactly after the last item. Prefer collecting every result in one walk instead of walking again for each question.
Payoff: Before: three separate loops to get rows, total and count. After: one pass produces all three, and a 100,000-row export stays quick.
Explain it like I am 8
Imagine a row of toy shelves. Touching every toy, one by one, from left to right, without missing any, is traversal. You can also walk right to left, or touch every second toy.
How it works, step by step
- Put a finger (an index,
i) on the first item:i = 0. - Do your work with
arr[i]: add it, print it, check it. - Move the finger one step:
i = i + 1. - Stop when
ireaches the length of the array. The last valid index islength - 1. - For backward, start at
length - 1and go down to 0. For every second item, jump by 2.
The code in four languages
PHP
<?php
$flats = [4, 8, 15, 16, 23]; // tiffins per flat
// 1. Forward walk with a running total
$total = 0;
for ($i = 0; $i < count($flats); $i++) {
$total += $flats[$i];
}
echo "Total: $total" . PHP_EOL;
// 2. Backward walk: last index down to 0
$backward = [];
for ($i = count($flats) - 1; $i >= 0; $i--) {
$backward[] = $flats[$i];
}
echo "Backward: " . implode(', ', $backward) . PHP_EOL;
// 3. Every second flat (step of 2)
$skipped = [];
for ($i = 0; $i < count($flats); $i += 2) {
$skipped[] = $flats[$i];
}
echo "Every second: " . implode(', ', $skipped) . PHP_EOL;JavaScript
const flats = [4, 8, 15, 16, 23]; // tiffins per flat
// 1. Forward walk with a running total
let total = 0;
for (let i = 0; i < flats.length; i++) {
total += flats[i];
}
console.log('Total: ' + total);
// 2. Backward walk: last index down to 0
const backward = [];
for (let i = flats.length - 1; i >= 0; i--) {
backward.push(flats[i]);
}
console.log('Backward: ' + backward.join(', '));
// 3. Every second flat (step of 2)
const skipped = [];
for (let i = 0; i < flats.length; i += 2) {
skipped.push(flats[i]);
}
console.log('Every second: ' + skipped.join(', '));Java
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] flats = {4, 8, 15, 16, 23}; // tiffins per flat
// 1. Forward walk with a running total
int total = 0;
for (int i = 0; i < flats.length; i++) {
total += flats[i];
}
System.out.println("Total: " + total);
// 2. Backward walk: last index down to 0
List<Integer> backward = new ArrayList<>();
for (int i = flats.length - 1; i >= 0; i--) {
backward.add(flats[i]);
}
System.out.println("Backward: " + backward.toString().replaceAll("[\\[\\]]", ""));
// 3. Every second flat (step of 2)
List<Integer> skipped = new ArrayList<>();
for (int i = 0; i < flats.length; i += 2) {
skipped.add(flats[i]);
}
System.out.println("Every second: " + skipped.toString().replaceAll("[\\[\\]]", ""));
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// joinInts turns [4 8 15] into "4, 8, 15".
func joinInts(nums []int) string {
parts := make([]string, len(nums))
for i, n := range nums {
parts[i] = strconv.Itoa(n)
}
return strings.Join(parts, ", ")
}
func main() {
flats := []int{4, 8, 15, 16, 23} // tiffins per flat
// 1. Forward walk with a running total
total := 0
for i := 0; i < len(flats); i++ {
total += flats[i]
}
fmt.Println("Total:", total)
// 2. Backward walk: last index down to 0
var backward []int
for i := len(flats) - 1; i >= 0; i-- {
backward = append(backward, flats[i])
}
fmt.Println("Backward:", joinInts(backward))
// 3. Every second flat (step of 2)
var skipped []int
for i := 0; i < len(flats); i += 2 {
skipped = append(skipped, flats[i])
}
fmt.Println("Every second:", joinInts(skipped))
}Time: O(n) · Extra space: O(1). You touch each of the n items once, and the counter needs no extra room.
Watch out for
- Off-by-one: using
i <= count($arr)reads one slot past the end. Valid indexes stop atlength - 1. - Changing the array (adding or removing items) while looping over it, which makes you skip or repeat items.
- Starting a backward walk at
lengthinstead oflength - 1.
Quick check
- An array has 5 items. What is the last valid index?
- 5
- 4
- 6
- How many times is each item visited in one normal forward traversal?
- Twice
- Once
- It depends on the values
- Which loop step visits every second item?
- i++
- i--
- i += 2