C Reverse array traversal
Read an ordered receipt history from the most recent entry to the earliest.
A simple example
Reverse array traversal
- Start with A, B, C
- Do this Read in reverse order
- Result C, B, A
Syntax
receipts[i - 1]
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonRead a receipt history newest first
A shop archives receipts in the order they were issued. The returns counter needs the newest receipt at the top of its screen without rearranging the archive for the accounting team.
#include <stdio.h>
int main(void) {
const char *receipts[] = {"R1", "R2", "R3"};
size_t count = sizeof receipts / sizeof receipts[0];
for (size_t i = count; i > 0; --i) {
printf("%s%s", i == count ? "" : ", ", receipts[i - 1]);
}
return 0;
}
R3, R2, R1
The counter sees receipt R3 first and R1 last.
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. The coordinator needs to visit the entries in reverse order on the return trip. Read the order from the final entry back to the first.
Work from the delivery round
A courier has three labelled stops in route order. The coordinator needs to visit the entries in reverse order on the return trip. Read the order from the final entry back to the first.
What to watch for
Use i > 0 before subtracting one from an unsigned index. Testing an unsigned index for negativity cannot end a reverse loop.