Sample Video Frame
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);
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.
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.