22
DecUnderstanding While loop in C
While Loop
The while Loop is an entry-controlled loop in C. This loop is used to iterate a part of the code while the given condition remains true. The test takes place before each iteration.
In this C Tutorial, we will explore more about while Loop which will include what is for loop in C, for loop in c programming example, and the syntax of for loop in C. First, we will see What are types of loops in C.
Read More - Top 50 C Interview Questions and Answers
Types of Loop in C
Let’s get into the three types of loops used in C programming.But right now we are going to focus on only While Loop, So let's discuss it.
What is a While Loop?
- While loop is nothing but a a pre-tested loop.
- It allows a part of the code to be executed n number of times depending upon a given boolean condition.
- The while loop is viewed as a repeating if statement.
- It is merely used in the case where the number of iterations is not known in advance.
Flowchart
Syntax
while(test condition){
//code to be executed
}
- The
test condition
is checked, iffalse
the loop will be skipped and the program will continue - If the test condition is
true
, the body of the loop executes - The
update expression
gets updated - Again the
test condition
is evaluated - The process repeats until the
test condition
becomestrue
.
Example: While loop in the CCompiler
// Print numbers from 1 to 10
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 10) {
printf("%d\n", i);
i++;
}
return 0;
}
Explanation:
- In the above code, i is initialized to 1 before the start of the loop.
- The test condition, i<=10 is evaluated. If true, the body of the loop executes.
- If the condition becomes false in the beginning itself, the program control does not even enter the loop once.
- The loop executes until i becomes 10.
Output
1
2
3
4
5
6
7
8
9
10
Infinite while loop:
- In this loop test condition is incorrect.
- And the updation statement is not present.
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Sch1= 1;
int Sch2= 1;
while (Sch1< 10) {
Sch2 = Sch2+ 1;
printf("Welcome to ScholarHat");
}
return 0;
}