What is being returned — Pseudocode Aptitude Question
What is being returned: The array A is 1-indexed and holds n elements. What does F(A, n, x) return? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 75 seconds
Question
The array A is 1-indexed and holds n elements. What does F(A, n, x) return?
Function F(Integer A[1..n], Integer n, Integer x)
Integer i, c
Set c = 0
For i = 1 to n
If A[i] == x Then
Set c = c + 1
End If
End For
Return c
End FunctionOptions
- The position of the first occurrence of x in A
- The number of times x occurs in A
- The sum of the elements of A that equal x
- TRUE when x is present in A and FALSE otherwise
Show the answer and the worked solution
Correct answer: B. The number of times x occurs in A
Worked solution
- c starts at 0 and is increased by exactly 1 for every position whose element equals x.
- There is no Break, so all n positions are examined.
- For A = {5, 2, 5, 5} and x = 5 the routine returns 3. The number of times x occurs in A is precisely what c has counted.
Answer: The number of times x occurs in A.
The idea
A counter incremented by 1 under a match is a frequency count; incrementing by A[i] would be a sum, and returning i would be a position. The increment tells you which routine you are looking at.
Shortcut. Test A = {5, 5} with x = 5: F returns 2, which is not a first position (1), a sum (10) or TRUE, so it can only be a count.
Common trap. "TRUE when x is present in A and FALSE otherwise" tempts because c is non-zero exactly when x is present, but the function returns the number itself and never stops early.