What will be the output of the following C++ program? # include <iostream>…

2018

What will be the output of the following C++ program?
# include <iostream>
using namespace std;
int main(){
char array[10];
int i;
for(i = 0; i < 5; i++)
*(array + i) = 65 + i;
*(array + i) = '\0';
cout << array;
return(0);
}

  1. A.

    ABCDE\0

  2. B.

    ABCDE

  3. C.

    BCDEF

  4. D.

    CDEFG

Attempted by 122 students.

Show answer & explanation

Correct answer: B

Concept: A variable declared inside a for-loop's own init-statement (for(int i = ...)) is scoped to that for-statement only — no statement after the loop can reference it; to use the loop counter's final value later, the counter must be declared before the loop. Separately, when a char array is used as a C-string, cout prints only the characters up to (and excluding) the first null terminator '\0' — any byte stored after that position is invisible on screen even though it still exists in memory.

  1. i is declared before the loop (int i;), so it remains in scope after the loop ends.

  2. The loop runs for i = 0 to 4, executing *(array + i) = 65 + i, which stores ASCII codes 65-69 — the characters 'A', 'B', 'C', 'D', 'E' — into array[0] through array[4].

  3. When the condition i < 5 fails, the loop exits with i = 5.

  4. The next statement, *(array + i) = '\0', legally uses i = 5 (still in scope) and writes a null terminator into array[5].

  5. cout << array prints the characters starting at array[0] and stops the instant it reaches the null terminator at array[5], so it prints A, B, C, D, E — i.e. ABCDE.

Cross-check: Listing the array byte-by-byte confirms indices 0-4 hold 'A'-'E' and index 5 holds '\0' with nothing else in between, so ABCDE is exactly what reaches the console — matching the option ABCDE, and ruling out ABCDE\0 (which wrongly treats the terminator as visible) as well as BCDEF and CDEFG (which shift the starting ASCII value and index).

Explore the full course: Uppsc Polytechnic Lecturer 2025 Cs