Pointer loop
- C course
- Beginner
- Lesson 80/116
- 5 min
Learn to loop over an array with a pointer.
Pointer loop
You can walk an array without using indices. Define a start pointer and an end pointer and print every element between them.
int arr[3] = {7, 8, 9};
int *p = arr; /* start */
int *end = arr + 3; /* end */
while (p < end) { printf("%d", *p); p++; }p++ jumps to the next element each step. The p < end condition keeps the loop going until the last element.
The end pointer pattern
The pattern end = arr + n gives a pointer to the end of the array. end points one past the last element; it is out of the array and used only for comparison.
int arr[3] = {7, 8, 9};
int *end = arr + 3; /* arr[3] must not be read */
for (int *p = arr; p < end; p++) {
printf("%d ", *p);
}This pattern resembles C++ iterators and keeps loops clean.
Practice Print with a pointer loop
Define int arr[3] = {7, 8, 9};. Define start and end pointers with int *p = arr; and int *end = arr + 3;. Inside while (p < end) print the element with printf("%d\n", *p); and advance with p++. Output should be 7, 8, 9.
Starter code
#include <stdio.h>
int main(void) {
int arr[3] = {7, 8, 9};
/* set p to start, end to arr+3; while p < end print *p and advance p */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int arr[3] = {7, 8, 9};
int *p = arr;
int *end = arr + 3;
while (p < end) {
printf("%d\n", *p);
p++;
}
return 0;
}Expected output
7 8 9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 p is start, end is end. What is the loop condition?
- p < end Correct answer
- p > end
- p == end
- p = end
Explanation: p < end keeps the loop going until the last element.
2 Match loop parts
| Term | Meaning |
|---|---|
p++ |
one forward |
p < end |
loop condition |
*p |
current value |
end = arr + n |
end pointer |
3 Complete the loop step
for (int *p = arr; p < end; ____) { /* ... */ }
for (int *p = arr; p < end; p++) { /* ... */ }
Explanation: p++ jumps to the next element each step.