ProgrammingHardCAT · MBA placement
Two positions in the word "hello" are chosen (the letters at the two positions form a pair, and positions are distinct). The procedure below counts the pairs whose two letters are different. What is printed?
Two positions in the word "hello" are chosen (the letters at the two positions form a pair, and positions are distinct). The procedure below counts the pairs whose two letters are different. What is printed?
count = 0
for i = 0 to n - 2
for j = i + 1 to n - 1
if s[i] != s[j] then count = count + 1
end for
end for
Print count- A. 10
- B. 1
- C. 6
- D. 9
Correct answer: D. 9
The only equal pair is the two l letters, so 10 - 1 = 9 pairs have different letters. Counting all pairs gives 10, counting equal pairs gives 1, and choosing two of the four distinct letters gives 6.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The procedure below counts the cyclic rotations of "abab" that are equal to "abab" itself, checking the rotations obtained by moving k…
- Coin denominations are 1, 4 and 6. The greedy method below pays amount 8 by always taking the largest coin that still fits (coins are…
- Ropes of lengths 1, 2, 3, 4 and 5 are merged two at a time with cost equal to the sum of the two lengths. The greedy merges the two…
- A truck carries at most 10 boxes. The box types are given as (units per box, number of boxes): (5, 3), (4, 2), (3, 4), (2, 5). The greedy…
- The greedy below repeatedly increases the smallest element of the array [3, 1, 2] by 1, three times in total. What is the minimum value of…
- For the function gcd(a, b) written by the procedure below, what is printed for gcd(252, 105)? (The procedure uses repeated remainder…