Challenge: Sum with a Pointer
Completed
Read n and n numbers into an array. Then add them up by walking through the array with a pointer (int *p = nums; and p++), and print the total.
Input
n (1 ≤ n ≤ 100), then n integers.
Output
The total.
Example
Input
4 1 2 3 4
Output
10
Editor
C
Hints
Start with int *p = nums;
*p is the current number; p++ moves to the next one.
Solution explanation
Each p++ moves the pointer one item forward, so *p visits every number in turn.
Show solution
#include <stdio.h>
int main() {
int n;
int nums[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
int *p = nums;
int total = 0;
for (int i = 0; i < n; i++) {
total += *p;
p++;
}
printf("%d\n", total);
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module