Computer Science
Java Loops
Java loops are used to execute a block of code repeatedly until a certain condition is met. There are three types of loops in Java: for, while, and do-while. The choice of loop depends on the specific requirements of the program.
Written by Perlego with AI-assistance
Related key terms
1 of 5
10 Key excerpts on "Java Loops"
- eBook - PDF
- Joyce Farrell(Author)
- 2018(Publication Date)
- Cengage Learning EMEA(Publisher)
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. - 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.
- 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. - eBook - PDF
- Joyce Farrell(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
• Three actions are taken with a loop control variable in every while loop: You must initialize a loop control variable, compare the variable to some value that controls whether the loop continues or stops, and alter the variable that controls the loop. • Nested loops are loops that execute within the confines of other loops. When nesting loops, you maintain two separate loop control variables and alter each at the appropriate time. • Common mistakes that programmers make when writing loops include failing to initialize the loop control variable, neglecting to alter the loop control variable, using the wrong comparison expression with the loop control variable, and including statements inside the loop that belong outside the loop. • Most computer languages support a for statement or for loop that you can use with definite loops when you know how many times a loop will repeat. The for statement uses a loop control variable that it automatically initializes, tests, and alters. • In a posttest loop, the loop body executes at least one time because the loop control variable is not tested until after the first iteration. • In all structured loops, there is exactly one loop-controlling value, and it provides either the only entrance to or the only exit from the loop. • Loops are used in many applications—for example, to accumulate totals in business reports. Loops also are used to ensure that user data entries are valid by repeatedly reprompting the user. • In the selection structure, the two logical paths that emerge from a test join together following their actions. In the loop structure, the paths that emerge from the test do not join together; instead, one of the paths eventually returns to the same test. Key Terms A loop control variable is a variable that determines whether a loop will continue. A definite loop is one for which the number of repetitions is a predetermined value. - 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.
- Joyce Farrell(Author)
- 2012(Publication Date)
- Cengage Learning EMEA(Publisher)
C H A P T E R 4 Looping In this chapter, you will learn about: The loop structure Using a loop control variable Nested loops Avoiding common loop mistakes Using a for loop Common loop applications Copyright 2012 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. Understanding the Loop Structure Although making decisions is what makes computers seem intelligent, looping makes computer programming both efficient and worthwhile. When you use a loop, you can write one set of instructions that operates on multiple data items. For example, a large company might use a single loop to produce thousands of paychecks, or a big-city utility company might use a single loop to process millions of customer bills. Using fewer instructions results in less time needed for design and coding, less compile time, and fewer errors. Recall the loop structure that you learned about in Chapter 2. Along with sequence and selection, it is one of the three basic structures used in structured programming. Figure 4-1 shows a loop structure. This loop starts with a test of a Boolean expression. The statements within a loop constitute the loop body ; the body executes as long as the loop-controlling Boolean expression remains true. The same loop-controlling question is asked following each execution of the loop body; the structure is exited only when the test expression is false. You may hear programmers refer to looping as repetition or iteration .- eBook - PDF
- Joyce Farrell(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
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. - eBook - PDF
Microsoft® Visual C# 2015
An Introduction to Object-Oriented Programming
- Joyce Farrell, , , (Authors)
- 2015(Publication Date)
- Cengage Learning EMEA(Publisher)
C H A P T E R 5 Looping In this chapter you will: Learn how to create loops using the while statement Learn how to create loops using the for statement Learn how to create loops using the do statement Use nested loops Accumulate totals Understand how to improve loop performance Learn about looping issues in GUI programs 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. 190 C H A P T E R 5 Looping In the previous chapter, you learned how computers make decisions by evaluating Boolean expressions. Looping allows a program to repeat tasks based on the value of a Boolean expression. For example, programs that produce thousands of paychecks or invoices rely on the ability to loop to repeat instructions. Likewise, programs that repeatedly prompt users for a valid credit card number or for the correct answer to a tutorial question run more efficiently with loop structures. In this chapter, you will learn to create loops in C# programs. Computer programs seem smart due to their ability to make decisions; looping makes programs seem powerful. Creating Loops with the while Statement 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. 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. - 95 C H A P T E R 4 LOOPS C H A P T E R G O A L S To implement while, for, and do loops To avoid infinite loops and off-by-one errors To understand nested loops To implement programs that read and process data sets 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 96 SYN while Statement 97 CE 1 Infinite Loops 100 CE 2 Don’t Think “Are We There Yet?” 101 CE 3 Off-by-One Errors 101 C&S The First Bug 102 4.2 PROBLEM SOLVING: HAND-TRACING 103 4.3 THE FOR LOOP 106 SYN for Statement 106 PT 1 Use for Loops for Their Intended Purpose Only 109 PT 2 Choose Loop Bounds That Match Your Task 110 PT 3 Count Iterations 110 4.4 THE DO LOOP 111 PT 4 Flowcharts for Loops 111 4.5 PROCESSING INPUT 112 ST 1 Clearing the Failure State 115 ST 2 The Loop-and-a-Half Problem and the break Statement 116 ST 3 Redirection of Input and Output 116 4.6 PROBLEM SOLVING: STORYBOARDS 117 4.7 COMMON LOOP ALGORITHMS 119 HT 1 Writing a Loop 123 WE1 Credit Card Processing 126 4.8 NESTED LOOPS 126 WE2 Manipulating the Pixels in an Image 129 4.9 PROBLEM SOLVING: SOLVE A SIMPLER PROBLEM FIRST 130 4.10 RANDOM NUMBERS AND SIMULATIONS 134 C&S Digital Piracy 138 96 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 C++, 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 how to repeatedly execute statements 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.
- eBook - PDF
- Cay S. Horstmann(Author)
- 2014(Publication Date)
- Wiley(Publisher)
I can remember the exact instant in time at which it dawned on me that a great part of my future life would be spent finding mistakes in my own programs.” Computing & Society 5.2 The First Bug Media Bakery. C H A P T E R S U M M A RY 270 Chapter 5 Loops Choose between the while loop and the do loop. • The do loop is appropriate when the loop body must be executed at least once. Implement loops that read sequences of input data. • A sentinel value denotes the end of a data set, but it is not part of the data. • You can use a Boolean variable to control a loop. Set the variable to true before entering the loop, then set it to false to leave the loop. • Use input redirection to read input from a file. Use output redirection to capture program output in a file. Use the technique of storyboarding for planning user interactions. • A storyboard consists of annotated sketches for each step in an action sequence. • Developing a storyboard helps you understand the inputs and outputs that are required for a program. Know the most common loop algorithms. • To compute an average, keep a total and a count of all values. • To count values that fulfill a condition, check all values and increment a counter for each match. • If your goal is to find a match, exit the loop when the match is found. • To find the largest value, update the largest value seen so far whenever you see a larger one. • To compare adjacent inputs, store the preceding input in a variable. Use nested loops to implement multiple levels of iteration. • When the body of a loop contains another loop, the loops are nested. A typical use of nested loops is printing a table with rows and columns. Apply loops to the implementation of simulations. • In a simulation, you use the computer to simulate an activity. • You can introduce randomness by calling the random number generator.
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.









