Computer Science

Java Do While Loop

The Java do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block as long as a specified condition is true. It is similar to the while loop, but the condition is checked after the block of code is executed, ensuring that the block is executed at least once.

Written by Perlego with AI-assistance

10 Key excerpts on "Java Do While Loop"

  • Book cover image for: Java Programming
    eBook - PDF
    C H A P T E R 6 Looping Upon completion of this chapter, you will be able to: Describe the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops Nest loops Improve loop performance Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 284 Looping C H A P T E R 6 Learning About the Loop Structure If making decisions is what makes programs seem smart, looping is what makes programs seem powerful. A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements called the loop body executes and the Boolean expression is evaluated again. The loop body can be a single statement, or a block of statements between curly braces. As long as the loop-controlling, Boolean expression is true, the statements in the loop body continue to execute. When the Boolean evaluation is false, the loop ends. One execution of any loop is called an iteration. Figure 6-1 shows a diagram of the logic of a loop. In Java, you can use several mechanisms to create loops. In this chapter, you learn to use three types of loops: • A while loop, in which the loop-controlling Boolean expression is the first statement in the loop, evaluated before the loop body ever executes • A for loop, which is usually used as a concise format in which to execute loops • A do…while loop, in which the loop- controlling Boolean expression is the last statement in the loop, evaluated after the loop body executes one time.
  • Book cover image for: Processing
    eBook - ePub

    Processing

    An Introduction to Programming

    5
    Repetition with a Loop: The  while    Statement    
    We have seen in the programs we have written that the order in which the statements are written makes a difference. This illustrates a key principle of computing known as sequence  .
    In Chapter  4, we saw that statements placed inside an if  or switch  statement are only performed if a certain condition is true. Such conditional programming illustrates a second key principle of computing known as selection  .
    In this chapter and the next, we will see that, sometimes, one or more statements need to be performed repeatedly   in a computer program. This will illustrate a third key principle in computing: repetition  .
    Human beings often find repetitive tasks to be tedious. In contrast, computers can provide an ideal way to perform repetitive tasks.  Repetition as Long as a Certain Condition Is True
    Like the if  statement, each repetition structure in this chapter will make use of a condition  . This condition will determine whether the repetition should continue  .
    Once again, let’ s consider a cooking recipe as an analogy to a computer program. Suppose a certain dough recipe says that you are to mix the ingredients and then repeatedly   add ½  cup of flour as long as   you can still stir the mixture with a spoon. A flowchart of this recipe might look like the following:
    Similarly, in computer programming, there are sometimes sets of statements that we would like to perform repeatedly  , but only as long as   a certain condition is true.
    Repetition with the while   Statement
    Processing provides several programming structures that can be used for creating repetition. One of the more versatile of these repetition structures is the while   statement. The basic form of the while
  • Book cover image for: Java Concepts
    eBook - PDF

    Java Concepts

    Late Objects

    • Cay S. Horstmann(Author)
    • 2016(Publication Date)
    • Wiley
      (Publisher)
    4 C H A P T E R 141 LOOPS To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To implement programs that read and process data sets To use a computer for simulations CHAPTER GOALS CHAPTER CONTENTS 4.1 THE WHILE LOOP 142 SYN while Statement 143 CE 1 Don’t Think “Are We There Yet?” 146 CE 2 Infinite Loops 147 CE 3 Off-by-One Errors 147 C&S The First Bug 148 4.2 PROBLEM SOLVING: HAND-TRACING 149 4.3 THE FOR LOOP 152 SYN for Statement 154 PT 1 Use for Loops for Their Intended Purpose Only 157 PT 2 Choose Loop Bounds That Match Your Task 157 PT 3 Count Iterations 158 4.4 THE DO LOOP 158 PT 4 Flowcharts for Loops 159 4.5 APPLICATION: PROCESSING SENTINEL VALUES 160 ST 1 The Loop-and-a-Half Problem and the break Statement 162 ST 2 Redirection of Input and Output 163 VE 1 Evaluating a Cell Phone Plan 4.6 PROBLEM SOLVING: STORYBOARDS 164 4.7 COMMON LOOP ALGORITHMS 167 HT 1 Writing a Loop 171 WE 1 Credit Card Processing 4.8 NESTED LOOPS 174 WE 2 Manipulating the Pixels in an Image 4.9 PROBLEM SOLVING: SOLVE A SIMPLER PROBLEM FIRST 178 4.10 APPLICATION: RANDOM NUMBERS AND SIMULATIONS 182 ST 3 Drawing Graphical Shapes 186 VE 2 Drawing a Spiral C&S Digital Piracy 188 © photo75/iStockphoto. 142 In a loop, a part of a program is repeated over and over, until a specific goal is reached. Loops are important for calculations that require repeated steps and for processing input consisting of many data items. In this chapter, you will learn about loop statements in Java, as well as techniques for writing programs that process input and simulate activities in the real world. 4.1 The while Loop In this section, you will learn about loop statements that repeatedly execute instructions until a goal has been reached. Recall the investment problem from Chapter 1. You put $10,000 into a bank account that earns 5 percent inter- est per year.
  • Book cover image for: Brief Java
    eBook - PDF

    Brief Java

    Early Objects

    • Cay S. Horstmann(Author)
    • 2019(Publication Date)
    • Wiley
      (Publisher)
    171 C H A P T E R 6 LOOPS C H A P T E R G O A L S To implement while, for, and do loops To hand-trace the execution of a program To learn to use common loop algorithms To understand nested loops To implement programs that read and process data sets To use a computer for simulations To learn about the debugger C H A P T E R C O N T E N T S © photo75/iStockphoto. 6.1 THE WHILE LOOP 172 SYN while Statement 173 CE 1 Don’t Think “Are We There Yet?” 177 CE 2 Infinite Loops 177 CE 3 Off-by-One Errors 178 6.2 PROBLEM SOLVING: HAND-TRACING 179 C&S Digital Piracy 182 6.3 THE FOR LOOP 183 SYN for Statement 183 PT 1 Use for Loops for Their Intended Purpose Only 188 PT 2 Choose Loop Bounds That Match Your Task 188 PT 3 Count Iterations 189 ST 1 Variables Declared in a for Loop Header 189 6.4 THE DO LOOP 190 PT 4 Flowcharts for Loops 191 6.5 APPLICATION: PROCESSING SENTINEL VALUES 192 ST 2 Redirection of Input and Output 194 ST 3 The “Loop and a Half” Problem 194 ST 4 The break and continue Statements 195 6.6 PROBLEM SOLVING: STORYBOARDS 197 6.7 COMMON LOOP ALGORITHMS 199 HT 1 Writing a Loop 203 WE1 Credit Card Processing 206 6.8 NESTED LOOPS 206 WE2 Manipulating the Pixels in an Image 209 6.9 APPLICATION: RANDOM NUMBERS AND SIMULATIONS 209 6.10 USING A DEBUGGER 213 HT 2 Debugging 215 WE3 A Sample Debugging Session 217 C&S The First Bug 217 172 In a loop, a part of a program is repeated over and over, until a specific goal is reached. Loops are important for calculations that require repeated steps and for processing input consisting of many data items. In this chapter, you will learn about loop statements in Java, as well as techniques for writing programs that process input and simulate activities in the real world. 6.1 The while Loop In this section, you will learn about loop statements that repeatedly execute instructions until a goal has been reached. Recall the investment problem from Chapter 1. You put $10,000 into a bank account that earns 5 percent interest per year.
  • Book cover image for: Microsoft® Visual C# 2015
    eBook - PDF

    Microsoft® Visual C# 2015

    An Introduction to Object-Oriented Programming

    If so, you can write a loop that checks at the “bottom” of the loop after the first iteration. The do loop (also called a do...while loop ) checks the loop-controlling Boolean expression after one iteration. Figure 5-12 shows a diagram of the structure of a do loop. Figure 5-12 Flowchart of a do loop Loop body Test of loop control variable true false Figure 5-13 shows the logic and the C# code for a do loop in a bank balance program. The loop starts with the keyword do . The body of the loop follows and is contained within curly Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 203 Creating Loops with the do Statement braces. Within the loop, the next balance is calculated, and the user is prompted for a response. The Boolean expression that controls loop execution is written using a while statement, placed after the loop body. The bankBal variable is output the first time before the user has any option of responding. At the end of the loop, the user is prompted, Do you want to see next year’s balance? Y or N… . Now the user has the option of seeing more balances, but the first view of the balance was unavoidable.
  • Book cover image for: Java Concepts
    eBook - PDF
    • Cay S. Horstmann(Author)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    . . } However, many people find it confusing if a for loop controls more than one variable. I rec- ommend that you not use this form of the for statement (see Programming Tip 5.2 on page 236). Instead, make the for loop control a single counter, and update the other variable explicitly: int j = 10; for (int i = 0; i <= 10; i++) { . . . j––; } Special Topic 5.1 238 Chapter 5 Loops 5.4 The do Loop Sometimes you want to execute the body of a loop at least once and perform the loop test after the body is executed. The do loop serves that purpose: do { statements } while (condition); The body of the do loop is executed first, then the condition is tested. Some people call such a loop a post-test loop because the condition is tested after completing the loop body. In contrast, while and for loops are pre-test loops. In those loop types, the condition is tested before enter- ing the loop body. A typical example for a do loop is input validation. Suppose you ask a user to enter a value < 100. If the user doesn’t pay attention and enters a larger value, you ask again, until the value is correct. Of course, you cannot test the value until the user has entered it. This is a perfect fit for the do loop (see Figure 5): int value; do { System.out.print("Enter an integer < 100: "); value = in.nextInt(); } while (value >= 100); Figure 5 Flowchart of a do Loop 16. Suppose that we want to check for inputs that are at least 0 and at most 100. Modify the do loop for this check. 17. Rewrite the input check do loop using a while loop. What is the disadvantage of your solution? 18. Suppose Java didn’t have a do loop. Could you rewrite any do loop as a while loop? 19. Write a do loop that reads integers and computes their sum. Stop when reading the value 0. 20. Write a do loop that reads integers and computes their sum. Stop when reading a zero or the same value twice in a row. For example, if the input is 1 2 3 4 4, then the sum is 14 and the loop stops.
  • Book cover image for: Microsoft Visual C#: An Introduction to Object-Oriented Programming
    bankBal = bankBal + bankBal * INT_RATE Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 200 C H A P T E R 5 Looping You never are required to use a do loop. Within the bank balance example, you could achieve the same results by unconditionally displaying the bank balance once, prompting the user, and then starting a while loop that might not be entered. However, when a task must be performed at least one time, the do loop is convenient. TWO TRUTHS & A LIE Creating Loops with the do Statement 1. The do loop checks the bottom of the loop after one iteration has occurred. 2. The Boolean expression that controls do loop execution is written using a do statement, placed after the loop body. 3. You never are required to use a do loop; you can always substitute one execution of the body statements followed by a while loop. The false statement is #2. The Boolean expression that controls do loop execution is written using a while statement, placed after the loop body. In a do loop, as a matter of style, many programmers prefer to align the while expression with the do keyword that starts the loop. Others feel that placing the while expression on its own line increases the chances that readers might misinterpret the line as the start of its own while statement instead of marking the end of a do statement. The while loop and for loop are pretest loops —ones in which the loop control variable is tested before the loop body executes. The do loop is a posttest loop —one in which the loop control variable is tested after the loop body executes.
  • Book cover image for: C# Programming
    eBook - PDF

    C# Programming

    From Problem Analysis to Program Design

    Conversely, if you know your loop will always be executed at least once, the do . . . while is a good option. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 6 Programming Example: LoanApplication | 371 If a numeric variable is being changed by a consistent amount with each iteration through the loop, the compactness of the for statement might work best. The ini-tialization, conditional expression, and update can all be located on the same line. Although the format allows for multiple entries for all three of these entries, a good rule of thumb is that the for statement initialization, condition, and update should be able to be placed on one line. Remember, readability is always an important consideration. The while statement can be used to write any type of loop. It can implement counter-controlled loops just as the for statement can. The while statement is also useful for applications requiring state- and sentinel-controlled loops. So it is always a good option. It offers the advantage of being a pretest type. With all of the loops, you want to ensure that you understand and design the condition that is used to end the loop as well as how the condition is updated or changed. This example demonstrates the use of loops in the analysis, design, and implementa-tion of a program. Both pretest and posttest forms of loops are included in the exam-ple. The pretest form is used to calculate individual loan details. It is nested inside the posttest through method calls. Static and instance methods, properties, and selection statements are included.
  • Book cover image for: Introduction to Programming and Problem-Solving Using Scala
    Loops 223 • The do-while loop is a post-test conditional loop and is just like the while loop except that the condition is checked after each execution of the body. This means that the body of a do-while loop will always execute at least once. • The most commonly used loop is the for loop. Scala’s for loop is a for-each loop that iterates through each member of a collection. It has many options that give it a lot of flexibility and power. – A generator in a for loop has a pattern followed by a <-followed by a collection that is iterated through. The <-symbol should be read as “in”. – To make counting easy, there is a Range type that can specify ranges of numeric values. The methods to and until can produce Range s on numeric types. The method by can adjust stepping. Floating point Range s require a stepping. – The yield keyword can be put before the body of a for loop to cause it to produce a value so that it is an expression. When you have a for loop yield a value, it produces a collection similar to the one the generator is iterating over with the values that are produced by the expression in the body of the loop. – The left side of a generator in a for loop is a pattern. This can allow you to pull values out of the elements of the collection, such as parts of a tuple. In addition, any elements of the collection that do not match the pattern is skipped over. – if guards can be placed in for loops. This is particularly helpful when using yield , and the values that fail the conditional check will not produce an output in the result. – You can also place value declarations in the specification of a for loop. This can help make the code shorter, easier to read, and faster. • Testing is an essential part of software development. This is where you run the program using various inputs to make certain that it does not fail or produce incorrect output. Proper testing should exercise all parts of the code.
  • Book cover image for: Learn C Programming
    Very often, we need to perform a series of statements repeatedly. We might want to perform a calculation on each member of a set of values, or we might want to perform a calculation using all of the members in a set of values. Given a collection of values, we also might want to iterate over the whole collection to find the desired value, to count all the values, to perform some kind of calculation on them, or to manipulate the set in some way – say, to sort it.
    There are a number of ways to do this. The simplest, yet most restrictive way is the brute-force method . This can be done regardless of the language being used. A more dynamic and flexible method is to iterate or repeatedly loop. C provides three interrelated looping statements – while()… , for()… , and do … while() . Each of them has a control or continuation expression, and a loop body. The most general form of these is the while()… loop. Lastly, there is the archaic goto label method of looping. Unlike other languages, there is no repeat … until() statement; such a statement can easily be constructed from any of the others.
    Each looping statement consists of the following two basic parts:
    • The loop continuation expression
    • The body of the loop
    When the loop continuation expression evaluates to true , the body of the loop is executed. The execution then returns to the continuation expression, evaluates it, and, if true , the body of the loop is again executed. This cycle repeats until the continuation expression evaluates to false ; the loop ends, and the execution commences after the end of the loop body.
    There are two general types of continuation expressions used for looping statements, as follows:
    • Counter-controlled looping , where the number of iterations is dependent upon a count of some kind. The desired number of iterations is known beforehand. The counter may be increasing or decreasing.
    • Condition- or sentinel-controlled looping
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.