C# & .NET Framework Loops — Repeat & Conquer
💡
Exercise 17

While & Do-While — Elevators and Safety Checks 15 XP Easy

Ctrl+Enter Run Ctrl+S Save

Not every job in the city has a fixed number of steps. Sometimes you need to keep going until a condition changes — like an elevator that keeps climbing until it reaches the right floor. That's where while and do-while loops shine.

The while loop — checks the condition before each iteration. If the condition is false from the start, the body never executes.

int floor = 1; while (floor <= 3) { Console.WriteLine($"Elevator at floor {floor}"); floor++; }

Think of it like an elevator with a smart sensor: "Check if we need to go higher. If yes, move up. If no, stop." The sensor checks before the elevator moves.

The do-while loop — guarantees the body runs at least once, then checks the condition. The check happens after the first execution.

int checkNum = 1; do { Console.WriteLine($"Safety check #{checkNum}: PASSED"); checkNum++; } while (checkNum <= 3);

This is like a building safety inspector who always performs at least one check — even if someone says "no checks needed," the inspector does one anyway. Safety first! 🔍

Key difference visualized:

  • while: Check → Run → Check → Run → ... → Check (fails) → Stop
  • do-while: Run → Check → Run → Check → ... → Check (fails) → Stop
  • while might run zero times if the condition is initially false
  • do-while always runs at least once, guaranteed

Here's a quick proof of the difference:

int x = 10; // This never prints — condition is false immediately while (x < 5) { Console.WriteLine("While: this won't print"); } // This prints ONCE — body runs before the check do { Console.WriteLine("Do-while: this prints once!"); } while (x < 5);

⚠️ Watch out for infinite loops! Always make sure your condition will eventually become false. If you forget to increment floor inside the while loop, the elevator gets stuck forever — and nobody wants to be trapped in an elevator! 😱

📋 Instructions
**Mission: Run the elevator and the safety system!** Your city's newest building has a smart elevator and a mandatory safety protocol: 1. **Elevator (while loop):** Start at `floor = 1`. While `floor <= 3`, print `Elevator at floor X` and move up one floor. 2. **Safety checks (do-while loop):** Start at `check = 1`. Use a `do-while` loop to print `Safety check #X: PASSED` while `check <= 3`. 3. After all safety checks, print `All checks complete!` Make sure both loops work together in sequence!
For the while loop: declare `int floor = 1;` before the loop, check `floor <= 3`, and do `floor++` inside. For the do-while: declare `int check = 1;`, use `do { ... check++; } while (check <= 3);`. Don't forget to print `All checks complete!` after the do-while loop.
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.