What is a While Loop?
*A while loop is a control flow statement in programming that repeatedly executes a block of code as long as a specified condition is true
*while loop statement repeatedly executes a code block as long as a given condition is true.
Syntax of while Loop
The syntax of a while loop is β
while(Boolean_expression) {
// Statements
}
while (condition) {
// code to be repeated
}
Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
**Why Use a While Loop?
Reason Explanation
* To repeat code until a condition becomes false
*when you donβt know how many times the loop should run.
While Loop
The while loop loops through a block of code as long as a specified condition is true:
SyntaxGet your own Java Server
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Reffer::
https://www.w3schools.com
Top comments (0)