4.4. while

The most basic loop in C is the while loop. A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statments get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again. This cycle repeats until the test condition evaluates to false. If the test condition is false the first time, the statments don't get executed at all. On the other hand if it's test condition never evaluates to false it may continue looping infinitely. To control the number of times a loop executes it's code you usually have at least one variable in the test condition that gets altered in the subsequent block of code. This allows the test condition to become false at some point.

Here's the quick example you are probably expecting. It's a simple guessing game, very simple for the person who is writing the code as they know the answer. When testing this program remember to guess the wrong answer a few times.

Example 4-3. guess_my_number.c

#include <stdio.h>


int
main()
{
  const int MAGIC_NUMBER = 6;
  int guessed_number;

  printf("Try to guess what number I'm thinking of\n");
  printf("HINT: It's a number between 1 and 10\n");

  printf("enter your guess: ");
  scanf("%d", &guessed_number);

  while (guessed_number != MAGIC_NUMBER);
    {
      printf("enter your guess: ");
      scanf("%d", &guessed_number);
    }

  printf("you win.\n")

  return 0;
}
    

The block of code following the while statement will be executed repeatedly until the player guesses the number six.