CHAPTER 4 Iterative Structure.

Slides:



Advertisements
Similar presentations
Programming Logic and Design Eighth Edition
Advertisements

Repetition There are three different ways that a set of instructions can be repeated, and each way is determined by where the decision to repeat is.
Repetition Control Structures
Repetition control structures
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
Objectives In this chapter, you will learn about:
Repetition Control Structure
Steps in Program Development
Chapter 4 Repetitive Execution. 2 Types of Repetition There are two basic types of repetition: 1) Repetition controlled by a counter; The body of the.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Repetition Control Structures
The University of Texas – Pan American
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Pseudocode algorithms using sequence, selection and repetition
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Programming Logic and Design Fifth Edition, Comprehensive
Programming Logic and Design Sixth Edition Chapter 5 Looping.
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.
9-1 COBOL for the 21 st Century Nancy Stern Hofstra University Robert A. Stern Nassau Community College James P. Ley University of Wisconsin-Stout (Emeritus)
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Repetition Control Structures Simple Program Design Third Edition A Step-by-Step Approach 5.
Pseudocode Algorithms Using Sequence, Selection, and Repetition Simple Program Design Third Edition A Step-by-Step Approach 6.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Lecture 5: Stopping with a Sentinel. Using a Sentinel Problem Develop a class-averaging program that will process an arbitrary number of grades each time.
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Topic: Control Statements. Recap of Sequence Control Structure Write a program that accepts the basic salary and allowance amount for an employee and.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Pendalaman Materi Conditional dan Repetition (Pengulangan)
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
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.
ALGORITHMS AND FLOWCHARTS
CS1010 Programming Methodology
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
2008/09/22: Lecture 6 CMSC 104, Section 0101 John Y. Park
Control Structures II Chapter 3
Topics Introduction to Repetition Structures
Algorithms and Flowcharts
CHAPTER 5A Loop Structure
Chapter 5: Control Structure
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Introduction To Flowcharting
( Iteration / Repetition / Looping )
Computer Science Faculty
Topics Introduction to Repetition Structures
ALGORITHMS AND FLOWCHARTS
Control Structure Senior Lecturer
Repetition and Loop Statements
Unit# 9: Computer Program Development
Pseudocode algorithms using sequence, selection and repetition
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
ALGORITHMS AND FLOWCHARTS
3 Control Statements:.
CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING
Chapter 6: Repetition Statements
Understanding Problems and how to Solve them by using Computers
EPSII 59:006 Spring 2004.
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Chopin’s Nocturne.
Presentation transcript:

CHAPTER 4 Iterative Structure

Content Introduction 3 types of iterative structure FOR-ENDFOR WHILEDO-ENDWHILE DOWHILE-ENDWHILE Pseudocode for iterative structure Q&A

Introduction aka repetition/loop structure Same logic steps (a set of instructions) are repeated for several unique sets of data. Process in the loop is repeated a number of times while the condition result is true When the condition result is false, the loop exited

Introduction A completion of the process must be identified which will bring the loop into a stop, otherwise the program may have an infinite loop. For e.g. end of file for input from file, for interactive program, the user might indicate that the input is complete by typing an end value from the keyboard such as an ‘N’ at the “Do you wish to continue?” prompt

Introduction Consider a program to read and calculate the age of all students. The age is calculated by having the current date minus the student’s birth date. These instructions are only written once and can be repeated over and over again for each student using a loop.

Introduction A simple example would be : If you want to print “Hello World” 100 times, you will not use 100 print lines, i.e., print “Hello World” /* line 1 print “Hello World” … print “Hello World” /* line 100 You would only use loop and only having a single print line, i.e., FOR counter = 1 to 100 Print “Hello World” END FOR

Repetition Structure Processes A Process Structure chart is represented by an asterisk at the top-right corner of a rectangular box. Processes An asterisk to denote repetitive component * A Process

Types of Iterative Structure There are 3 types of iterative structure FOR-ENDFOR WHILEDO-ENDWHILE DOWHILE-ENDWHILE

FOR structure Used when the exact number of loop iteration is known in advance. Requires lowest and highest value of a range - initial_value and final_value e.g. 1 and 10 for execution of process for 10 times. Can specify the increment value as well Test the value of loop_index (loop-control variable) at the beginning of each loop to ensure that it is within the specified range of values

FOR structure General structure format Condition is placed on top right side of the iterative component PROCESSES FOR loop_index = i to n [step m] A PROCESS * Initial value Final value Number of step

FOR structure : Example Everyday, a weather station receives 15 temperatures expressed in degrees Fahrenheit. A program is to be written which will accept each Fahrenheit temperature, convert it to Celsius and display both temperatures on the screen. After 15 temperatures have been processed, the word “all temperatures processed” are to be displayed on the screen

Solution Algorithm: Example Loop is terminated once the counter exceeds 15 initializes the counter to 1 FOR counter = 1 to 15 Read fahrenheit Compute celsius = (fahrenheit – 32) * 0.5555 Display fahrenheit, celsius Display “All temperatures processed” These statements will be repeated 15 times

Solution Algorithm: Example The process of FOR loop: It initializes the loop_index (in this case, is the counter) to 1 Execute the statements in the loop Increments the loop_index by 1 as it passes through the loop Tests the loop_index at the beginning of each pass so that it is within the range 1 to 15 Loop is terminated once the loop_index exceeds 15. Then the statement after the loop (i.e. statement #2) will be executed Algorithm: FOR counter = 1 to 15 Read fahrenheit Compute celsius = (fahrenheit – 32) * 0.5555 Display fahrenheit, celsius Display “All temperatures processed”

FOR : Structure Chart counter is initialized to 1 and keeps on incremented once all the steps are executed TEMPERATURE CONVERSION PROCESS TEMPERATURES DISPLAY “All temperatures processed” FOR counter = 1 to 15 Steps are repeated 15 times PROCESS A TEMPERATURE * READ FAHRENHEIT CELSIUS= (FAHRENHEIT – 32) * 0.5555 DISPLAY FAHRENHEIT, CELSIUS

FOR : Pseudocode BEGIN TEMPERATURECONVERSION sequence BEGIN PROCESSTEMPERATURES iteration FOR counter = 1 to 15 BEGIN PROCESSATEMPERATURE sequence READ fahrenheit; celsius = (fahrenheit – 32) * 0.555; WRITE fahrenheit, celsius; END PROCESSATEMPERATURE sequence ENDFOR END PROCESSTEMPERATURES iteration WRITE “All temperatures processed”; END TEMPERATURECONVERSION sequence

For Structure : example 2 Design an algorithm to accept several numbers from the keyboard. The number of input integers is indicated by the first number entered, e.g. if the first number entered is 5, then 5 input integers will follow. Your algorithm should be able to decide and display the even integers which have been entered (excluding the first integer). If there are no even number entered, an appropriate message should be displayed instead. Task : Do the problem analysis Draw the structured chart Create the Pseudocode

Problem Analysis evenFound = 0 numOfInteger, integerValue Initialization evenFound = 0 Input Definition numOfInteger, integerValue Output Definition EvenValues = 99 99 99 99

Problem Analysis Processing Requirements Processing Control MOD is use to find the remainder of a division Processing Requirements READ numOfInteger FOR counter = 1 to numOfInteger 2.1. READ integerValue 2.2. Check Even Number IF number MOD 2 = 0 THEN 2.2.1 evenValues = evenValues + integerValue 2.2.2 evenFound = 1 Check Even Found IF evenFound = 1 THEN DISPLAY evenValues ELSE DISPLAY “No even number found in the input data” Processing Control numOfInteger and integerValue must be integer

Problem Analysis Test Data & Expected Result numOfInteger integerValue Output 5 10, 20, 15, 12, 3 10 20 12 3 13, 9, 5 No even number found in the input data 3.6 error Error

Structured Chart o o o evenFound = 1 else integerValue MOD 2 = 0 PROBLEM evenFound = 0 READ numOfInteger PROCESS INTEGERS DISPLAY Message evenFound = 1 else FOR counter = 1 to numOfInteger o o PROCESS AN INTEGER * DISPLAY evenValues DISPLAY “No even number found in the input data” READ integerValue Check Even Number integerValue MOD 2 = 0 o EVEN NUMBER evenValues = evenValues + integerValue evenFound=1

Pseudocode BEGIN INTEGERPROBLEM sequence evenFound = 0; READ numOfInteger; BEGIN PROCESSINTEGERS iteration FOR counter = 1 to numOfInteger BEGIN PROCESSANINTEGER sequence READ integerValue; BEGIN CHECKEVENNUMBER selection IF integerValue MOD 2 = 0 THEN BEGIN EVENNUMBER sequence evenValues = evenValues + integerValue; evenFound = 1; END EVENTNUMBER sequence END IF END CHECKEVENNUMBER selection END PROCESSANINTEGER sequence ENDFOR END PROCESSINTEGERS iteration BEGIN DISPLAY MESSAGE selection IF evenFound = 1 THEN WRITE evenValues; ELSE WRITE “No even number found in the input data”; END DISPLAYMESSAGE selection END INTEGERPROBLEM sequence

WHILEDO structure Used when we do not know exactly how many times to carry out the a process Condition is tested first before the block of statements are executed will continue to repeat a group of statements while a condition remains true. When the condition becomes false, the loop is exited Block of statements are executed 0 or many times

WHILEDO Structure start off by first testing the condition at the beginning of the loop a variable will need to be initialised prior to this test. In many programming languages, if you don’t provide an initial value for a variable, the variable value is unknown or garbage. Since the loop will only terminates when the WHILE condition is false, some process must be set up within the statement block which will EVENTUALLY CHANGE the condition to becomes false. Failure to do so results in an endless loop

WHILEDO structure General structure format Condition expression PROCESSES WHILE continue = true A PROCESS *

WHILEDO structure : Example Everyday, a weather station receives a number of temperatures expressed in degrees Fahrenheit. A program is to be written which will accept each Fahrenheit temperature, convert it to celsius and display both temperatures on the screen. After all temperatures have been processed, the word “all temperatures processed” are to be displayed on the screen

Solution Algorithm: Example continue = ‘Y’ WHILE continue = ‘Y’ READ fahrenheit CALCULATE Celcius Celsius = (fahrenheit – 32) * 0.5555 DISPLAY fahrenheit, celsius READ continue Display “All temperatures processed” A variable named ‘continue’ must be initialized These statements will be repeated until continue is not = Y This statement will be executed after continue value is not Y

WHILEDO : Structure Chart TEMPERATURE CONVERSION continue =‘Y’ PROCESS TEMPERATURES DISPLAY “All temperatures processed” WHILE continue = ‘Y’ Repeated steps PROCESS A TEMPERATURE * READ fahrenheit celsius= (fahrenheit – 32) * 0.5555 DISPLAY fahrenheit, celsius READ continue

WHILEDO : pseudocode BEGIN TEMPERATURECONVERSION sequence continue = ‘Y’; BEGIN PROCESSTEMPERATURES iteration WHILE continue = ‘Y’ BEGIN PROCESSATEMPERATURE sequence READ fahrenheit; celsius = (fahrenheit – 32) * 0.555; WRITE fahrenheit, celsius; READ continue ; END PROCESSATEMPERATURE sequence ENDWHILE END PROCESSTEMPERATURES iteration WRITE “All temperatures processed”; END TEMPERATURECONVERSION sequence

DOWHILE structure Same as WHILEDO structure BUT Condition is tested after the block of statements are executed once. Block of statements are executed 1 or many times.

DOWHILE structure General structure format Condition expression PROCESSES DOWHILE continue = true A PROCESS *

DOWHILE structure : Example Everyday, a weather station receives a number of temperatures expressed in degrees Fahrenheit. A program is to be written which will accept each Fahrenheit temperature, convert it to celsius and display both temperatures on the screen. After all temperatures have been processed, the word “all temperatures processed” are to be displayed on the screen

Solution Algorithm: Example These statements will be executed and then repeated until continue is not = Y DO READ fahrenheit CALCULATE Celsius = (fahrenheit – 32) * 0.5555 DISPLAY fahrenheit, celsius READ continue WHILE continue= ‘Y’ DISPLAY “All temperatures processed”

DOWHILE : structured chart TEMPERATURE CONVERSION PROCESS TEMPERATURES DISPLAY “All temperatures processed” DOWHILE continue = ‘Y’ PROCESS A TEMPERATURE * READ fahrenheit celsius= (fahrenheit – 32) * 0.5555 DISPLAY fahrenheit, celsius READ reply

DOWHILE : Pseudocode BEGIN TEMPERATURE_CONVERSION sequence BEGIN PROCESS_TEMPERATURES iteration DO BEGIN PROCESS_A_TEMPERATURE sequence READ fahrenheit; celsius = (fahrenheit – 32) * 0.555; WRITE fahrenheit, celsius; READ continue; END PROCESS_A_TEMPERATURE sequence WHILE continue = ‘Y’; END PROCESSTEMPERATURES iteration WRITE “All temperatures processed”; END TEMPERATURE_CONVERSION sequence

Class Exercise 1 Class Exercise 2 Write the algorithm of a program which will compute and display sum of all odd numbers from 1 to 99 - 1,3,5,7,9…….99. Class Exercise 2 A manager of a cattle ranch is looking for the great sheep. The first input indicates how many ‘weight of sheep’ records to follow. Records , each containing the sheep number, age in years and weight in kilogram, follow the first input record. All weight must be validated so that the value is more than zero. The program should be able to find the average weight, the detail of the lightest and the heaviest sheep. Write down the algorithm.

Solution for Exercise 2 totalweight = 0, lightest=1000, heaviest=0 READ noofsheep FOR count = 1 to noofsheep 3.1 Read sheepno, age 3.2 DO 3.2.1 Read weight 3.2.2 IF weight <= 0 THEN Display “Invalid weight. Reenter weight” WHILE weight <= 0 3.3 totalweight = totalweight + weight 3.4 If weight < lightest l_sheepno = sheepno, l_age=age, lightest = weight 3.5 If weight > heaviest h_sheepno = sheepno, h_age = age, heaviest =weight avgweight = totalweight/noofsheep Display avgweight Display l_sheepno, l_age, lightest Display h_sheepno, h_age, heaviest