Consider the following C program:
#include <stdio.h>
void stringcopy (char *, char *);
int main() {
char a[30] = "@#Hello World!";
stringcopy(a, a+2);
printf("%s\n",a);
return 0;
}
void stringcopy(char *s, char *t) {
while (*t)
*s++=*t++;
}Which one of the following will be the output of the program?
View worked solution
Answer: D
Let's trace the execution of the program step-by-step:
1. Initialization:
The character array a is initialized as follows:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| Value | @ | # | H | e | l | l | o | W | o | r | l | d | ! | \0 |
2. Function Call:
Calling stringcopy(a, a+2) sets the pointer s to a[0] and t to a[2].
3. Loop Execution:
The loop while (*t) *s++ = *t++; copies characters from source t to destination s one by one:
- The characters
'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'(from indices 2 to 13) are copied to indices 0 to 11. - When
tpoints toa[14](which is'\0'), the loop conditionwhile (*t)evaluates to false and the loop terminates. - Because the loop terminates before copying, the null-terminator
'\0'is not copied toa[12].
4. Final State of Array a:
Indices 12, 13, and 14 retain their original values:
a[12] = 'd'a[13] = '!'a[14] = '\0'
Thus, the array contents starting from index 0 are "Hello World!d!" followed by '\0'. Printing this string yields Hello World!d!.
Free practice · Your answers on this page are not saved.
