
Mastering Repetition with Loops in Programming
Learn the fundamentals of while, do-while, and for loops to efficiently execute statements in programming. Understand the distinctions between these loop types and how to use break and continue statements effectively. Dive into the power of repetition and grasp how using appropriate loop parameters can simplify complex tasks.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Lecture Set 5 Control Structures Part D - Repetition with Loops
Objectives Learn to write while, do-while, and for loops to repeatedly execute statements Learn the differences between these three types of loops Learn how to use loop break and continue statements This material is mostly review so it should go quickly you have seen most of it already 8/6/2013 9:01 PM
Introduction to Loops These structures are part of nearly every program written Repetition is the most powerful feature of any language it is what computers do best (and FAST!) Learning how to construct loops with appropriate loop parameters can make difficult tasks seem easy (and code-able with a short instruction sequence) 8/6/2013 9:01 PM
Executing Statements Repeatedly Situations where repetition is used Calculating payroll a loop is used to calculate the payroll for each employee Reading multiple records in a file a loop is used to process each record in a file Graphical animations a loop is used to move graphical objects about the screen Accounting problems depreciation and loan balances are calculated repeatedly for multiple periods 8/6/2013 9:01 PM
Types of Loops Pre-test loops -- test a condition before executing the statements in a loop Post-test loops -- execute the loop's statements first, and then test the loop's condition 8/6/2013 9:01 PM
while and do-while Loops (Syntax) - 1 Do-While loop do { [statements] [break;] [continue;] [statements] } while (condition); 8/6/2013 9:01 PM
while and do-while Loops (Syntax) - 2 while loop while (condition) { [statements] [break;] [continue;] [statements] }
DoWhile and DoUntil Loops (Syntax, continued) The while loop tests the condition before executing the statements in the body of a loop The condition evaluates to a Boolean value and the loop will continue repeating as long as the condition is true The while loop will execute 0 or more times The do-while loop tests the condition after the first execution of the loop and will continue repeating as long as the condition is true The do-while loop will execute 1 or more times When the condition becomes false, execution continues with the statements following the loop The break and continue statements will be discussed at the end of this Lecture Set 3/19/2025 6:01 AM
Loops and Counters A counter is a variable whose value increases by a constant value each time through a loop The constant value used to increment the counter is typically 1 but does not have to be A counter update takes the following general form: counter = counter + 1; counter += 1; counter++; i -= 5; // decreases the counter i by 5 3/19/2025 6:01 AM
Loops and Counters (example) Print the counting numbers 1 through 10 using a while loop Almost every loop has a loop control variable (lcv) that is used to control the execution of the loop int counter = 1; // lcv initialization while (counter <= 10) // lcv test { Debug.WriteLine(counter); counter += 1; // lcv update } // end while loop 3/19/2025 6:01 AM
Loops and Counters (Example, continued) Print the counting numbers 1 through 10 using a do-while loop int counter = 1; do { Debug.WriteLine(counter); counter += 1; } while (counter <= 10); 3/19/2025 6:01 AM
The Role of an Accumulator An accumulator is similar to a counter An accumulator is updated each time the statements in a loop execute It can be used to calculate (accumulate) a total An accumulator usually takes the following general form: accumulator = accumulator + value; accumulator += value; But we will see other forms of accumulators as well they are a powerful programming tool 3/19/2025 6:01 AM
Accumulator (Example) Store the sum of the counting numbers 1 through 10 int counter = 1; int accumulator = 0; while (counter <= 10) { Debug.WriteLine(counter); accumulator += counter; counter += 1; } 3/19/2025 6:01 AM
Infinite Loops A condition must ultimately occur causing a loop to exit Loops can be mistakenly written so that statements execute indefinitely These loops are called infinite loops Infinite loop example (counter is always equal to 1): int counter = 1; while (counter <= 10) { Debug.WriteLine(Counter); } 3/19/2025 6:01 AM
Nested Loops and Decision Structures Loops can be nested, just as decision statements can be nested Loops can contain decision statements Decision statements can contain loops Both can contain nested structures HOWEVER it is generally a good idea to avoid any heavy nesting of control structures, especially when loops are involved Complicates logic Helpful to put nested loops in separate functions 3/19/2025 6:01 AM
Combining Loops and Decision Statements (Example) Determine whether a number is prime // Simple-minded function to determine if a number is prime private Boolean isPrime (int arg) { if (arg % 2 == 0) return false; int count = 3; while (count < arg) { if (arg % count) == 0) return false; count += 2; } // end while loop return true; } // end isPrime 3/19/2025 6:01 AM
for Loops (Introduction) for loops execute statements repeatedly We usually use a for loop in place of a while loop when the iteration count (the number of times the loop will execute) is known in advance for loops usually run more quickly than comparable Do loops because they are optimized for loops are usually more readable than equivalent Do loops (Why?) 3/19/2025 6:01 AM
For Loops (Syntax) for (initialization; condition; update) { [statements] [break;] [continue;] [statements] } // end for loop // next sequential statement (See explanation on next page) 3/19/2025 6:01 AM
For Loop Sequence of Steps (continued) 1. The initialization expression assigns a value to a loop control variable (lcv) The condition normally compares the lcv to a loop termination value If the condition is true, the loop body is executed once When loop body execution reaches the end (right) brace, the lcv is updated and steps 2-4 are repeated If the condition is false the loop terminates and execution continues with the next sequential statement Break and continue statements are discussed later in the Lecture Set 2. 3. 4. 5. 3/19/2025 6:01 AM
for Loops (Example) Print the counting numbers 1 to 10 for (int counter = 1; counter <= 10, counter++) { Debug.WriteLine(counter); } // end for loop OR, since the loop has a one-statement body for (int counter = 1; counter <= 10, counter++) Debug.WriteLine(counter); 3/19/2025 6:01 AM
Execution of a for Loop 3/19/2025 6:01 AM
Nested for Loops (Example) Print a multiplication table int factor1, factor2, result; for (factor1 = 1; factor1 <= 10; factor1++) { for (factor2 = 1; factor2 <= 10; factor2++) { result = factor1 * factor2; Debug.WriteLine(result.ToString() + inner loop"); } // end inner loop Debug.WriteLine(factor1.ToString() + outer loop ); } // end outer loop 3/19/2025 6:01 AM
Using the Step Keyword Use the Step keyword to modify a counter's value by a value other than 1 Example to decrement a counter by 5 int currentYear As Integer for (currentYear = 2000; currentYear >= 1900; Step 5) { Debug.WriteLine(CurrentYear.ToString) } // end for loop OR use the following for loop header: for (currentYear = 2000; currentYear >= 1900; currentYear -= 5) 3/19/2025 6:01 AM
break and continue Statements Can be used with any loop form break causes the innermost loop that contains it to exit immediately, sending control to the first instruction that follows the loop (next sequential instruction or nsi) continue causes the innermost loop that contains it to repeat immediately (effectively sending control to the loop header so that the expressions that control loop repetition can be executed again) 3/19/2025 6:01 AM
The break Statement (Example) decimal monthlyInvestment; decimal monthlyInterestRate; int months; decimal futureValue; for (int i = 1; i<= months; i++) { futureValue = (futureValue + monthlyInvestment) * (1 + monthlyInterestRate); if (futureValue > 1000000.0) { MessageBox.Show("Future value is too large.", "Future Value Overflow!"); break; // break from or exit the for loop to nsi } // end if } // end for loop // next sequential instruction (nsi) 3/19/2025 6:01 AM
The continue Statement int sumNumbers = 0; int sumBigNumbers = 0; for (int i = 1; i <=6; i++) { sumNumbers += i; if (i < 4) { continue; // to top of loop; increment and test i } // end if sumBigNumbers += i; } // end for loop 3/19/2025 6:01 AM
The Implications of Long-running Loops Some loops can run for hours Display messages periodically in long-running loops, or Show a progress bar as the loop is running so the user knows that progress is being made Improve the performance of long-running loops where possible Move unnecessary statements to the outside of a loop 3/19/2025 6:01 AM
Setting and Clearing Breakpoints How to set and clear breakpoints To set a breakpoint, click in the margin indicator bar to the left of a statement. Or, press the F9 key to set a breakpoint at the cursor insertion point. Then, a red dot will mark the breakpoint. To remove a breakpoint, use either technique for setting a breakpoint. To remove all breakpoints at once, use the Clear All Breakpoints command in the Debug menu. How to work in break mode In break mode, a yellow arrowhead marks the current execution point, which points to the next statement that will be executed. To step through your code one statement at a time, press the F11 key or click the Step Into button on the Debug toolbar. To continue normal processing until the next breakpoint is reached, press the F5 key. 3/19/2025 6:01 AM