OA. free
Free
Texas Instruments Core Cs & Systems Core Computer Science Medium

Predict the output of the following C code snippet:

Texas Instruments technical mcq question, verified with a worked answer. Free to practise - no sign-up.

Predict the output of the following C code snippet:

#include <stdio.h>

int main(void) {
    int numbers[5];
    int *p;
    p = numbers;
    *p = 10;
    p++;
    *p = 20;
    p = &numbers[2];
    *p = 30;
    p = numbers + 3;
    *p = 40;
    p = &numbers[4];
    *(p + 0) = 50;
    for (int n = 0; n < 5; n++)
        printf("%d,", numbers[n]);
    return 0;
}
Choose one option.
Show answer & explanation
Answer: A. 10,20,30,40,50,

The code sequentially assigns values to each element of the 'numbers' array using various pointer arithmetic techniques (direct assignment, pointer incrementing, and indexing). The loop then prints each element followed by a comma.

Step-by-step Derivation:
Step 1: int numbers[5]; declares an array of 5 integers. p = numbers; sets pointer p to the address of numbers[0].
Step 2: *p = 10; assigns 10 to numbers[0].
Step 3: p++; moves the pointer to the next integer address. *p = 20; assigns 20 to numbers[1].
Step 4: p = &numbers[2]; explicitly sets p to the address of the third element. *p = 30; assigns 30 to numbers[2].
Step 5: p = numbers + 3; uses pointer arithmetic to point to the fourth element. *p = 40; assigns 40 to numbers[3].
Step 6: p = &numbers[4]; sets p to the address of the fifth element. *(p + 0) = 50; is equivalent to *p = 50;, assigning 50 to numbers[4].
Step 7: The for loop iterates from n = 0 to 4, printing numbers[0] through numbers[4] each followed by a comma: 10,20,30,40,50,.