The while loop

In this section, we will learn the while loop in detail. First, create a new class. Now let us see how we can utilize this while loop when programming our code. Let's say we want to print the numbers from 1 to 10, sequentially. How do we print this using the while loop? The basic syntax of the while loop is:

// While loop

while(boolean)
{

}

And here, if the Boolean expression returns true, only then will the control go inside this loop, whereas if the expression returns false, then the control will not go inside the loop. That's the basic simple concept you have with the while loop. Now let's say we want to bring in the numbers from 1 to 10. For this, we will write the following code: 

//While loop 

//1 to 10

int i=0;
while(i<10)
{
System.out.println(i);
}

As you can see, in the preceding code example, we can see that that the given condition is true. So, it goes inside the loop and prints the value of i. This loop keeps on executing until the expression evaluates to false. As per our example, the condition will always be true; thus, it will go to the infinite loop and print zero.

This is how the while loop works. Unless the condition becomes false in this argument, this loop will never stop executing. Now, what if we increment after printing the variable? Let's see what happens when we do that:

//While loop 

//1 to 10

int i=0;
while(i<10)
{
System.out.println(i);
i++;
}

The output will be as that shown in the following screenshot:

Output of the while condition as per the code

If we use the following condition:

while(i<=10)

The new output will be:

Output of the while condition after modifying the code

Similarly, you you can reverse the condition, as follows:

//While loop 

//1 to 10

int i=10;
while(i>0)
{
System.out.println(i);
i++;//i=2
}

The output will go to infinite, since the numbers keep on increasing because 10 is greater than 0.

If we use the decrement condition, it will keep on decreasing until the condition becomes false. After that, it will exit the loop, as shown in the following code example:

//While loop 

//1 to 10

int i=10;
while(i>0)
{
System.out.println(i);
i--;//i=2
}

The output for the preceding code example will be:

5
4
3
2
1

So, this is how we can use the while loop syntax in our Java program. In the next section, we will see how to work on the do...while loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.76.0