2

C while Loop


The while loop is often used when it doesn’t know how many time the loop will be repeated. Here is the sample code for the while loop:

/*
 *
 * while.c
 *
 * Program to demonstrate the use of the while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char type = 'x';
 int album;    // Boolean

 while (type != 'a' && type != 's') {
  printf("Album or single (a for album, s for single)? ");
  scanf("%c", &type);
  album = type == 'a';    // Determine if type is equal to 'a'
  if (type != 'a' && type != 's')
   printf("Errorn");

   // Dummy statement to flush the input
  while (getchar() != 'n' && getchar() != EOF) {
   printf("");
  }
 }

 if (album)
  printf("Albumn");
 else
  printf("Singlen");

 fflush(stdin);
 getchar();
}

As you can see in the code above, format of the while loop is the same as the format of the if statement, except the condition is repeatedly used until the condition is true instead of used only once.

Below is the sample code for the while loop which is specified the number of repeated loops:

/*
 *
 * while2.c
 *
 * Program to demonstrate the use of the while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int counter = 1;
 int total = 0;

 while (counter <= 1000) {
  total = total + counter;
  counter = counter + 1;
 }

 printf("The sum of all numbers from 1 to 1000 is %dn", total);

 fflush(stdin);
 getchar();
}


There are no posts related to C while Loop.

  1. [...] that it’s the same code as the while loop. The difference is that the type variable is not initialized anymore since it uses do…while [...]

  2. [...] forever loops can only used in the for loops, and it’s similar to the while loop for input validation. Related Posts:C do…while LoopC while LoopC for LoopC Loop IntroductionA Simple C Program to [...]