Chapter 5: Control Structure

Slides:



Advertisements
Similar presentations
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Advertisements

REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
CPSC 171 Introduction to Computer Science 3 Levels of Understanding Algorithms More Algorithm Discovery and Design.
Looping While-continue.
Chapter 2 - Algorithms and Design
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping with.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Unit 2 – Algorithms & Pseudocode. Algorithms Computer problems solved by executing series of action in order Procedure –The Actions to execute –The Order.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Chapter 7 Problem Solving with Loops
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Topic: Control Statements. Recap of Sequence Control Structure Write a program that accepts the basic salary and allowance amount for an employee and.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CHAPTER 6: REPETITION AND LOOP STATEMENTS Learning outcomes  Define the concept of repetition structure.  Specify.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Lesson #5 Repetition and Loops.
Chapter 4: Looping Structures LECTURER : MRS ROHANI HASSAN
ALGORITHMS AND FLOWCHARTS
REPETITION CONTROL STRUCTURE
CHAPTER 6: REPETITION AND LOOP STATEMENTS
Topics Introduction to Repetition Structures
Lesson #5 Repetition and Loops.
CHAPTER 5A Loop Structure
Chapter 4 Loops DDC 2133 Programming II.
Pseudocode Upsorn Praphamontripong CS 1110 Introduction to Programming
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
( Iteration / Repetition / Looping )
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Siti Nurbaya Ismail Senior Lecturer
ALGORITHMS AND FLOWCHARTS
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Control Structure Senior Lecturer
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Control Structure Senior Lecturer
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Lesson #5 Repetition and Loops.
Iteration: Beyond the Basic PERFORM
ALGORITHMS AND FLOWCHARTS
CIS 16 Application Development Programming with Visual Basic
Introduction to Algorithms and Programming
Topics Introduction to Repetition Structures
Chapter 6: Repetition Statements
Chapter 5: Control Structure
Let’s all Repeat Together
Introduction to Repetition Structures
CHAPTER 4 Iterative Structure.
Topics Introduction to Repetition Structures
Lesson #5 Repetition and Loops.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Chapter 2 - Algorithms and Design
The while Looping Structure
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Chapter 5: Control Structure Part 2: Repetition/Loop Control Structure

Lesson Outcome At the end of this chapter, students should be able to: Use the control structure in problem solving Understand the concept of loop control structure Apply iteration structure on the given problems Differentiate simple loop and nested loop Understand the execution of pseudocode uses nested loop control structure

Introduction In some cases, we may want to solve a problem that needs to do the same process for several time. For this type of problem, it is suitable to use repetition or loop or iteration control structure. For example, the concept of repetition is implemented when you want to check balance in your account using ATM.

Introduction (cont.) The steps to follow are: Insert ATM card Choose language Insert pin number The machine asks you which transaction to perform. Say that you choose a check balance transaction The machine will display the amount in your account The machine asks you either you want to continue the next transaction or not. If you choose yes, the machine will repeat the above forth (4) step.

Statement for Repetition (Loop Control Structure) There are two types of repetition that can be implemented: Counter loop - The number of repetition is identified Sentinel loop - The number of repetition is unknown The statement while…endWhile can be used to implement both type of repetition control structure.

Statement for Repetition (Loop Control Structure) (cont.) The pseudocode for while…endWhile statement for loop: Initial value of a loop while (condition) statement(s) to be repeated statement to update the condition endWhile

Statement for Repetition (Loop Control Structure) (cont.) Here is the flowchart for loop control structure:

Statement for Repetition (Loop Control Structure) (cont.) When implementing counter loop, the following three statements must be available: initialize counter with 1 counter ≤ N increase counter by 1 where N represent the number of repetition.

Statement for Repetition (Loop Control Structure) (cont.) Some examples of problem that we know the number of repetition needed are: Ask the user to enter 30 numbers. Count how many odd numbers. Determine the highest mark in a class of 35 students. Find the average of rain received in particular city in a year. Calculate the total salary of all staff in finance department. The number of staff will be entered by the user.

Example Write flowcharts and pseudocode for the following problems: a) Display the multiplication table as follows: 1 x 2 = 2 2 x 2 = 4 3 x 2 = 6 : : 10 x 2 = 20

Example (cont.) PSEUDOCODE: Start Set count  1 While (count ≤ 10) result = count x 2 Display count, “ x 2 = ”, result Display newline Add 1 to count endWhile End

FLOWCHART:

Tracing Algorithm for Counter Loop

Exercise 5D What is the output is n = 4?

Exercise 5E (Counter Loop) Write an algorithm using flowchart and pseudocode for the following problem statement: A second hand store is having a seven day sale during which the price of any unsold item drops 10% each day. For example, an item that costs RM10.00 on the first day costs 10% less (RM9.00), on the second day. On the third day, the same item is 10% less than RM9.00 (RM8.10). Produce a report that shows the price of the item on each day, 1 through 7.

Statement for Repetition (Loop Control Structure) (cont.) When implementing sentinel loop, the following three statements must be available: initialize the loop Condition of the loop Statement to make the condition false The three statements will make sure that the loop starts and stops correctly.

Statement for Repetition (Loop Control Structure) (cont.) Some examples of sentinel loop problem: Ask the user to enter a group of number and end the data entry with zero. Count how many odd numbers in the group. Determine the highest mark in a class. The process stop when the user enters an invalid mark. Calculate the total salary of all staff in finance department. The process ends when there is no more data to be process.

Statement for Repetition (Loop Control Structure) (cont.) The three statements will make sure that the loop starts and stops correctly. For example, if we miss the statement with false condition in the algorithm, we will get an infinite loop. An infinite loop is a scenario where the loop does not stop.

while…endWhile Statement for Sentinel Loop The syntax is: All statements in between while…endWhile will be executed when the condition is TRUE. The repetition stop when the condition is FALSE. Initial value of a loop while(condition) statement(s) to be repeated statement to update the condition endWhile

while…endWhile Statement for Sentinel Loop (cont.) Example 1: Ask the user to enter a group of numbers. The last number is 999. Display all entered numbers. Read number while (number is NOT 999) Display number endWhile

while…endWhile Statement for Sentinel Loop (cont.) Example 2: Input marks of students. Display mark which is less than 50. Stop the process when the user enters invalid marks. Read mark while (mark ≥ 0.0 AND mark ≤ 100) If (mark < 50) Display mark endIF endWhile

Exercise 5F (Sentinel Loop) Suppose that the input is 58 23 176 145 -999. What is the output of the following pseudocode? Start Read num While (num is NOT -999) Display num % 25 Display newline endWhile End

Exercise 5G (Sentinel Loop) Suppose that the input is 10 -6 12 -5 -4 0. What is the output of the following pseudocode? Start Set sum  0 Read num While (num is NOT 0) If (num greater than 0) sum  sum + num Else sum  sum – num endIF endWhile Display “Sum = ” sum End

Exercise 5H (Sentinel Loop) Write an algorithm (pseudocode and flowchart) to input two numbers and display their sum. It asks the user if he/she would like to run the program. If the answer Y or y, it prompts the user to enter two numbers. After adding the numbers and displaying the results, it again asks the user if he/she would like to add more number.

Exercise 5I (Sentinel Loop) One large chemical company pays its salespeople on a commission basis. The salespeople receive RM200.00 per week plus 9 percent of their gross sales for that week. Write a pseudocode and draw a flowchart that use loop structure to input each salesperson’s gross sales for last week and calculate and display that salesperson’s earnings. Enter sales in Ringgit Malaysia (-1 to end): 5000.00 Salary is: RM650.00 Enter sales in Ringgit Malaysia (-1 to end): 6000.00 Salary is: RM740.00 Enter sales in Ringgit Malaysia (-1 to end): 7000.00 Salary is: RM830.00 Enter sales in Ringgit Malaysia (-1 to end): -1   Total number of salesperson: 3 Have a Good Day!!!

Basic Algorithm Using Loop Control Structure The scope of problem for this chapter focuses on how to: Calculate the total Calculate the average Find maximum value and minimum value Count

Basic Algorithm Using Loop Control Structure Example of Problem Statement Write an algorithm that receives the value of test scores for 30 students. Find and displays the following: The total of the test scores The average of the test scores The highest test score The lowest test score Count the number of student that pass the test and the number of student that fail the test. Passing mark is 50.

Algorithm To Calculate The Total General algorithm to calculate the total for a group of numbers: Start Initialize variable total with 0 repeat the following actions until end of data Read number Add number to variable total endRepeat Display total End

Algorithm To Calculate The Average General algorithm to calculate the average for a group of numbers: Start Set total with 0 Set count with 0 repeat the following actions until end of data Read number total  total + number add 1 to count endRepeat average  total / count Display average End

Algorithm Using while…endWhile To Find Total and Average Calculate the average of 5 numbers Start sum  0 Display “Enter 5 numbers: ” Set counter to 1 While (counter ≤ 5) Read number sum  sum + number add 1 to counter endWhile average  sum / 5 Display “The sum of 5 numbers: ”, sum Display newline Display “The average of 5 numbers: ”, average End

Algorithm To Find The Maximum and The Minimum When the limit values are known, such as student marks, we may apply the general algorithm to find the highest mark as given below: Start Read the first data Assign maximum with the first data repeat until end of data Read next data If (next data > maximum) maximum  next data endIF endRepeat Display maximum End

Algorithm To Find The Maximum and The Minimum General algorithm to find a minimum value: Start Read the first data Set variable minimum with the first data repeat the following actions until end of data Read next data If (next data < minimum) minimum  next data endIF endRepeat Display minimum End

Algorithm Using while…endWhile To Find Maximum and Minimum Find the highest and the lowest mark among 10 marks Start read mark maximum  mark minimum  mark set count to 2 while (count ≤ 10) If (mark > maximum) endIF If (mark < minimum) Add 1 to count endWhile Display maximum, minimum End

Algorithm To Count When we want to count something, the initial value for variable to hold the count is zero. Then we search what we want to count. Every time we found the value that we want, then we increase the value of the count by one. Repeat the process until end of data. Start count_even  0 repeat until end of data read data If (data is even) add 1 to count_even endIF endRepeat Display count_even End

Algorithm Using while…endWhile To Count Calculate how many odd numbers in a group of 20 numbers. Start count_odd  0 set count to 1 while (count ≤ 20) Read number If (number % 2 ≠ 0) add 1 to count_odd endIF Add 1 to count endWhile Display count_odd End

Problem using Counter Loop Task: given 5 marks, calculate the total of marks which are greater than 50. Start sum  0 Set counter to 1 While (counter ≤ 5) Read mark If (mark ≥ 50) sum  sum + mark endIF counter = counter + 1 endWhile Display sum End

Exercise 5J Write pseudocode and draw a flowchart for the following problems: Ask the user to input the volume of monthly rain received in a particular city in a year and displays: The total volume of rain in that city The average rain received The highest rain received The lowest rain received

Exercise 5K Write pseudocode and draw a flowchart for the following problems: Ask the user to enter N numbers. Find: How many odd numbers How many negative numbers Total of number which is divisible by 10

Exercise 5L Write pseudocode and draw a flowchart for the following problems: Write an algorithm that receives the name and the salary of ABC company staff. Then calculates and displays the: Name of the staff with the highest salary Name of the staff with the lowest salary Average salary of all staff Total number of staff with salary below RM2000 Use a sentinel value to exit your loop.

Infinite Loop An infinite loop is a non stop loop, where the repetition keeps running and never stop. Example: Start count  0 number  7 while(count ≤ 100) Display number Read number endWhile Display count End

Nested Loop Nested loop refers to a situation where there is another loop in a loop. In this situation, we have an inner loop and outer loop. The execution of this type of structure is, the computer will finish the inner loop for every iteration of outer loop.

Nested Loop (cont.) Format for nested loop:

Nested Loop (cont.) The flowchart for a nested loop is as follows:

Execution of Nested Loop

Execution of Nested Loop (cont.) Value changes for variables out- counter and inner-counter Expected screen:

Example Given the following pseudocode, trace and provide the output:

Any Question