Table of Contents
In this lesson, we will be learning about while loop in C with the help of examples.
The while loop provides a programming condition where you want to repeat a thing (statement, function, etc.), while a particular “condition” is true. This is where ‘while loop’ plays its part.
syntax of while loop in C
while(condition) { statement(s); }
while loop FlowChart
Explanation: First, the condition is checked; if the condition is false, then statement y will get executed, which is the end of the loop. If the condition is true, then the statement block will get executed, and the conditional expression gets updated, and the loop continues.
Example of while loop in C
#include <stdio.h> int main() { /* local variable definition */ int var = 15; /*while loop execution */ while (var < 15) { printf(“Value of var: % d\ n”, var); var ++; } return 0; }
In this example, a variable var is initialized by an integer value 10. In the next line, the ‘while loop’ condition is checked. If it is found true, then the body of the while loop gets executed. Otherwise, if found false, then the while loop gets terminated. The command is given to the line immediately to the while loop’s body.
Output
Value of var: 10
Value of var: 11
Value of var: 12
Value of var: 13
Value of var: 14
Use of Logical operators in while loop in C
As like the rational operators (<, >, >=, <=,! =, ==), logical operators can also be used in C. The following cases are valid:
- while( var1<=00 && var2<=100) using AND (&&) operator, this specifies to both the condition being true.
- while(var1<=000 || var2<=100) OR(||) operator, until both the value return false the loop will run indefinitely.
- while(var1!=var2 && var1<=100 ) Use of two logical operators NOT (!) and AND (&&).
Example of Logical operation in while loop in C
#include <stdio.h> int main() { int i=2, j=2; while (i <= 4 || j <= 3) /*checks whether a condition is right or not; if found right the while body will get executed*/ { printf("%d %d\n",i, j); i++; j++; } return 0; }
Output
2 2
3 3
4 4
Summary
- The Syntax of a while loop in C is:
(condition) { statement; }
- The while loop gets executed until the condition inside it is found false by the compiler.
- Never form an indefinite loop, as it may lead to stack overflow exception, i.e., exhaustion of the stack memory, which leads to error.