So, here's a very simple example of "while" loop. Programming is more on logic, so just try to analyze the logic of this following programs.
import java.util.*;
public class while1{
public static void main(String[]args){
public class while1{
public static void main(String[]args){
int x = 1;
while (x <= 5)
{
System.out.println(x);
x++;
}
}}
while (x <= 5)
{
System.out.println(x);
x++;
}
}}
output:
1
2
3
4
5
import java.util.*;
public class while2{
public static void main(String[]args){
int x = 0;
while (x <= 4)
{
x++;
System.out.println(x);
}
}}
output:
1
2
3
4
5
The first and second program has the same output, but their source code are not the same. The value of x on the first program starts at one then ends at five and it has 1,2,3,4,5 output. The value of x on the second program starts at zero then ends at four and then it also has 1,2,3,4,5 output. The difference in these two programs is, in the first one it displays first the value of x before it increments (x++). But on the second program, the increment (x++) was added before it displayed the value of x.
import java.util.*;
public class while3{
public static void main(String[]args){
int x = 5;
while (x > 0)
{
System.out.println(x);
x--;
}
}}
output:
5
4
3
2
1
These last program, the output is opposite from the first and second program. It starts at five and ends at one. Its all because of the decrement (x--), unlike the first two programs we increment (x++) its value.