While Loops
A while loop repeats a function until a condition is met.
Simple while loops
Have you ever kept repeating a question until someone gives you the correct answer? (Teachers do this all the time.) This is called a while loop. For example, let’s ask the viewer what year C was developed. The correct answer is 1971, so if the viewer does not answer 1971, we’ll repeat the question.
The symbol for “does not equal” is !=. We will use this in our simple while loop.
A simple while loop has five parts:
- The condition, which is usually written as a negative (!=), like “If the answer does NOT equal 1971.” If this condition is met, the loop will repeat to ask the question again.
- The question, which is written INSIDE the while loop. This insures that it will repeat if the condition is met. Let’s ask “What year was C developed?”
- Scan the viewer’s answer, using scanf.
- Close the loop. If the viewer does not answer 1971, then the loop will repeat. If the answer is 1971, the viewer will exit the loop.
- Respond to the correct answer, if the loop is exited.
Let’s fill in each of these with C code:
- The condition: while (answer != 1971) {
- The question: printf(“\nWhat year was C developed? “);
- Scan the viewer’s answer: scanf(“%d”, &answer);
- Close the while loop: }
If the viewer’s answer meets the condition, then the question will repeat.
If the viewer’s answer does NOT meet the condition, then the viewer will exit the loop. - Respond to a correct answer: printf(“\nYes, C was developed in 1971.”);
Let’s put these together in a C program:
#include<stdio.h> void main( ) { int answer; while(answer != 1971) {
}
|
Type this source code in your editor and save it as while.c then compile it, link it, and run it.
Continue on to For Loops.
Leave a comment