C - Structuring a while loop

Introduction

Basically, a while loop goes like this:

while(condition) 
{ 
      statement(s); 
} 

The condition is a true/false comparison.

The condition is checked every time the loop repeats. As long as it's true, the loop continues and the statement (statements) between the curly brackets continues to execute.

Because the evaluation happens at the start of the loop, the loop must be initialized before the while statement.

After the while loop is done, program execution continues with the next statement after the final curly bracket.

A while loop can omit the curly brackets when it has only one statement:

while(condition) 
     statement; 

Demo

#include <stdio.h> 

int main() /*from w w w .j  a  v  a  2 s.co  m*/
{ 
     int x; 

     x=0; 
     while(x<10) 
     { 
         puts("Sore shoulder surgery"); 
         x=x+1; 
     } 
     return(0); 
}

Result

The while loop above has three parts:

  • The initialization takes place where variable x is set equal to 0.
  • The loop's exit condition is contained within the while statement's parentheses.
  • The loop body is where variable x is increased in value.

Related Topic