Computer Science

Loop in programming

A loop in programming is a control structure that allows a set of instructions to be repeated multiple times. It is used to automate repetitive tasks and iterate over a collection of data. There are different types of loops, such as for loops, while loops, and do-while loops, each with its own specific use cases and syntax.

Written by Perlego with AI-assistance

11 Key excerpts on "Loop in programming"

  • Book cover image for: An Object-Oriented Approach to Programming Logic and Design
    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 .
  • 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: Programming Logic and Design, Introductory
    If you omit any of these actions—initialize, test, alter—or perform them incorrectly, you run the risk of creating an infinite loop. Once your logic enters the body of a structured loop, the entire loop body must execute. Program logic can leave a structured loop only at the evaluation of the loop control variable. Commonly, you can control a loop’s repetitions in one of two ways: • Use a counter to create a definite, counter-controlled loop. • Use a sentinel value to create an indefinite loop. Using a Definite Loop with a Counter Figure 5-3 shows a loop that displays Hello four times. The variable count is the loop control variable. This loop is a definite loop because it executes a definite, predetermined number of times—in this case, four. The loop is a counted loop, or counter-controlled loop, because the program keeps track of the number of loop repetitions by counting them. The false statement is #3. A loop is a structure that repeats actions while some condition continues. TWO TRUTHS & A LIE Appreciating the Advantages of Looping 1. When you use a loop, you can write one set of instructions that operates on multiple, separate sets of data. 2. A major advantage of having a computer perform complicated tasks is the ability to repeat them. 3. A loop is a structure that branches in two logical paths before continuing. 179 Using a Loop Control Variable Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. The loop in Figure 5-3 executes as follows: • The loop control variable, count, is initialized to 0. • The while expression compares count to 4. • The value of count is less than 4, and so the loop body executes. The loop body shown in Figure 5-3 consists of two statements that, in sequence, display Hello and add 1 to count. • The next time the condition count < 4 is evaluated, the value of count is 1, which is still less than 4, so the loop body executes again.
  • Book cover image for: Java Concepts
    eBook - PDF
    • Cay S. Horstmann(Author)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    5 C H A P T E R 217 LOOPS 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 G O A L S C H A P T E R C O N T E N T S 5.1 THE WHILE LOOP 218 Syntax 5.1: while Statement 219 Common Error 5.1: Don’t Think “Are We There Yet?” 223 Common Error 5.2: Infinite Loops 224 Common Error 5.3: Off-by-One Errors 224 5.2 PROBLEM SOLVING: HAND-TRACING 225 Computing & Society 5.1: Software Piracy 229 5.3 THE FOR LOOP 230 Syntax 5.2: for Statement 230 Programming Tip 5.1: Use for Loops for Their Intended Purpose Only 235 Programming Tip 5.2: Choose Loop Bounds That Match Your Task 236 Programming Tip 5.3: Count Iterations 236 Special Topic 5.1: Variables Declared in a for Loop Header 237 5.4 THE DO LOOP 238 Programming Tip 5.4: Flowcharts for Loops 239 5.5 APPLICATION: PROCESSING SENTINEL VALUES 239 Special Topic 5.2: Redirection of Input and Output 242 Special Topic 5.3: The “Loop and a Half” Problem 242 Special Topic 5.4: The break and continue Statements 243 5.6 PROBLEM SOLVING: STORYBOARDS 245 5.7 COMMON LOOP ALGORITHMS 248 How To 5.1: Writing a Loop 252 Worked Example 5.1: Credit Card Processing 5.8 NESTED LOOPS 255 Worked Example 5.2: Manipulating the Pixels in an Image 5.9 APPLICATION: RANDOM NUMBERS AND SIMULATIONS 259 Special Topic 5.5: Loop Invariants 262 5.10 USING A DEBUGGER 264 How To 5.2: Debugging 267 Worked Example 5.3: A Sample Debugging Session Computing & Society 5.2: The First Bug 269 218 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.
  • Book cover image for: Microsoft® Visual C# 2015
    eBook - PDF

    Microsoft® Visual C# 2015

    An Introduction to Object-Oriented Programming

    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.
  • Book cover image for: Microsoft Visual C#: An Introduction to Object-Oriented Programming
    C H A P T E R 5 Looping Upon completion of this chapter, you will be able to: • Create loops using the while statement • Create loops using the for statement • Create loops using the do statement • Use nested loops • Accumulate totals • Understand how to improve loop performance • Appreciate 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. 186 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 because of 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.
  • Book cover image for: Brief C++
    eBook - PDF

    Brief C++

    Late Objects

    • Cay S. Horstmann(Author)
    • 2017(Publication Date)
    • Wiley
      (Publisher)
    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.
  • Book cover image for: Job Ready Python
    eBook - PDF
    • Haythem Balti, Kimberly A. Weiss(Authors)
    • 2021(Publication Date)
    • Wiley
      (Publisher)
    P A R T I I Loops and Data Structures Lesson 7: Controlling Program Flow with Loops Lesson 8: Understanding Basic Data Structures: Lists Lesson 9: Understanding Basic Data Structures: Tuples Lesson 10: Diving Deeper into Data Structures: Dictionaries Lesson 11: Diving Deeper into Data Structures: Sets Lesson 12: Pulling It All Together: Prompting for an Address Lesson 13: Organizing with Functions Lesson 7 Controlling Program Flow with Loops P ython supports a variety of control structures that determine how content in a program will work and interact. This lesson continues the exploration including additional control structures that make creating algorithms possible. The lesson concludes with a discussion of how iteration aids in text processing. LEARNING OBJECTIVES By the end of this lesson, you will be able to: • Create a Python script that uses a for loop to repeat an activity until a specific crite -rion is met. • Create a Python script that uses a while loop to repeat an activity as long as a specific criterion holds true. • Using string operations to manipulate text. Job Ready Python 144 ITERATIONS OVERVIEW Lesson 5 introduced control structures. These structures are used to “control” the flow of data through an application. Python supports various structures through control state-ments of sequence, iteration, and selection. In Lesson 5 selection and progression were discussed. The sequence control structure (executed in a sequence statement) is com -pleted one statement after the other. The selection control structure (implemented in a selection statement) executes only after a particular condition is met. Although these types of code statements allow applications to run, in most cases, using only sequence and selection statements would make for very long program code. In this lesson, a third control structure is introduced: iteration.
  • 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: Python For Everyone
    • Cay S. Horstmann, Rance D. Necaise(Authors)
    • 2019(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: Just Enough Programming Logic and Design
    l You might retrieve a new value from an input device. l When a loop control variable is numeric, its value is often altered by incrementing it, or adding to it (see Figure 4-2). l Other loops are controlled by reducing, or decrementing , a variable and testing whether the value remains greater than some benchmark value. For example, the loop in Figure 4-2 could be rewritten so that count is initialized to 4, and reduced by 1 on each pass through the loop. The revised loop should then continue while count remains greater than 0. Because you frequently need to increment or decrement a variable, many programming languages contain shortcut operators for these operations. You will learn about these shortcut operators when you study a programming language that uses them. A loop such as the one in Figure 4-2, for which the number of iterations is predetermined, is called a definite loop or counted loop . The looping logic shown in Figure 4-2 uses the count variable as a counter. A counter is any numeric variable you use to count the number of times an event has occurred. In everyday life, people usually count things starting with 1. However, many programmers prefer starting their counted loops with a variable containing 0 for two reasons. First, in many computer applications, numbering starts with 0 because of the 0-and-1 nature of computer circuitry. Second, when you learn about arrays in Chapter 5, you will discover that array manipulation naturally lends itself to 0-based loops. However, although it is common, you are not required to start counting using 0. You could achieve the same results in a program such as the one in Figure 4-2 by initializing count to 1 and continuing the loop while it remains less than 5. You could even initialize count to some arbitrary value such as 23 and continue while it remains less than 27 (which is 4 greater than 23). This last choice is not recommended because it is confusing; however, the program would work just as well.
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.