WHILE Loop
Definition:
- WHILE Loop is a decision-making control
flow statement that execute body of statements based on given Boolean
condition.
- WHILE Loop belongs from Unbounded Loop
category which means it will execute indefinite number of times.
- WHILE Loop is known as Pre-Test Loop
because condition is tested at first then executes the body of statements.
- WHILE Loop is mostly used for the repetition
of block of code as long as the condition is true.
- WHILE Loop is also known as Entry-Controlled loop where condition is checked at the beginning itself.
Syntax:
The basic syntax of the WHILE Loop in C-Language
while(condition)
{
//
Body of statement(s)
//
Increment or Decrement Operation
}
How WHILE Loop Works:
- The
WHILE Loop check the condition inside the parenthesis ().
- If
the condition is true then body of WHILE Loop execute and again check the
condition.
- This
process will continue until the condition become false.
- If
the condition is false then the WHILE Loop gets terminated.
Illustration of WHILE Loop
Program: Write a C program to print numbers from 1 to
5.
#include<stdio.h>
int main()
{
int counter=1
while(counter<=5)
{
printf(“Value
of counter: %d\n”, counter);
counter++;
}
return 0;
}
Output:
Value of counter: 1
Value of counter: 2
Value of counter: 3
Value of counter: 4
Value of counter: 5
Explanation:
The initial
value of counter=1
- When
counter is 1 then WHILE Loop condition is true (counter<=5). Hence the body
of WHILE Loop is executed and value of counter is increased to 2.
- Now
counter is 2, WHILE Loop condition is true (counter<=5). Hence, again the
body of WHILE Loop is executed and value of counter is increased to 3.
- This
process will repeat until the WHILE Loop condition become false. (If counter is
6 then WHILE Loop condition counter<=5 become false)
- Once the WHILE Loop condition become false then loop gets terminated.
Application:
The concept of WHILE Loop is mostly used in such case
where the number of iterations is not known in beginning or advance.
WHILE Loop is used in such situation where you want to
print block of code repeatedly until the condition become false.
0 Comments
Welcome Dear Reader, I am very glad to help you | keep visiting my blog... Thanks !