In the last lesson we began at looking at conditionals, which are one kind of control structure in C. In this lesson we will continue in this vein by considering how to do repetition in C. In particular, we will look at while loops.
Let's begin with a simple example. Suppose that you've written a program that asks the user to input a temperature in degrees Kelvin. As you may know, zero degrees Kelvin is ``absolute zero''--the absolute minimum temperature there is. There are no temperatures below absolute zero, and it's physically impossible to cool any object down to absolute zero. This means that the user of your program is expected to input a positive temperature value.
You might write this part of your program like this:
printf("Please enter the temperature in degrees Kelvin: ";
scanf("%f", &temp);
if (temp <= 0.0) {
printf("You must enter a positive temperature.");
}
What is the shortcoming of this segment of code?
Let's think about what we'd really like the program to do. It would be nice if the program could ask the user to input a new, hopefully positive value for temp. In other words, we'd like to have the program repeat the block of statements, asking the user to enter a new value and once again checking it for validity. In fact, you might want to have your program ask the question over and over until the user entered an acceptable value.
In this lesson we'll look at how to use while loops in C to solve problems such as these. We'll also look at the application of while loops to numerical root-finding and summation by studying two problems that we've previously considered in the context of Maple.
Before you go any farther, click below to copy today's example files into your own examples directory.
Click to copy the example files.