Consider the ๐ถ/๐ถ++ function ๐‘“() given below: void f(char w[]) { intโ€ฆ

2018

Consider theย ๐ถ/๐ถ++ย functionย ๐‘“()ย given below:

void f(char w[])

{

int x=strlen(w); //length of a string

char c;

for (int i=0; i<x; i++)

{

c=w[i];

w[i]=w[x-i-1];

w[x-i-1] =c;

}

}

Which of the following is the purpose ofย ๐‘“()ย ?

  1. A.

    It outputs the contents of the array in reverse order

  2. B.

    It outputs the contents of the array in the original order

  3. C.

    It outputs the contents of the array with the characters shifted over by one position

  4. D.

    It outputs the contents of the array with the characters rearranged so they are no longer recognized as the words in the original phrase

Attempted by 124 students.

Show answer & explanation

Correct answer: B

Answer: The string remains in its original order (the function leaves the array unchanged).

Reasoning:

  • x = strlen(w) gives the length of the string.

  • The loop for (int i = 0; i < x; i++) swaps w[i] with w[x - i - 1] for every index i from 0 to x-1.

  • For indices before the midpoint a pair is swapped once (when i = k) and then swapped back later (when i = x - k - 1). Those two swaps cancel each other.

  • If the length is odd, the middle character is swapped with itself (no change).

  • Net effect: every change is undone later in the loop, so the array ends up in its original order.

  • Important note: the function modifies the array in place and returns void; it does not print or output the string.

Fix to reverse the string (if that was intended): run the loop only up to the midpoint, e.g. for (int i = 0; i < x/2; i++) { swap w[i] and w[x-1-i]; }

A video solution is available for this question โ€” log in and enroll to watch it.

Explore the full course: Mppsc Assistant Professor