Practice While Loop in CS Thinking

Use these practice problems to test your method after reviewing the concept explanation and worked examples.

Quick Recap

A control structure that repeats a block of code as long as a specified condition remains true. The condition is checked before each iteration, and if it is false from the start, the loop body never executes at all.

A while loop is like 'keep going until...' β€” keep stirring the soup WHILE it's not boiling. Keep asking for a password WHILE the password is wrong.

Showing a random 20 of 50 problems.

Example 1

medium
Trace: `i=2; while i<=16: i*=2`. Final ii and iteration count?

Example 2

medium
Trace: `a=0; b=1; while a<10: a,b = b, a+b`. Final aa?

Example 3

medium
Trace: `n=123; sum=0; while n>0: sum+=n%10; n=n//10`. Final sum?

Example 4

easy
Spot the bug: `i=0; while i<3: print(i)`. What goes wrong?

Example 5

medium
Trace: `i=0; while i<5: i+=2; print(i)`. What prints?

Example 6

medium
Trace: `i=0; count=0; while i<10: if i%3==0: count+=1; i+=1`. Final count?

Example 7

easy
Trace: `i=1; total=0; while i<=3: total+=i; i+=1`. Final total?

Example 8

easy
A while loop with a condition that never becomes false creates an ____ loop.

Example 9

medium
Trace: `i=0; while True: if i>=3: break; print(i); i+=1`. What prints?

Example 10

medium
Trace: SET n = 1. WHILE n < 100: n = n * 2. OUTPUT n. How many iterations?

Example 11

medium
Trace: `s='hello'; i=0; out=''; while i<len(s): out+=s[i].upper(); i+=1`. Final out?

Example 12

medium
Trace: `n=100; c=0; while n>1: n=n//2; c+=1`. Final cc?

Example 13

challenge
Trace: `i=1; j=10; while i<j: i+=2; j-=1; print(i,j)` give the final i and j and iteration count.

Example 14

easy
Does this loop body ever run? `x=5; while x<3: print('hi')`.

Example 15

medium
Trace: `n=7; sum=0; while n>0: sum+=n%10; n=n//10`. Final sum?

Example 16

medium
Trace: `i=1; while i<=8: i*=2; print(i)`. What prints and how many iterations?

Example 17

hard
Trace: `n=20; r=0; while n>0: if n%2==1: r+=1; n=n//2`. Final rr?

Example 18

hard
Trace: `lo=0; hi=10; target=7; arr=[1,3,5,7,9,11,13,15,17,19]; while lo<hi: m=(lo+hi)//2; if arr[m]<target: lo=m+1; else: hi=m`. Final lo?

Example 19

easy
Spot the bug: `n=3; while n>0: print('hi')`. What goes wrong?

Example 20

medium
Trace: `i=10; while i>1: i//=2; print(i)`. What prints?