Direction: The procedure given below is required to find and replace certain characters inside an input character string supplied in array A. The characters to be replaced are supplied in array oldc, while their respective replacement characters are supplied in array newc. Array A has a fixed length of five characters, while arrays oldc and newc 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 = “da b”
2. oldc = “cde”, newc = “bcd”
3. oldc = “bca”, newc = “cda”
4. oldc = “abc”, newc = “bac”
-
The tester now tests the program on all input strings of length five consisting of characters ‘a’, ‘b’, ‘c’, ‘d’ and ‘e’ with duplicates allowed. If the tester carries out this testing with the four test cases given above, how many test cases will be able to capture the flaw?
-
- Only 1
- Only 2
- Only 3
- All four
- Only 1
Correct Option: C
Analyzing the flow in the function. Fix an 'i' in the outer loop.
Suppose A[i] = old c[0], then A[i] is set to new c[0] [j = 0].
Now suppose that old c[1]= new c[0]
⇒ A[i] = old c[1] (after the j = 0th iteration)
which means in the next iteration with j = 1; A[i] again gets changed form new c[0] (or old c[1]) to new c[1] which is incorrect.
The current loop should "break" after a match is found and A[i] is replaced.
The inner loop should look like
for (int j = 0; j < 3, j + +)
if (A [i] = = old c[j])
A[j] = new c [j];
break;
The above flow is exposed by the test cases 3 & 4 only. For test 1 and test 2, the expected output is produced by the code. Test 3 Expected A after replacements
= "abcde" → "acdde"
result from code = "abcde" → "addde"
Test 4 Expected "abcde" → "bacde"
result form code "abcde" → "abcde".
∴ Answer is 3 and 4 only (c)