Watching the program counter shows the order in which a machine runs its instructions, and how a jump changes it.
What to build
A program that follows the PC through a list of instructions and prints every value it takes.
Requirements
- Execution starts at address 0. Each instruction is either
JMP t(continue at address t),HALT(record it, then stop) or any other word (an ordinary instruction: continue at the next address). - Print the PC value of every instruction that runs, in order, separated by spaces.
- Stop when HALT runs, when the PC moves past the last instruction, or once 30 values have been printed.
Input
A line with n, then n instructions, one per line.
Output
One line of numbers.
Constraints
1 ≤ n ≤ 50; every jump target is from 0 to n − 1.
Example
Input:
4
LOAD
JMP 3
ADD
HALT
Output:
0 1 3
Why it works
A jump replaces the incremented PC with its target; every other instruction leaves the normal plus-one in place. The 30-value limit keeps a loop such as JMP 0 from running forever.
Examples
4 LOAD JMP 3 ADD HALT
0 1 3
3 ADD ADD STORE
0 1 2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Start with pc = 0. In each step, record pc, then work out the next one: pc + 1, or t for a JMP t.
Hint 2
Stop at HALT (after recording it), when pc leaves the program, or after 30 recorded values.
Solution
Show one correct solution (try it yourself first)
n = int(input())
program = [input().split() for _ in range(n)]
pc, seen = 0, []
while pc < n and len(seen) < 30:
seen.append(pc)
parts = program[pc]
if parts[0] == "HALT":
break
pc = int(parts[1]) if parts[0] == "JMP" else pc + 1
print(*seen)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step