Lessons 11–15 · About 60 min per lesson

Loops and state updates

Repeat a task while carrying the latest stock from one step to the next.

Lesson breakdown

  1. Lesson 11

    Repeat a fixed number of times with range and for, checking its endpoints.

  2. Lesson 12

    Read several requests in a loop and add up their demand.

  3. Lesson 13

    Deduct stock after approved requests and verify the remainder in a trace table.

  4. Lesson 14

    Use while to read until a sentinel and inspect what makes the loop stop.

  5. Lesson 15

    Test zero requests, exact depletion and processing that continues after an unfilled request.

Worked example

Stock is 7 kg. Process requests for 5, 4 and 2 kg in order.

How to solve it

Approve the first request and retain 2 kg. Skip the request for 4 kg, keeping the 2 kg, then approve the final request and finish at 0.

Assignment

Read starting stock, a request count and each demand. Print Enough or Wait for each request, then print the remaining stock.

Check your result

Stock 7 and requests 8 and 7 → Wait, Enough, 0. Zero requests leave the original stock.