Do while java codes

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.
Читайте также:  Php array unsupported operand types

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

Источник

Циклы в Java

Java-университет

Циклы в Java - 1

Программа, написанная на языке Java, состоит из определенного кода. Обычно он выполняется последовательно: строка за строкой, сверху вниз. Но есть и такие конструкции кода, которые меняют линейное выполнение программы. Их называют управляющими конструкциями. Благодаря им, код можно выполнять выборочно. Например, запустить один блок кода вместо другого. Циклы — это разновидность управляющих конструкций для организации многократного выполнения одного и того же участка кода. Код внутри такой управляющей конструкции выполняется циклично. Каждое выполнение кода — это итерация цикла. Количество итераций регулируется условием цикла. Код, который выполняется внутри цикла, называют телом цикла. Известны такие виды циклов:

  1. Циклы с предусловием: условие выполнения определяется перед первой итерацией.
  2. Циклы с постусловием: условие выполнения определяется после первой итерации (поэтому они всегда выполняются минимум один раз). Полезны, когда нужно выполнять некое действие, пока не реализуется некое условие: например, считывать ввод пользователя, пока он не введет слово “stop”.
  3. Циклы со счетчиком: количество итераций определяется смоделированным счетчиком. В условии цикла задается его начальное и конечное значение. Каждую итерацию счетчик наращивается. Мы можем заранее определить количество итераций. Эти циклы бывают полезны, когда нужно перебрать все элементы в какой-то коллекции. Циклы со счетчиком называют “циклами для. ”. “Для каждого элемента некоторой коллекции осуществить следующие действия”. Допустимы случаи, когда выполнение цикла можно прервать до достижения его условия. Например, если у нас есть коллекция из 100 чисел и нам необходимо понять, содержит ли она отрицательные числа. Мы можем начать перебор всех чисел, используя цикл “для”. Но когда мы найдем первое отрицательное число, нам не обязательно перебирать оставшиеся числа. Мы можем прервать выполнение цикла, если его дальнейшее выполнение не имеет смысла. Подобные ситуации называют прерыванием цикла.
  4. Безусловные циклы — циклы, которые выполняются бесконечно. Например: “Пока 1=1, печатать “1=1””. Такая программа будет выполняться, пока ее вручную не прервут. Данные циклы тоже бывают полезны, когда используются вместе с прерыванием цикла “изнутри”. Используйте их осторожно, чтобы не спровоцировать зависание программы. Подробнее с циклами в языке программирования Java можно познакомиться на 4-ом уровне курса JavaRush. В частности, с циклами while и for.

Циклы в Java

  • while — цикл с предусловием;
  • do..while — цикл с постусловием;
  • for — цикл со счетчиком (цикл для);
  • for each.. — цикл “для каждого…” — разновидность for для перебора коллекции элементов.

Цикл while

  • expression — условие цикла, выражение, которое должно возвращать boolean значение.
  • statement(s) — тело цикла (одна или более строк кода).
 public class WhileExample < public static void main(String[] args) < int countDown = 10; while (countDown >= 0) < System.out.println("До старта: " + countDown); countDown --; >System.out.println("Поехали !"); > > 
 До старта: 10 До старта: 9 До старта: 8 До старта: 7 До старта: 6 До старта: 5 До старта: 4 До старта: 3 До старта: 2 До старта: 1 До старта: 0 Поехали ! 
 public class WhileExample < public static void main(String[] args) < int count = 1; while (true) < System.out.println("Строка №" + count); if (count >3) < break; >count++; // Без наращивания цикл будет выполняться вечно > > > 
 Строка №1 Строка №2 Строка №3 Строка №4 

Цикл do..while

  • expression — условие цикла, выражение, которое должно возвращать boolean значение.
  • statement(s) — тело цикла (одна или более строк кода).
 public class DoWhileExample < public static void main(String[] args) < int count = 1; do < System.out.println("count lang-java line-numbers"> for (initialization; termination; increment)
  • initialization — выражение, которое инициализирует выполнение цикла. Исполняется только раз в начале цикла. Чаще всего в данном выражении инициализируют счетчик цикла
  • termination — boolean выражение, которое регулирует окончание выполнения цикла. Если результат выражения будет равен false, цикл for прервется.
  • increment — выражение, которое исполняется после каждой итерации цикла. Чаще всего в данном выражении происходит инкрементирование или декрементирование переменной счетчика.
  • statement(s) — тело цикла.
 Строка №1 Строка №2 Строка №3 Строка №4 Строка №5 

Цикл for each

Этот цикл Java — разновидность цикла for для итерации коллекций и массивов. Структура for each выглядит так:

  • vars — переменная, существующий список или массив
  • Type var — определение новой переменной того же типа ( Type ), что и коллекция vars .
 public class ForExample < public static void main(String[] args) < String[] daysOfWeek = < "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье" >; for (String dayOfWeek : daysOfWeek) < System.out.println(dayOfWeek); >> > 

Циклы в Java - 2

Циклы Java изучаются на курсе JavaRush на четвертом уровне квеста Java Syntax. Попробуйте свои силы в решении задач по этой теме 🙂

Источник

Java While Loop

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

Java While Loop

The while loop loops through a block of code as long as a specified condition is true :

Syntax

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Example

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Example

Do not forget to increase the variable used in the condition, otherwise the loop will never end!

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Java do while loop

Java do while loop

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java do-while loop is used to execute a block of statements continuously until the given condition is true. The do-while loop in Java is similar to while loop except that the condition is checked after the statements are executed, so do while loop guarantees the loop execution at least once.

Java do while loop

The expression for the do-while loop must return a boolean value, otherwise, it will throw compile-time error.

do while java flow diagram

Java Do While Loop

Java do-while loop example

package com.journaldev.javadowhileloop; public class JavaDoWhileLoop < public static void main(String[] args) < int i = 5; do < System.out.println(i); i++; >while (i > 

java do while loop example

do while true java

We can create an infinite loop by passing boolean expression as true in the do while loop. Here is a simple do while java infinite loop example.

package com.journaldev.javadowhileloop; public class DoWhileTrueJava < public static void main(String[] args) throws InterruptedException < do < System.out.println("Start Processing inside do while loop"); // look for a file at specific directory // if found, then process it, such as inserting rows into database System.out.println("End Processing of do while loop"); Thread.sleep(5 * 1000); >while (true); > > 

Note that you will have to manually quit the application to stop it, using Ctrl+C if the program is executed in the terminal. If you execute the program in Eclipse IDE then there is a red color button to terminate the program.

do while vs while loop

The only time you should use a do-while loop is when you want to execute the statements inside the loop at least once, even though condition expression returns false. Otherwise, it’s always better to use a while loop. Java while loop looks cleaner than a do-while loop. That’s all for java do while loop. You should also look into java for loop and java continue statement. Reference: Oracle Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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