Lecture 5: Control Structure loops PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document is a lecture on programming loops, likely part of an introductory computer science course. It covers various loop types, including while loops, for loops, and do-while loops. The lecture also touches on different aspects of loop control, such as sentinel values and loop design strategies.
Full Transcript
Lecture 5: Control Structure loops CS110: Programming Language I Table of contents 01 02 03 Why loops? While loops Sentinel-controlled repetition 04 05 06 do..While loop For loop...
Lecture 5: Control Structure loops CS110: Programming Language I Table of contents 01 02 03 Why loops? While loops Sentinel-controlled repetition 04 05 06 do..While loop For loop Break continue 07 Nested control structures 01 Why loops? Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times: System.out.println("Welcome to Java!"); So, how do you solve this problem? Iterate / Repeating Code ❖ Loops are used in programs for repeated execution of one or more statements until a terminating condition is reached.. Types of repetition ❑ Counter- controlled repetitions / Definite repetition: Terminate the execution of the block after it is executed for a fixed number of times. Definite repetition, because the number of repetitions is known before the loop begins executing ❑ Sentinel – controlled repetitions / indefinite repetition: Terminate the execution of the block after one of the designated values called a sentinel is encountered Use sentinel values for indefinite repetition Loops statements Loop statements are used to repeat lines of code Java provides three types of loops: ✓ for ✓ while ✓ do-while 02 While loop while Loop Syntax The while loop continually executes a block of statements while a particular condition is true. The while statement evaluates boolean expression. The statement(s) within the curly braces execute as long as boolean expression is true. Eventually, the condition will become false. At this point, the repetition terminates, and the first statement after the repetition statement executes. while Loop/ Pre-Test Loop A pre-test loop evaluates the condition before the loop executes. If the condition is false, the loop stops or may never execute. while loop flow chart: While loop Counter-Controlled Repetition Example In this example, you know exactly how many times the loop body needs to be executed because the control variable count is used to count the number of executions. Trace while loop What is the output of this program? What is the value of count after executing the program? 1 3 2 4 Trace while loop (cont.) 5 7 9 6 8 Loop Design Strategies Consider three steps when writing a loop: Step 1: Identify the statements that need to be repeated. Step 2: Wrap these statements in a loop Step 3: Code the loop-continuation-condition and add appropriate statements for controlling the loop. Common Programming Error Loop Logical Errors Execute the loop body 10 times int count = 1; while (count < 10){ ……….. count++; } int count = 0; while (count < = 10){ ……….. count++; } while : Counter-Controlled Repetition Class average Exercise A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. N o t e : The class average is equal to the sum of the grades divided by the number of students. while : Counter-Controlled Repetition Class average Exercise Now, write the code! while : Exercise 03 Sentinel-controlled repetition While loop Sentinel-controlled repetition Let’s look at an example: Let’s say you have to write a program to enter exam marks and find their average, but you may not know how many exams are involved. Instead of forcing users to count them all ahead of time, you can allow them to enter the marks one at a time and then enter -1 to indicate the completion of the entries. In such situations, you have to use the while loop. It works like this: The while loop continually executes a block of statements while a particular condition is true. While loop Sentinel-controlled repetition Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value. A sentinel value (also called a signal value, a dummy value or a flag value) can be used to indicate “end of data entry.” A sentinel value must be chosen that can not be confused with an acceptable input value. ❑ Sentinel-controlled repetition is often called indefinite repetition because the number of repetitions is not known before the loop begins executing. Sentinel-controlled repetition Example Develop a class-averaging program that prompts users for grades of arbitrary number of students , and then output their average. The input -1 signifies the end of the input. Sentinel-controlled repetition Example Program logic Reads the first value before reaching the while. This value determines whether the program’s flow of control should enter the body of the while. If the condition of the while is false, the user entered the sentinel value, so the body of the while does not execute (i.e., no grades were entered). If the condition is true, the body begins execution and processes the input. Then the loop body inputs the next value from the user before the end of the loop. Sentinel-controlled repetition Example Sentinel-controlled repetition Example Sentinel-controlled repetition Example Sentinel-controlled repetition Exercise 03 do … while loop do…while Loop A post-test loop evaluates its condition at the bottom of the loop instead of the top. The do-while loop is a post-test loop. do…while Loop The do-while loop is a modified while loop that allows you to execute the loop once, before testing the Boolean condition. Syntax: do…while Loop Example do…while Loop Exercise 04 for loop for: Counter-Controlled Repetition ▪ A for loop executes a known number of times. ▪ For loops are also called definite loops. ▪ It is Pre-Test Loop ▪ Specifies the counter-controlled-repetition details in a single line of code. For loop syntax and flowchart ▪ Syntax: ▪ Flow chart: The initialization expression initializes the loop. It’s executed only once, as the loop begins. Tells the compiler what variable (called a loop counter/ control variable) is used in the loop. When the loop continuation condition evaluates to false, the loop terminates. The update expression is invoked after each iteration through the loop. This expression can increment or decrement a value. Each expression should be separated with a semicolon (;). for loop example Trace for loop What is the output of this program? What is the value of i after executing the program? 1 3 5 2 4 6 Trace for loop 7 9 8 10 For Loop example Common Programming Errors Variable’s scope A variable’s scope defines where it can be used in a program. For loop exercise Reimplement the “class average” program using for loops For loop The initialization, loop-continuation condition and increment can contain arithmetic expressions. Example Assume that x = 2 and y = 10 for (int j = x; j