// Example program #1 from Chapter 14 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter14ex1.c
/* This program increases a counter from 1 to 5, printing updates
and then counts it back down to 1. However, it uses while loops and
the increment and decrement operators */
#include <stdio.h>
main()
{
int ctr = 0;
while (ctr < 5)
{
printf("Counter is at %d.\n", ++ctr);
}
while (ctr > 1)
{
printf("Counter is at %d.\n", --ctr);
}
return 0;
}
You might be getting a little sick of our “Counter is at...” code example, but using different statements,
formats, and functions to accomplish the same task is an excellent method to show how new skills can
help you execute a task differently or more efficiently.
When comparing this listing to the previous times you wrote programs to accomplish the same goal,
you can see that your number of lines decreases significantly when using a loop. Previously, you
needed to type five printf() statements for the count up and then type another four to count down.
However, by using while loops, you need only one printf() statement in the count up loop and
one in the count down loop, which streamlines the program.
The variable ctr is initially set to 0. The first time while executes, i is less than 5, so the while
condition is true and the body of the while executes. In the body, a newline is sent to the screen
and ctr is incremented. The second time the condition is tested, ctr has a value of 1 , but 1 is
still less than 5, so the body executes again. The body continues to execute until ctr is incremented
to 5. Because 5 is not less than 5 (they are equal), the condition becomes false and the loop stops
repeating. The rest of the program is then free to execute, leading to the second while loop that
counts down from 5 to 1, when it eventually makes the second condition false and ends the loop.
Tip
If ctr were not incremented in the while loop, the printf() would execute
forever or until you pressed Ctrl+Break to stop it.