Video Coming Soon...

Created by Zed A. Shaw Updated 2026-11-26 20:48:52

WARNING: This exercise needs a full review to match recent changes to C. If you find problems please report them with the bug feature (top right, bug icon).

09: While-Loop and Boolean Expressions

The first looping construct I'll show you is the while-loop, and it's the simplest, useful loop you could possibly use in C. Here's this exercise's code for discussion:

View Source file ex9.c Only

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i = 0;
    while (i < 25) {
        printf("%d", i);
        i++;
    }

    // need this to add a final newline
    printf("\n");

    return 0;
}

From this code, and from your memorization of the basic syntax, you can see that a while-loop is simply this:

while(TEST) {
    CODE;
}

It simply runs the CODE as long as TEST is true (1). So to replicate how the for-loop works, we need to do our own initializing and incrementing of i. Remember that i++ increments i with the post-increment operator. Refer back to your list of tokens if you didn't recognize that.

What You Should See

The output is basically the same, so I just did it a little differently so that you can see it run another way.

View Source file ex9.sh-session Only

$ make ex9
cc -Wall -g    ex9.c   -o ex9
$ ./ex9
0123456789101112131415161718192021222324 
$

How to Break It

There are several ways to get a while-loop wrong, so I don't recommend you use it unless you must. Here are a few easy ways to break it:

Capability Assessment

  1. Make the loop count backward by using i-- to start at 25 and go to 0.
  2. Write a few more complex while-loops using what you know so far.
Previous Lesson Next Lesson

Register for From Impostor to Programmer

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.