while task.1
A while loop in Java executes a block of code repeatedly as long as the given condition remains true.
package Mistak;
public class Ifcount {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=1;
while(count<=5) {
System.out.println(1);
count=count+1;
}
}
//ANS = 1 1 1 1 1
}
TASK 2
package Mistak;
public class Countwhile {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=5;
while(count>=1) {
System.out.println(count);
count=count-1;
}
// ANS = 5 4 3 2 1
}
}
TASK 3.
package Mistak;
public class While {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=1;
while(count<=10) {
System.out.println(count);
count=count+2;
}
} //ANS = 1 3 5 7 9
}
TASK 4.
package Mistak;
public class Countwhile {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=5;
while(count>=1) {
System.out.println(count);
count=count-1;
}
// ANS = 5 4 3 2 1
}
}
Key Points:
The loop executes as long as the condition is true.
If the condition is false at the start, the loop won't execute even once.
Ensure the loop condition eventually becomes false to avoid an infinite loop.
Here are some key points about the while loop in Java:
Entry-Controlled Loop: The condition is checked before executing the loop body.
Executes 0 or More Times: If the condition is false initially, the loop won't run at all.
Condition Must Change: Ensure the condition eventually becomes false to avoid an infinite loop.
Used for Indeterminate Iterations: Best suited when the number of iterations is unknown beforehand.
Can be Interrupted: Use break to exit the loop prematurely and continue to skip an iteration.
May Cause Infinite Loops: If the condition never turns false, the loop will run forever.
Better for Waiting Scenarios: Often used when waiting for a condition to become true dynamically.
Top comments (0)