Sample Video Frame

Created by Zed A. Shaw Updated 2024-02-17 04:54:36

Exercise 9: 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:

#include <stdio.h>

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

    // need this to add a final newline

    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) {

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.

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

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:

Extra Credit

Previous Lesson Next Lesson

Register for Learn C the Hard Way

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