While loop (while loop in java) in java
Loop is used to execute a set of statements until a particular condition is met. Here is the syntax of while loop in java
syntax (while loop): –
while(condition)
{
statement(s);
}
If-else statements, syntax and examples in java
How while Loop works?
In a while loop, the condition is evaluated first and if the condition is true then the statements inside the while loop are executed. When the condition becomes false, the control exits the loop and goes to the next statement after the loop. The important thing to note when using a while loop is that we need to use increment / decrement inside the loop so that the loop variable changes at each iteration and at one point the shape condition becomes false. Is, thus execution of the while loop occurs.
Simple while loop example
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
}
}
}
Output:
10
9
8
7
6
5
4
3
2
Infinite while loop
class WhileLoopExample2 {
public static void main(String args[]){
int i=10;
while(i>1)
{
System.out.println(i);
i++;
}
}
}
This loop will never end. This is an infinite loop, here the condition is i> 1 which will always be true as the value of variable i is incrementing inside the while loop in this program.
Here is another example of Infinite while loop –
while (true){
statement(s);
}
Iterating an array using while loop using a while loop –
Here we are displaying the elements of the array using a while loop –
class WhileLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
int i=0;
while(i<4){
System.out.println(arr[i]);
i++;
}
}
}
Output:
2
11
45
9
.