C
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Arrays and Strings
-
Section 5: Pointers
-
Section 6: Memory Management
-
Section 7: Structures and Unions
-
Section 8: The Preprocessor and Build Process
-
Section 9: Standard Library: stdio.h
-
Section 10: Standard Library: stdlib.h
-
Section 11: Standard Library: string.h
-
Section 12: Standard Library: ctype.h and wctype.h
-
Section 13: Standard Library: math.h, complex.h, fenv.h, tgmath.h
-
Section 14: Standard Library: Type and Limit Headers
-
Section 15: Standard Library: Error Handling and Debugging
-
Section 16: Standard Library: Localization and Encoding
-
Section 17: Standard Library: time.h
-
Section 18: Standard Library: Concurrency (C11)
-
Section 19: POSIX and System Programming (unistd.h)
-
Section 20: More Data Structures
-
Section 21: Algorithms in C
-
Section 22: Bitwise Operations
-
Section 23: Command-Line Programs
-
Section 24: Debugging and Best Practices
-
Section 25: Compiler and Language Internals
-
Section 26: Embedded and Cross-Platform Considerations
-
Section 27: Networking Basics
-
Section 28: Practical Projects
-
Section 29: Interview Practice
-
Section 30: C23 Modern Features
-
Section 31: More Practice and Review
23: While Loops
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.
There are no comments for now.