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);
}
- A.
ABCDE\0
- B.
ABCDE
- C.
BCDEF
- 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.
i is declared before the loop (int i;), so it remains in scope after the loop ends.
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].
When the condition i < 5 fails, the loop exits with i = 5.
The next statement, *(array + i) = '\0', legally uses i = 5 (still in scope) and writes a null terminator into array[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).