The procedure given below is required to find and replace certain characters inside an input character string supplied in array . The characters to be replaced are supplied in array , while their respective replacement characters are supplied in array . Array has a fixed length of five characters, while arrays and 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.
If array is made to hold the string “”, which of the above four test cases will be successful in exposing the flaw in this procedure?
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 matches a subsequent character in (where 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 :
- Test Case 3: ,
- Expected: should be replaced by .
- Actual: At , . For , matches and is replaced by . Next, for , the updated matches and is replaced again by . This results in an incorrect final character .
- Test Case 4: ,
- Expected: should be replaced by .
- Actual: At , . For , matches and becomes . For , the updated matches and is replaced again by . This results in an incorrect final character .
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.
