Skip to content
Official PYQ · 2013

GATE CS 2013 Q51 — Arrays, Stacks and Queues

Explain with AI

The procedure given below is required to find and replace certain characters inside an input character string supplied in array AA. The characters to be replaced are supplied in array oldcoldc, while their respective replacement characters are supplied in array newcnewc. Array AA has a fixed length of five characters, while arrays oldcoldc and newcnewc contain three characters each. However, the procedure is flawed.

void find_and_replace (char *A, char *oldc, char *newc) {
    for (int i=0; i<5; i++)
        for (int j=0; j<3; j++)
            if (A[i] == oldc[j])
                A[i] = newc[j];
}


The procedure is tested with the following four test cases.

  1. oldc=“abc”,newc=“dab”oldc = “abc”, newc = “dab”     
  2. oldc=“cde”,newc=“bcd”oldc = “cde”, newc = “bcd”
  3. oldc=“bca”,newc=“cda”oldc = “bca”, newc = “cda”     
  4. oldc=“abc”,newc=“bac”oldc = “abc”, newc = “bac”

If array AA is made to hold the string “abcdeabcde”, which of the above four test cases will be successful in exposing the flaw in this procedure?

Choose one option
View worked solution

Answer: C

The flaw in the given procedure is that the inner loop continues to run even after a character replacement has occurred. If a newly replaced character at A[i]A[i] matches a subsequent character in oldc[j]oldc[j] (where jj is larger than the index of the first match), it undergoes a second replacement in the same pass.

Let's test the cases with the initial string A="abcde"A = \text{"abcde"}:

  • Test Case 3: oldc="bca"oldc = \text{"bca"}, newc="cda"newc = \text{"cda"}
    • Expected: A[1]=’b’A[1] = \text{'b'} should be replaced by ’c’\text{'c'}.
    • Actual: At i=1i=1, A[1]=’b’A[1] = \text{'b'}. For j=0j=0, A[1]A[1] matches oldc[0]=’b’oldc[0] = \text{'b'} and is replaced by newc[0]=’c’newc[0] = \text{'c'}. Next, for j=1j=1, the updated A[1]=’c’A[1] = \text{'c'} matches oldc[1]=’c’oldc[1] = \text{'c'} and is replaced again by newc[1]=’d’newc[1] = \text{'d'}. This results in an incorrect final character ’d’\text{'d'}.
  • Test Case 4: oldc="abc"oldc = \text{"abc"}, newc="bac"newc = \text{"bac"}
    • Expected: A[0]=’a’A[0] = \text{'a'} should be replaced by ’b’\text{'b'}.
    • Actual: At i=0i=0, A[0]=’a’A[0] = \text{'a'}. For j=0j=0, A[0]A[0] matches oldc[0]=’a’oldc[0] = \text{'a'} and becomes ’b’\text{'b'}. For j=1j=1, the updated A[0]=’b’A[0] = \text{'b'} matches oldc[1]=’b’oldc[1] = \text{'b'} and is replaced again by newc[1]=’a’newc[1] = \text{'a'}. This results in an incorrect final character ’a’\text{'a'}.

Both Test Cases 3 and 4 result in unintended multiple replacements, exposing the flaw in the procedure.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Arrays, Stacks and Queues questions