Computer Science

Java While Loop

A Java while loop is a control flow statement that allows a block of code to be executed repeatedly based on a given boolean condition. The loop continues to execute as long as the condition remains true. It is a fundamental construct in programming for creating iterative processes and is commonly used for tasks such as iterating through arrays or performing calculations until a certain condition is met.

Written by Perlego with AI-assistance

11 Key excerpts on "Java 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: Microsoft® Visual C# 2015
    eBook - PDF

    Microsoft® Visual C# 2015

    An Introduction to Object-Oriented Programming

    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. As long as the expression is true , the statements in the loop body continue to execute and the loop-controlling Boolean expression continues to be reevaluated. When the Boolean evaluation is false , the loop ends. Figure 5-1 shows a diagram of the logic of a loop. One execution of any loop is called an iteration . %RROHDQ H[SUHVVLRQ WUXH IDOVH /RRS ERG Figure 5-1 Flowchart of a loop structure You can use a while loop to execute a body of statements continuously as long as the loop’s test condition continues to be true . A while loop consists of the following: • the keyword while • a Boolean expression within parentheses • the loop body The evaluated Boolean expression in a while statement can be either a single Boolean expression or a compound expression that uses ANDs and ORs. The body can be a single statement or any number of statements surrounded by curly braces. 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. 191 Creating Loops with the while Statement For example, the following code shows an integer declaration followed by a loop that causes the message Hello to display (theoretically) forever because there is no code to end the loop. A loop that never ends is called an infinite loop . An infinite loop might not actually execute infinitely.
  • Book cover image for: Microsoft Visual C#: An Introduction to Object-Oriented Programming
    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. As long as the expression is true , the statements in the loop body continue to execute and the loop-controlling Boolean expression continues to be reevaluated. When the Boolean evaluation is false , the loop ends. Figure 5-1 shows a diagram of the logic of a loop. One execution of any loop is called an iteration . Figure 5-1 Flowchart of a loop structure Boolean expression true false Loop body You can use a while loop to execute a body of statements continuously as long as the loop’s test condition continues to be true . A while loop consists of the following: • the keyword while • a Boolean expression within parentheses • the loop body The evaluated Boolean expression in a while statement can be either a single Boolean expression or a compound expression that uses ANDs and ORs. The body can be a single statement or any number of statements surrounded by curly braces. 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. 187 Creating Loops with the while Statement For example, the following code shows an integer declaration followed by a loop that causes the message Hello to display (theoretically) forever because there is no code to end the loop: int number = 1; while(number > 0) WriteLine(Hello); A loop that never ends is called an infinite loop . An infinite loop might not actually execute infinitely.
  • Book cover image for: Big Java
    eBook - PDF

    Big 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: Programming Logic and Design, Introductory
    It is easy for others to read, and because the loop control variable’s initialization, testing, and alteration are all performed in one location, you are less likely to leave out one of these crucial elements. Although for loops are commonly used to control execution of a block of statements a fixed number of times, the programmer doesn’t need to know the starting, final, or step value for the loop control variable when the program is written. For example, any of the values might be entered by the user, or might be the result of a calculation. Figure 5-15 Comparable while and for statements that each output Hello four times count = 0 while count <= 3 output "Hello" count = count + 1 endwhile for count = 0 to 3 step 1 output "Hello" endfor The for loop is particularly useful when processing arrays. You will learn about arrays in Chapter 6. In Java, C11, and C#, a for loop that displays 21 values (0 through 20) might look similar to the following: for(count 5 0; count <= 20; count11) { output count; } The three actions (initializing, evaluating, and altering the loop control variable) are separated by semi- colons within a set of parentheses that follow the keyword for. The expression count11 increases count by 1. In each of the three languages, the block of statements that depends on the loop sits between a pair of curly braces, so the endfor keyword is not used. None of the three languages uses the keyword output, but all of them end output statements with a semicolon. 200 C H A P T E R 5 Looping Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Both the while loop and the for loop are examples of pretest loops. In a pretest loop, the loop control variable is tested before each iteration. That means the loop body might never execute because the evaluation controlling the loop might be false the first time it is made.
  • Book cover image for: Programming Logic & Design, Comprehensive
    C H A P T E R 5 Looping Upon completion of this chapter, you will be able to: Appreciate the advantages of looping Use a loop control variable Create nested loops Avoid common loop mistakes Use a for loop Use a posttest loop Recognize the characteristics shared by all structured loops Describe common loop applications Appreciate the similarities and differences between selections and loops Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 Appreciating the Advantages of Looping Although making decisions is what makes computers seem intelligent, looping makes computer programming both efficient and worthwhile. When you use a loop, one set of instructions can operate on multiple, separate sets of data. Using fewer instructions results in less time required for design and coding, fewer errors, and shorter compile time. Recall the loop structure that you learned about in Chapter 3; it looks like Figure 5-1. As long as a Boolean expression remains true, the body of a while loop executes. Quick Reference 5-1 shows the pseudocode standards this book uses for the while statement. Figure 5-1 The loop structure No Yes QUICK REFERENCE 5-1 while Statement Pseudocode Standards while condition statements that execute when condition is true endwhile The while keyword starts the statement and precedes any statements that execute when the tested condition is true. The tested condition is a Boolean expression. It might be a comparison such as x > y , it might be a Boolean variable if the language supports that type, or it might be a call to a method that returns a Boolean value. (Chapter 9 in the comprehensive version of this book describes methods that return values.) The endwhile keyword ends the structure. After endwhile , the condition is tested again. Although many modern languages do not require indentation, the bodies of while loops in this book are indented.
  • Book cover image for: Python for Beginners
    • Kuldeep Singh Kaswan, Jagjit Singh Dhatterwal, B Balamurugan(Authors)
    • 2023(Publication Date)
    5 Iterative Control Structure
    DOI: 10.1201/9781003202035-5
    Looping is a program or script procedure that performs repetitive (or iterative) tasks. The loop is a sequence of instructions (a block) that is executed repeatedly while or until some condition is met or satisfied. Each repetition is called an iteration. All programming and scripting languages provide loop structures, and, like other languages, Python has several looping constructs [28 ].
    Algorithm design is frequently based on iteration and conditional execution.

    5.1 The While Loop

    The output of Program 5.1 (counting.py) counts up to five.
    print (5) print (4) print (3) print (2) print (1)
    Output 5 4 3 2 1
    How would you write the code to count to 10,000? Would you copy, paste, and modify 10,000 printing statements? You could, but that would be impractical! Counting is such a common activity, and computers routinely count up to very large values, that there must be a better way. What we would really like to do is print the value of a variable (call it count), then increment the variable (count += 1), repeating this process until the variable is large enough (count == 5 or maybe count == 10000). Python has two different keywords, while and for , that enable iteration [29 ].
    Program 5.2 (loopcounting.py) uses the keyword while to count up to five:
    count = 1 while count <= 5: print (count) count += 1
    Output 1 2 3 4 5
    The while keyword in Program 5.2 (loopcounting.py) causes the variable ‘count’ to be repeatedly printed then incremented until its value reaches five. The block of statements
    print(count) count += 1
    is executed five times. After each print of the variable count
  • Book cover image for: Python for Everyone
    • Cay S. Horstmann, Rance D. Necaise(Authors)
    • 2020(Publication Date)
    • Wiley
      (Publisher)
    125 C H A P T E R 4 LOOPS C H A P T E R G O A L S To implement while and for loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To process strings To use a computer for simulations C H A P T E R C O N T E N T S © photo75/iStockphoto. 4.1 THE WHILE LOOP 126 SYN while Statement 127 CE 1 Don’t Think “Are We There Yet?” 130 CE 2 Infinite Loops 130 CE 3 Off-by-One Errors 131 ST 1 Special Form of the print Function 132 C&S The First Bug 132 4.2 PROBLEM SOLVING: HAND-TRACING 133 4.3 APPLICATION: PROCESSING SENTINEL VALUES 135 ST 2 Processing Sentinel Values with a Boolean Variable 138 ST 3 Redirection of Input and Output 138 4.4 PROBLEM SOLVING: STORYBOARDS 139 4.5 COMMON LOOP ALGORITHMS 141 4.6 THE FOR LOOP 145 SYN for Statement 145 SYN for Statement with range Function 146 PT 1 Count Iterations 148 HT 1 Writing a Loop 149 4.7 NESTED LOOPS 152 WE1 Average Exam Grades 155 WE2 A Grade Distribution Histogram 157 4.8 PROCESSING STRINGS 159 4.9 APPLICATION: RANDOM NUMBERS AND SIMULATIONS 164 WE 3 Graphics: Bull’s Eye 167 4.10 GRAPHICS: DIGITAL IMAGE PROCESSING 169 4.11 PROBLEM SOLVING: SOLVE A SIMPLER PROBLEM FIRST 174 C&S Digital Piracy 180 126 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 Python, 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: 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: Just Enough Programming Logic and Design
    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. Using a Definite while Loop with a Counter You can use a while loop to execute a body of statements continuously as long as some condition continues to be true. To make a while loop end correctly, make sure your program performs three separate actions: l Initialize a variable called the loop control variable before the loop ’ s while expression — that is, before the loop begins executing. l Test the loop control variable in the while expression; if the result is true, the loop body begins executing, but if it is false, the loop ends. l Alter the value of the loop control variable so that the while expression eventually evaluates as false within the loop body. For example, the code in Figure 4-2 shows a loop that displays Hello four times. The variable count is the loop control variable. The loop executes as follows: l The loop control variable is initialized to 0. l The while expression compares count to 4. l The value is less than 4, so the loop body executes. The loop body consists of two statements that display Hello and then add 1 to count . l The next time count is evaluated, its value is 1, which is still less than 4, so the loop body executes again. Hello displays a second time and count becomes 2, Hello displays a third time and count becomes 3, then Hello displays a fourth time and count becomes 4. l Now when the expression count < 4? is evaluated, it is false , so the loop ends. start stop No Yes Declarations num count = 0 count = count + 1 start Declarations num count = 0 while count < 4 output Hello count = count + 1 endwhile stop count < 4? output “Hello” Loop control variable is initialized.
  • Book cover image for: Introduction to Programming and Problem-Solving Using Scala
    We will explore alternate ways of solving problems like this that can be more efficient in chapter 15 . For now, these methods give us the ability to solve complex problems that would otherwise be out of our reach. 8.6 End of Chapter Material 8.6.1 Problem Solving Approach This chapter added quite a few new constructs for you to pick from for any given line of code in the form of three different types of loops. These have been added below to what was given previously. 1. Call a function just for the side effects. 2. Declare something: • A variable with val or var . • A function with def . Inside of the function will be statements that can pull from anything in this list. • A type declaration with type . 3. Assign a value to a variable. 4. Write a conditional statement: • An if statement. • A match statement. 5. Write a loop statement: • Use a while loop when you do not have a collection or know how many times something will happen, nor do you need to use it as an expression. • Use a do-while loop in a situation where you could consider a while loop, but you know that it should always happen at least once. • Use a for loop to run through the elements of a collection or to do simple counting. 8.6.2 Summary of Concepts • The while loop is a pre-test conditional loop. It will repeat the body of the loop until a condition check returns false . The condition is checked before the first execution of the body and then before any subsequent executions. The while loop is used as a statement only. It results in Unit so it cannot be used as a productive expression. 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.
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.