in Unknown Category edited by
1,145 views
0 votes
0 votes

Consider the $C/C++$ function $f()$ 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 $f()$ ?

  1. It outputs the contents of the array in reverse order
  2. It outputs the contents of the array in the original order
  3. It outputs the contents of the array with the characters shifted over by one position
  4. It outputs the contents of the array with the characters rearranged so they are no longer recognized as the words in the original phrase
in Unknown Category edited by
by
1.1k views

1 Answer

1 vote
1 vote
let i be a position in array from left side, then (x-i-1) should be the i$^{th}$ position from the right.

When for loop starts, upto the mid point,

c = w[i]

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

w[x-i-1] = c

swaps the elements which are at i$^{th}$  and (x-i-1)$^{th}$ ===> reverse the input order.

 

From the mid point to end, again same code applied

reverse(revere of input order) = original order of input preserve at the end.

 

PS: let take input length(x)=7 ===> maximum index = 6 only due to strlen returns size of the string without null character.

when i=0, x-i-1=6 ==> a[0] swapped with a[6]

when i=6, x-i-1 =0 ==> a[6] swapped with a[0].

∴ original order preserved.
Answer:

Related questions