You are reading without signing in. Sign in or continue as guest to take quizzes and keep XP.
Loops and switch
Repeat until success with while, unroll constant for loops, pick a branch with switch.
- Write a repeat-until-success loop and explain why it terminates.
- Know when a for loop is unrolled and when it stays a loop.
- Read a switch as an if/else chain.
Repeat until success
Each round prepares q0 in |+⟩ and measures it. The loop exits only when it reads 0, then flips q1. Simulate: every shot ends in c = 10; the number of rounds varies, the result does not.
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
h q[0];
c[0] = measure q[0];
while (c[0] == true) {
x q[0];
h q[0];
c[0] = measure q[0];
}
x q[1];
c[1] = measure q[1];
Repeat-until-success is the workhorse of many fault-tolerant protocols: try a probabilistic step, check a flag bit, retry on failure. The expected number of rounds is 1/p for success probability p, here two.
for uint i in [0:2] { // constant bounds: unrolled to h q[0]; h q[1]; h q[2];
h q[i];
}
for uint k in [0:3] { // contains break: stays a real loop
c[1] = measure q[1];
if (c[1]) { break; }
x q[1];
}
switch (c) { // one arm by register value
case 0 { x q[0]; }
case 1, 2 { z q[0]; }
default { h q[0]; }
}A while loop re-prepares |+⟩ and measures until it reads 0. Expected number of rounds?
Sign in to answer and earn XP; you will come back to this lesson.
Why does QubitLab unroll `for uint i in [0:2] { h q[i]; }`?
Sign in to answer and earn XP; you will come back to this lesson.
while repeats on a measured flag, for with constant bounds is unrolled, switch chooses an arm by value. All three draw as frames and run on the shot simulator.
Up next: Teleportation with feed-forward