What will be the output of the following code snippet? char str [] = {'h',…

20242024

What will be the output of the following code snippet?

char str [] = {'h', 'e', 'l', 'l', 'o', '\0'};

str[0] = 'y';

printf("%s", str);

  1. A.

    hello

  2. B.

    yello

  3. C.

    ello

  4. D.

    hyello

Attempted by 82 students.

Show answer & explanation

Correct answer: B

The code initializes a character array str with the characters 'h', 'e', 'l', 'l', 'o', and a null terminator '\0'. This forms a valid C string. The statement str[0] = 'y'; changes the first character from 'h' to 'y'. Since strings in C are mutable arrays, this modification affects the first character. The printf function with the %s format specifier prints characters starting from the first element until it encounters the null terminator. The rest of the characters 'e', 'l', 'l', 'o', and the null terminator remain unchanged, so the output is 'yello'.

Explore the full course: Hexaware Preparation