Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

Up until now, we've looked at ways to execute code once or a fixed number of times. But in the real world, you often don't know how many times a piece of code needs to run. You just know it needs to keep going until a specific condition changes. That's where the while loop comes in.

To show you how this works, let's build a simple fuel gauge simulator for a rocket. We want to print the remaining fuel percentage every second and stop the moment the tank hits zero.

Setting up the fuel tank

First, I'll need a variable to track the fuel. Since we're dealing with a percentage, an integer will do just fine for this example. I'll start it at 100.

int fuel = 100;

while (fuel > 0) {
    printf("Fuel remaining: %d%%\n", fuel);
}

Wait, my terminal is screaming

I just ran that code, and my terminal is scrolling thousands of lines of "Fuel remaining: 100%" per second. I've just created an infinite loop. This is the most common mistake you'll make with while loops, and honestly, I still do it occasionally when I'm rushing.

The problem is that my condition (fuel > 0) is always true. I'm checking the fuel, but I'm never actually using any of it. To fix this, I need to change the value of fuel inside the loop body so that eventually, the condition becomes false.

Burning through the fuel

Let's fix that. I'll subtract a random amount of fuel during each iteration. I'll use a simple decrement for now to keep the logic clean, but the key is that fuel-- (or fuel = fuel - 1) happens inside the curly braces.

int fuel = 100;

while (fuel > 0) {
    printf("Fuel remaining: %d%%\n", fuel);
    fuel--; // This ensures the loop eventually ends
}

Now, the loop checks the condition, prints the value, drops the value by one, and then jumps back to the top to check the condition again. This will repeat exactly 100 times.

Handling the empty state

If you run the code above, you'll notice it stops at 1%. It never actually prints "Fuel remaining: 0%" because as soon as fuel becomes 0, the condition fuel > 0 is false, and the loop exits immediately.

If I want to signal that the rocket has actually run out of fuel, I can just put a final print statement after the loop. Since the loop only exits when the condition is no longer true, anything written immediately after the closing brace is guaranteed to happen only once the loop is finished.

int fuel = 100;

while (fuel > 0) {
    printf("Fuel remaining: %d%%\n", fuel);
    fuel--;
}

printf("Liftoff failed: Out of fuel!\n");

It's a simple pattern, but it's powerful. Whether you're waiting for user input, reading a file until the end, or simulating a physical process, the while loop is your go-to tool when the end goal is a state, not a count.




📋 Practical Task

Build a Digital Safe Combination Lock

Write a program that simulates a digital safe. Create an integer variable called secret_code and set it to any number you like (e.g., 1234). Create another variable called user_guess and initialize it to 0.

Using a while loop, continuously ask the user to enter the code using scanf(). The loop should keep running as long as the user_guess is not equal to the secret_code. Inside the loop, if the guess is wrong, print "Access Denied. Try again."

Once the loop exits (meaning the user finally guessed correctly), print "Click... Safe opened!" to the console.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.