While Loop in C
Advertisements
While Loop in C
In while loop First check the condition if condition is true then control goes inside the loop body other wise goes outside the body. while loop will be repeats in clock wise direction.
Execution Flow of While Loop
Syntax While Loop
Assignment; while(condition) { statements; ............ Increment or Decrements (++ or --); }
Note: If while loop condition never false then loop become infinite loop.
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop.
When while loop is use ?
When we do not know about how many times loops are perform or iteration of loop is unknown.
Flow Diagram
Example of while Loop
#include<stdio.h> #include<conio.h> void main() { int i; clrscr(); i=1; while(i<5) { printf("\n%d",i); i++; } getch(); }
Output
Output: 1 2 3 4
Execution process of while loop is slower than for loop.
Infinite While Loop
Example of Infinite while Loop
#include<stdio.h> #include<conio.h> void main() { int var = 6; while (var >=5) { printf("%d", var); var++; } getch(); }
Output
var will always have value >=5 so the loop would never end.
Properties of While Loop
- In while loop onditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.
- The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.
- In while loop, the condition expression is compulsory.
- Running a while loop without a body is possible.
- We can have more than one conditional expression in while loop.
- If the loop body contains only one statement, then the braces are optional.
While Loop Can't be Empty
Example of Empty while Loop
#include<stdio.h> #include<conio.h> void main() { while() { printf("Hello World!"); } getch(); }
Output
compile time error: while loop can't be empty
Google Advertisment