Friday, July 29, 2016

C Basics - The while Loop in C

A while loop in C programming repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop is,

while(condition) {
   statement(s);
}

The general form of while is as shown below:

initialise loop counter ; 
while ( test loop counter using a condition )
{ 
do this ; 
and this ;
increment loop counter ; 
} 

The statements within the while loop would keep on getting executed till the condition being tested remain true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop.

In place of the condition there can be any other valid expression. So long as the expression evaluates to a non-zero value the statements within the loop would get executed.

#include <stdio.h>
 
int main () {

   int i = 1;

   while( i < 5 ) {
      printf("value of i is: %d\n", i);
      i++;
   }
 
   return 0;
}
Output of above program,

value of i is: 1
value of i is: 2
value of i is: 3
value of i is: 4



Related topics:
Loops in C   |   The for Loop in C   |   The do-while Loop in C   |   Nested Loop in C   |   Infinite Loop in C   |   Loop Control Statements in C   |   The break Statement in C   |   The continue Statement in C   |   The goto Statement in C   |   The return Statement in C

List of topics: C Programming

No comments:

Post a Comment