While Loops

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:

  1. 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.
  2. 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?”
  3. Scan the viewer’s answer, using scanf.
  4. 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.
  5. Respond to the correct answer, if the loop is exited.

Let’s fill in each of these with C code:

  1. The condition: while (answer != 1971) {
  2. The question: printf(“\nWhat year was C developed? “);
  3. Scan the viewer’s answer: scanf(“%d”, &answer);
  4. 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.
  5. 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) { 

printf(“\nWhat year was C developed? “);


scanf(“%d”, &answer);

}
printf(“\nYes, C was developed in 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.

Published by Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Join the Conversation

2 Comments

Leave a comment

Your email address will not be published. Required fields are marked *