LearnFrenzy
Sign in Take a free test

Pointers · Predict the Output · Question 12

Output of a pointer loop that steps by 2 in C Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>

int main(void) {
    int a[] = {2, 4, 6, 8};
    int sum = 0;
    for (int *p = a; p < a + 4; p += 2)
        sum += *p;
    printf("%d\n", sum);
    return 0;
}
  • A 20
  • B 8 Correct
  • C 12
  • D 6
Correct Answer: Option B

p visits a[0] and a[2] only, because it moves 2 elements each time: 2 + 6 = 8. The next step would be a + 4, which ends the loop.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular