Dry run this loop and tell me the output (pseudocode with nested loops).

How to solve pseudocode and nested-loop output questions in the Infosys test and interview: a trace table method with two worked examples and the common traps.

0 0
Read Time:1 Minute, 37 Second

Pseudocode questions give you a short program and ask for the output. They reward careful tracing, not guessing. The method is always the same: write a table with one column per variable and one row per step.

Worked example 1

count = 0
for i = 1 to 4
    for j = i to 4
        if (i + j) mod 2 == 0
            count = count + 1
print count

List the (i, j) pairs and mark the ones with an even sum:

i=1: j=1(2 ✓) j=2(3) j=3(4 ✓) j=4(5)   -> 2
i=2: j=2(4 ✓) j=3(5) j=4(6 ✓)          -> 2
i=3: j=3(6 ✓) j=4(7)                   -> 1
i=4: j=4(8 ✓)                          -> 1
count = 6

Output: 6.

Worked example 2: a pattern

for i = 1 to 3
    for j = 1 to i
        print j (no new line)
    print new line
1
12
123

The inner loop runs i times, so the first row has one number and the third has three.

Traps the test sets

  • Whether “to” includes the end value. In these tests it usually does; check the question.
  • The inner loop starting from i rather than 1.
  • Integer division: 7 / 2 is 3, and mod with negative numbers.
  • A variable changed inside the loop that also controls it.
  • Where the print sits: inside the inner loop, the outer loop, or after both.
  • Short-circuit: in a && b, b is not evaluated when a is false.

Tips

  • Count iterations first: nested loops of 1..n and i..n run n(n+1)/2 times, a quick sanity check.
  • Do not skip rows to save time; most mistakes come from skipping.
  • In the online test, eliminate options that are impossible (for example an odd count when only pairs are counted).

This answer was written by Debugger’s Space as practice material. See how Infosys hires, step by step, and more Infosys practice questions.

Previous post Given an array, move all zeros to the end while keeping the order of other numbers.
Next post Print the Fibonacci series up to N, then explain recursion versus a loop.
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Close
0
Would love your thoughts, please comment.x
()
x