Pointer Arithmetic
Completed
Read n integers into an array. Using a pointer int *p that you move with p += 2 and p++ (no a[i] when reading values), print the elements at even indexes, then the sum of all elements.
Input
Line 1: n. Line 2: n integers.
Output
Two lines.
Example
Input
6 10 20 30 40 50 60
Output
10 30 50 210
Editor
C
Hints
int *p = a; makes p point at a[0].
p += 2 moves two elements forward; *p reads the element.
Solution explanation
Adding 1 to a pointer moves it by one element, not one byte.
Show solution
#include <stdio.h>
int main() {
int n, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int *p = a;
for (int i = 0; i < n; i += 2) {
if (i > 0) printf(" ");
printf("%d", *p);
p += 2;
}
printf("\n");
int sum = 0;
p = a;
for (int i = 0; i < n; i++) {
sum += *p;
p++;
}
printf("%d\n", sum);
return 0;
}