While and do while in java with example

while loop | do while loop Java Explained [Easy Examples]

Loops in Java are used. when we need to repeatedly execute a block of statements. The two most important types of loops are the while loop and the for loop. while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

In this tutorial, we will learn about while loop java in detail. We will cover different examples and various kinds of while loop java including an empty and infinite while loop. At the same time, we will also discuss the use of break and continue statements in the while loop and their role in control flow. Moreover, we will also the nested while loops and how they actually work by taking different examples.

Читайте также:  Url redirect using html

Towards the end, we will also give a touch to the java do-while loop and will solve examples. All in all, this is going to be a full tutorial about while loop java, and we are sure that by the end of this tutorial you will have a deep understanding of while loop.

Getting started with while loop in Java

while loop in Java may contain a single, compound, or empty statement. The loop repeats while the test expression or condition evaluates to true. When the expression becomes false, the program control passes to the line just after the end of the loop-body code. Here is a simple diagram that explains the while loop java pictorially.

while loop , do while loop Java Explained [Easy Examples]

In the following section, we will learn the basic syntax of while loop java along with some examples.

Syntax of while loop in Java

The syntax of while loop java is very simple. We need to write the condition inside the brackets as shown below:

Now let us take a simple example and print all the numbers from 0 up to 5. See the example below.

number. 0 number. 1 number. 2 number. 3 number. 4

Notice that once the condition inside the while loop becomes false, the program stops executing the while loop.

Syntax and example of empty while loop in Java

An empty while loop java does not contain any statement in its body. It just contains a null statement which is denoted by a semicolon after the while statement: The simple syntax looks like this;

Notice that there is nothing inside the body of the while loop except a semi-colon. Now let us take an example of the empty while loop. See the example below:

Notice that we increment the num inside the condition which is fine. The above empty loop will be executed until the condition becomes false. Because it is an empty while loop java, it will not return anything when we run the code. Such a loop is a time delay loop. The time delay loop is useful for pausing the program for some time. For instance, if an important message flashes on the screen and before we can read it, it goes off. So, In such cases, we can use a time delay loop to get sufficient time to read the message.

Syntax and example of Java infinite loop

A while loop can be an infinite loop if we skip writing the update statement inside its body or the condition is always true. The following is the simple syntax of the java infinite loop;

It is important that to have always a true condition for an infinite loop, otherwise, the loop will stop, once the condition becomes false. Now let us take an example of java infinite while loop. See the example below;

Notice that the above condition is always true as we are not updating or incrementing the number inside the loop. If we run the above code, it will iterate or execute the while loop infinitely time. We can stop an infinite loop by pressing ctrl+ C button on the keyboard.

Iterating an array using while loop in Java

Now we know the basics and important concepts about the while loop. Let us now iterate over an array using while loop java and print out all the elements. See the example below:

// class public class Main < public static void main(String[] args)< // array of int type int arr[]=; //INDEX starts with 0 as array index starts with 0 too int INDEX=0; // while loop java: while(INDEX <5)< // printing the element System.out.println(arr[INDEX]); // updating the index INDEX++; >> >

The break statement in the Java loop

The break keyword is a command that works inside Java while (and for) loops. When the break command is met, the Java Virtual Machine breaks out of the while loop, even if the loop condition is still true. No more iterations of the while loop are executed once a break command is met. This is useful when we want to stop the loop when a certain condition meets. See the example below, which stops the loop even the initial condition is true all the time.

// class public class Main < public static void main(String[] args)< // variable int num = 0; // while loop java: while(true)< // if condition if(num==7)< break; >System.out.println("counting. "+num); num++; > > >
counting. 0 counting. 1 counting. 2 counting. 3 counting. 4 counting. 5 counting. 6

Notice that even the initial condition was true all the time but still we managed to come out of the while loop using a break statement.

While loop in Java with continue statement

Java continue command is also used inside Java while (and for ) loops. The continue command is placed inside the body of the while loop. When the continue command is met, the Java Virtual Machine jumps to the next iteration of the loop without executing more of the while loop body. The next iteration of the while loop body will proceed like any other.

If that iteration also meets the continue command, that iteration too will skip to the next iteration, and so forth. Now let us take an example and say that we want to print the numbers from 0 to 9 without printing the number 5. In such cases, we can use the continue statement. See the example below;

// class public class Main < public static void main(String[] args)< // variable int num = 0; // while loop java: while(num<10)< // if condition if(num==5)< num++; // continue statement continue; >// printing the num System.out.println("counting. "+num); num++; > > >
counting. 0 counting. 1 counting. 2 counting. 3 counting. 4 counting. 6 counting. 7 counting. 8 counting. 9

Notice that we were able to print the numbers without printing number 5. We used the continue statement which skips the number 5 and prints others.

Nested while loop in Java

When a while loop exists inside the body of another while loop, it is known as nested while loop in java. Initially, the outer loop executes once and the afterward inner loop begins to execute. Execution of the inner loop continues until the condition of the inner loop is satisfied(until the test expression is false). In this section, we will have a look at the java nested while loops and will solve examples as well.

Syntax and example of Java nested while loop

As we already discussed nested while loop is when one while loop is inside another while loop. The simple syntax of nested while loop looks like this:

// Outer while loop while(condition1) < // inner while loop while(condition2)< // statements >>

We can put as many while loops inside each other as we wanted. Now, let us take an example of java nested while loop. See the example below:

// class public class Main < public static void main(String[] args)< // variable int num = 1; // while loop in Java: while(num<5)< // printing the table System.out.println("Table of "+num); int num2 = 1; // inner while loop while(num2< 6)< // printing the table System.out.print(num*num2+" "); num2++; >// printing new line System.out.println(""); // updating the num num++; > > >
Table of 1 1 2 3 4 5 Table of 2 2 4 6 8 10 Table of 3 3 6 9 12 15 Table of 4 4 8 12 16 20 

Notice that we were successfully able to print the table of numbers from 1 to 5 using nested while loop. There can be many other cases as well where nested loops help us to solve the problem easily.

do-while loop Java

Unlike the for and while loops, the do-while loop is an exit-controlled loop which means a do-while loop evaluates its test-expression or test-condition at the bottom of the loop after executing the statements in the loop-body. Even if the condition is false, the loop is going to be executed at least once. In this section, we will have a look at the syntax of the java do-while loop and will solve examples using the do-while loop.

Syntax of do-while loop in Java

In the for and while loops, the condition is evaluated before executing the loop-body. The loop body never executes if the test expression evaluates to false for the first time itself. But in some situations, we want the loop-body to execute at least once, no matter what is the initial state of the test expression. In such cases, the do-while loop is the best option which is executed at least once even the condition is always false. The simple syntax looks like this:

First, the statements inside the do will be executed and then the program will check the condition in the while loop. If the condition is false, the loop will not execute for the second time but if the condition is true the do statements will again execute.

Examples of do-while loop in Java

Now we already know the syntax of the Java do-while loop. Let us now take an example and see how it actually works. See the example below:

// class public class Main < public static void main(String[] args)< // do while loop do< System.out.println("Do while loop"); >while(false); > >

Notice that even the condition was false, the do-while loop was executed once. Now let us take another example and print the numbers from 1 to 5 using do-while loop;

// class public class Main < public static void main(String[] args)< // variable int num =0; // do while loop do< num++; System.out.println("counting. "+num); >while(num <5); >>

Источник

Java while and do. while Loop

In computer programming, loops are used to repeat a block of code. For example, if you want to show a message 100 times, then you can use a loop. It’s just a simple example; you can achieve much more with loops.

In the previous tutorial, you learned about Java for loop. Here, you are going to learn about while and do. while loops.

Java while loop

Java while loop is used to run a specific code until a certain condition is met. The syntax of the while loop is:

  1. A while loop evaluates the textExpression inside the parenthesis () .
  2. If the textExpression evaluates to true , the code inside the while loop is executed.
  3. The textExpression is evaluated again.
  4. This process continues until the textExpression is false .
  5. When the textExpression evaluates to false , the loop stops.

To learn more about the conditions, visit Java relational and logical operators.

Flowchart of while loop

Flowchart of while loop in Java

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 > >

Here is how this program works.

Iteration Variable Condition: i Action
1st i = 1
n = 5
true 1 is printed.
i is increased to 2.
2nd i = 2
n = 5
true 2 is printed.
i is increased to 3.
3rd i = 3
n = 5
true 3 is printed.
i is increased to 4.
4th i = 4
n = 5
true 4 is printed.
i is increased to 5.
5th i = 5
n = 5
true 5 is printed.
i is increased to 6.
6th i = 6
n = 5
false The loop is terminated

Example 2: Sum of Positive Numbers Only

// Java program to find the sum of positive numbers import java.util.Scanner; class Main < public static void main(String[] args) < int sum = 0; // create an object of Scanner class Scanner input = new Scanner(System.in); // take integer input from the user System.out.println("Enter a number"); int number = input.nextInt(); // while loop continues // until entered number is positive while (number >= 0) < // add only positive numbers sum += number; System.out.println("Enter a number"); number = input.nextInt(); >System.out.println("Sum /java-programming/scanner" title="Java Scanner">Scanner class to take input from the user. Here, nextInt() takes integer input from the user.

The while loop continues until the user enters a negative number. During each iteration, the number entered by the user is added to the sum variable.

When the user enters a negative number, the loop terminates. Finally, the total sum is displayed.


Java do. while loop

The do. while loop is similar to while loop. However, the body of do. while loop is executed once before the test expression is checked. For example,

do < // body of loop >while(textExpression);
  1. The body of the loop is executed at first. Then the textExpression is evaluated.
  2. If the textExpression evaluates to true , the body of the loop inside the do statement is executed again.
  3. The textExpression is evaluated once again.
  4. If the textExpression evaluates to true , the body of the loop inside the do statement is executed again.
  5. This process continues until the textExpression evaluates to false . Then the loop stops.

Flowchart of do. while loop

Flowchart of do. while loop in Java

Let's see the working of do. while loop.

Example 3: Display Numbers from 1 to 5

// Java Program to display numbers from 1 to 5 import java.util.Scanner; // Program to find the sum of natural numbers from 1 to 100. class Main < public static void main(String[] args) < int i = 1, n = 5; // do. while loop from 1 to 5 do < System.out.println(i); i++; >while(i >

Here is how this program works.

Iteration Variable Condition: i Action
i = 1
n = 5
not checked 1 is printed.
i is increased to 2.
1st i = 2
n = 5
true 2 is printed.
i is increased to 3.
2nd i = 3
n = 5
true 3 is printed.
i is increased to 4.
3rd i = 4
n = 5
true 4 is printed.
i is increased to 5.
4th i = 5
n = 5
true 6 is printed.
i is increased to 6.
5th i = 6
n = 5
false The loop is terminated

Example 4: Sum of Positive Numbers

// Java program to find the sum of positive numbers import java.util.Scanner; class Main < public static void main(String[] args) < int sum = 0; int number = 0; // create an object of Scanner class Scanner input = new Scanner(System.in); // do. while loop continues // until entered number is positive do < // add only positive numbers sum += number; System.out.println("Enter a number"); number = input.nextInt(); >while(number >= 0); System.out.println("Sum infinite-loop">Infinite while loop 

If the condition of a loop is always true, the loop runs for infinite times (until the memory is full). For example,

// infinite while loop while(true)< // body of loop >

Here is an example of an infinite do. while loop.

// infinite do. while loop int count = 1; do < // body of loop >while(count == 1)

In the above programs, the textExpression is always true . Hence, the loop body will run for infinite times.

for and while loops

The for loop is used when the number of iterations is known. For example,

And while and do. while loops are generally used when the number of iterations is unknown. For example,

Table of Contents

Источник

Оцените статью