While loop:
Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed.
Syntax of while loop in Java:
while (test_expression) {
// statements
update_expression;
}
condition is evaluated before each iteration of the loop
If condition is true, the code block inside the while loop will execute
The process repeats until condition is false
Enter fullscreen mode Exit fullscreen mode
Execution of While Loop in Java:
- Control enters the while loop.
- The condition is tested.
- If true, execute the body of the loop.
- If false, exit the loop.
- After executing the body, update the loop variable.
- Repeat from step-2 until the condition is false.
Example 1: Display Numbers from 1 to 5
// Program to display numbers from 1 to 5
class Main {
public static void main(String[] args) {
// declare variables
int i = 1, n = 5;
// while loop from 1 to 5
while(i <= n) {
System.out.println(i);
i++;
}
}
}
output:
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode
Task1:
Program:
public class Count {
public static void main(String[] args) {
int count=1;
while (count<=5){
count=count+1;
System.out.println("count: "+count);
}
}
}
output:
count: 2
count: 3
count: 4
count: 5
count: 6
Enter fullscreen mode Exit fullscreen mode
Task2:
Program:
public class Count1 {
public static void main(String[] args) {
int count=5;
while (count>=1) {
count=count-1;
{
System.out.println("count:" +count);
}
}
}
}
output:
count:4
count:3
count:2
count:1
count:0
Enter fullscreen mode Exit fullscreen mode
Task3:
Program:
public class Count2 {
public static void main (String args[])
{
int count=0;
while(count<10) {
count=count+2;
{
System.out.println("count:" +count);
}
}
}
}
output:
count:2
count:4
count:6
count:8
count:10
Enter fullscreen mode Exit fullscreen mode
Task4:
program:
public class Count3 {
public static void main (String args[])
{
int count=1;
while(count<=10) {
count=count+2;
{
System.out.println("count:" +count);
}
}
}
}
output:
count:3
count:5
count:7
count:9
count:11
Enter fullscreen mode Exit fullscreen mode
References:
https://www.geeksforgeeks.org/java-while-loop-with-examples/
https://www.programiz.com/java-programming/do-while-loop
原文链接:While loop:
暂无评论内容