While loop
While loop allows a part of the code to be executed multiple times depending upon a given condition. It can be viewed as repeating if statement. The while loop is used in the case where the number of iteration is not known in advance.
Properties:
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.
Syntax:
While(condition)
{
statement;
}
Below are the steps followed by the While loop:
The "While" loop evaluates the "condition" inside the parentheses ().
If the condition is true, the statement or code inside the body of the while loop will execute. Then the condition is evaluated again.
If the Condition is false, the loop terminates (end).
Structure:
Example:
Program to print 1-5 numbers using while loop
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("%d\n", i);
++i;
}
return 0;
}
Output:
Do While Loop
The Do While loop is similar to the While loop. The only difference is that the body of Do While loop is executed at least once. Only then the condition is evaluated. The do-while loop is used in menu-driven programs where the termination condition depends upon the end user.
Syntax:
do
{
//body of the loop
}
while(condition);
Below are the steps followed by the Do While loop
The body of the Do While loop is executed once. Only then the condition is evaluated.
If the condition is true, the body of the loop is executed again and the condition is evaluated once more.
If the Condition is false, the loop will terminate.
Example:
Program to add numbers until the user enter 0.
#include <stdio.h>int main() {
double number, sum = 0;
// the body of the loop is executed at least oncedo {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
Output:
Difference Between While and Do-While Loop
While Do-While
Condition is Checked first then Statement is Statement is executed at least once,
Executed thereafter condition is checked
It might occur statement is executed zero At Least once the statement is executed
times if the condition is false
If there is single statement brackets are not Brackets are always required
required
Variable in condition is initialized before the Variable may be initialized before or
execution of loop within the loop
While loop is entry controlled loop Do-while loop is exit controlled loop
No semicolon at the end of the while loop Semicolon at the end of the while
While(condition) while(condition);
The Tech Platform
Comments