HIDE NAV

C While Loop

Three demostrations of the basic syntax for a while loop. The first program uses a while loop to repeat a block of code a set number of times - a counting loop. The second uses a control variable to conditionally exit looping code. The third is an infinite loop (because the condition never evaluates false) that is terminated by the keyword break

.

counting_while_loop.c


#include <stdio.h>

int main() {
  int counter = 0;
  int repeatTimes = 20;

  puts("this is a counting loop... we're going to count.");
  puts("how many times?");
  scanf("%d",&repeatTimes);
  puts("now counting....");

  while(counter < repeatTimes){
    printf("%d\n", counter);
    counter = counter + 1;
  }
  puts("done.");
  return 0;
}

control_variable_while_loop.c


#include <stdio.h>

int main() {
  int keepLooping = 1;

  while(keepLooping){
    // note: loop continues until the user enters 0 because all non-zero values represent 'true' in C.
    puts("loop program... Keep going? [yes = 1]  [no = 0]");
    scanf("%d",&keepLooping);
  }

  puts("done.");
	return 0;
}

infinite_while_loop_with_break.c


#include <stdio.h>

int loopCount = 0;
int numRepeats = 10;

int main() {
  puts("program start"); 
  while(1){

    loopCount = loopCount + 1;
    printf("loop has run %d times);
    if(loopCount >= 10) {
      break;
    }
  }		
  puts("done.");
  return 0;
}