J. Michael Moore Other Control Structures CSCE 110 Influenced by material developed by James Tam & Jennifer Welch.

Slides:



Advertisements
Similar presentations
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
Advertisements

James Tam Repetition In Pascal In this section of notes you will learn how to have a section of code repeated without duplicating the code.
James Tam Making Decisions In Python In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
James Tam Repetition In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Computer Science 1620 Loops.
J. Michael Moore Structured Programming CPSC 110 Drawn from James Tam's material.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
J. Michael Moore Other Control Structures CSCE 110 Influenced by material developed by James Tam & Jennifer Welch.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
J. Michael Moore Structured Programming CSCE 110 Drawn from James Tam's material.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate your code.
Programming: Part II In this section of notes you will learn more advanced programming concepts such as branching and repetition as well as how to work.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Making Decisions In Python
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Program Errors and Debugging Week 10, Thursday Lab.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
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.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Pascal Programming Iteration (looping) Carl Smith National Certificate Unit 4.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
James Tam Making Decisions In Python In this section of notes you will learn how to have your programs choose between alternative courses of action.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Loops Brent M. Dingle Texas A&M University Chapter 7 – part C (and some from Mastering Turbo Pascal 5.5, 3 rd Edition by Tom Swan)
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.
REPETITION CONTROL STRUCTURE
Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code. Repetition in Pascal:
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
( Iteration / Repetition / Looping )
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 6: Repetition Statements
Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Computer Science 1 For..do loop Dry Run Take notes on the For loop
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

J. Michael Moore Other Control Structures CSCE 110 Influenced by material developed by James Tam & Jennifer Welch

J. Michael Moore Revisiting Selection (Decision-Making) In Pascal Selection / branching constructs (mechanisms) in Pascal If-then If-then-else If, else-if Case-of

J. Michael Moore Case Statements An alternative to the if, else-if : at most only one of many conditions can be true, i.e. mutual exclusion Format: case (selector_expression) of i 1 : body; i 2 : body; : i n : body; else body; end; (* case *) The selector expression can be a variable constant calculation That evaluates to a: char integer boolean The body is a single statement (can be a compound statement)

J. Michael Moore Case Statement: Integer Example Example case (gpa) of 4: writeln(‘You got an A’); 3: writeln(‘You got a B’); 2: writeln(‘You got a C’); 1: writeln(‘You got a D’); 0: writeln(‘You got an F’); else writeln('GPA must be one of 4, 3, 2, 1 or 0'); end; (* case *)

J. Michael Moore Case Statement: Character Example Example case (letter) of 'A': writeln('GPA = 4'); 'B': writeln('GPA = 3'); 'C': writeln('GPA = 2'); 'D': writeln('GPA = 1'); 'F': writeln('GPA = 0'); else writeln('Letter grade must be one of an ''A'', ', '''B'', ''C'', ''D'' or ''F'''); end; (* case *)

J. Michael Moore Case Statement: Menu Example while (menuChoice<>'q') and (menuChoice<>'Q') do begin displayMenu; getMenuChoice(menuChoice); case (menuChoice) of 'f', 'F': begin getNumber(num); answer := factorial(num); outputAnswer(num, answer); end; 's', 'S': begin getNumber(num); answer := sqrt(num); outputAnswer(num, answer); end; end; (* case *) end What should menuChoice be initialized to? Any character except ‘q’ or ‘Q’

J. Michael Moore Recap: What Decision Making Constructs Are Available In Pascal/When To Use Them ConstructWhen To Use If-thenEvaluate a Boolean expression and execute some code (body) if it’s true If-then-elseEvaluate a Boolean expression and execute some code (first body) if it’s true, execute alternate code (second body) if it’s false Multiple if’sMultiple Boolean expressions need to be evaluated with the answer for each expression being independent of the answers for the others (non-exclusive). Separate code (bodies) can be executed for each expression. If, else-ifMultiple Boolean expressions need to be evaluated but zero or at most only one of them can be true (mutually exclusive). Zero bodies or exactly one body will execute. Case-ofSimilar to the ‘if, else-if’ but results in smaller (cleaner) programs but only works for specific situations (Boolean expressions that involve characters or integer values only).

J. Michael Moore Recap: When To Use Compound And Nested Decision Making Constructs ConstructWhen To Use Compound decision making More than one Boolean expression must be evaluated before some code (body) can execute. Nested decision making The outer Boolean expression must be true before the inner expression will even be evaluated.

J. Michael Moore Revisiting Loops - Basic Structure Of Loops 1)Initialize the control a)Control – typically a variable that determines whether or not the loop executes or not. 2)Testing the control against a condition 3)Executing the body of the loop 4)Update the value of the control

J. Michael Moore Types Of Loops 1.Pre-test loops Check the stopping condition before executing the body of the loop. The loop executes zero or more times. Pascal implementation: while-do, for 2.Post-test loops Check the stopping condition after executing the body of the loop. The loop executes one or more times. Pascal implementation: repeat-until

J. Michael Moore Pre-Test Loops 1.Initialize loop control 2.Check if the stopping condition has been met a.If it’s been met then the loop ends b.If it hasn’t been met then proceed to the next step 3.Execute the body of the loop (the part to be repeated) 4.Update the loop control 5.Go to step 2 Initialize loop control Execute body Conditio n met? Update control After the loop (done looping) No Yes

J. Michael Moore Pre-Test Loop: For Typically used when it is known in advance how many times that the loop will execute (counting loops). Loop executes until the loop control would go past the stopping condition. Format (counting up): for initialize control to final value do body Format (counting down): for initialize control downto final value do body Note: For loops are only supposed to count up (‘to’) or down (‘downto’) by one. If the program must go up or down by other multiples then use a while-do loop instead. NEVER modify the loop control of a Pascal for loop in the body of the loop!

J. Michael Moore First For Loop Example Example one: begin var i : integer; var total : integer; total := 0; for i := 1 to 5 do begin total := total + i; writeln('i=', i, ‘ total=', total); end; (* for *) end.

J. Michael Moore Example one: begin var i : integer; var total : integer; total := 0; for i := 1 to 5 do begin total := total + i; writeln('i=', i, ‘ total=', total); end; (* for *) end. First For Loop Example 1) Initialize control i := 1 3) Update control to 2) Test condition 4) Execute body to 5

J. Michael Moore Second For Loop Example Example two begin var i : integer; var total : integer; total := 0; for i := 5 downto 1 do begin total := total + i; writeln('i=', i, ' total=',total); end; (* for *) end.

J. Michael Moore Post-Test Loops 1.Initialize loop control (sometimes not needed because initialization occurs when the control is updated) 2.Execute the body of the loop (the part to be repeated) 3.Update the loop control 4.Check if the stopping condition has been met a.If it’s been met then the loop ends b.If it hasn’t been met then return to step 2. Initialize loop control Execute body Update control No Conditio n met? After the loop (done looping) Yes

J. Michael Moore Post Test Loops: Repeat-Until Can be used instead of a while-do loop if you need the loop to execute the loop at least once. (Note: A while-loop can also be modified so that it is guaranteed to execute at least once by initializing the loop control to a value that will result in a true evaluation of the Boolean expression). Loop executes while some Boolean expression is false, it stops when it’s true. Format: repeat body until (Boolean expression); Unlike the while loop, the repeat-until loop can have multiple statements in its body without using a compound statement.

J. Michael Moore Repeat-Until: An Example (2) program repeatUntil (output); begin var i : integer; i:= 1; repeat begin writeln('i = ', i); i := i + 1; end; (* loop *) until (i > 5); end.

J. Michael Moore Repeat-Until: An Example (2) program repeatUntil (output); begin var i : integer; i:= 1; repeat begin writeln('i = ', i); i := i + 1; end; (* loop *) until (i > 5); end. 2) Execute body 3) Update control 4) Test condition 1) Initialize control

J. Michael Moore Solving A Problem Using Loops Problem: Write a program that will execute a game: The program will randomly generate a number between one and ten. The player will be prompted to enter their guess. The program will continue the game until the player indicates that they no longer want to continue.

J. Michael Moore Repeat-Until: An Example var guess : integer; var answer : integer; var choice : char; repeat answer := random(10) + 1; write('Enter your guess: '); readln(guess); if (guess = answer) then writeln('You guessed correctly!') else writeln('You guessed incorrectly'); write('Number was ', answer) writeln( ', your guess was ', guess); write('Play again?'); writeln('Enter “n” to quit or anything else to continue'); write('Choice: '); readln(choice); writeln; until (choice = 'N') OR (choice = 'n');

J. Michael Moore repeat displayMenu; getMenuChoice(menuChoice); case (menuChoice) of 'f', 'F': begin getNumber(num); answer := factorial(num); outputAnswer(num, answer, 'factorial'); end; 's', 'S': begin getNumber(num); answer := sqrt(num); outputAnswer(num, answer, 'square root'); end; end (* case *) until (menuChoice='q') or (menuChoice='Q') Repeat-Until: Menu Example What should menuChoice be initialized to? We don’t have to Initialize it

J. Michael Moore Recap: What Looping Constructs Are Available In Pascal/When To Use Them ConstructWhen To Use Pre-test loopsYou want the stopping condition to be checked before the loop body is executed (typically used when you want a loop to execute zero or more times). While-doThe most powerful looping construct: you can write a ‘while-do’ loop to mimic the behavior of any other type of loop. In general it should be used when you want a pre-test loop which can be used for most any arbitrary stopping condition e.g., execute the loop as long as the user doesn’t enter a negative number. ForA ‘counting loop’: You want a simple loop to count up or down a certain number of times. Post-test: Repeat-until You want to execute the body of the loop before checking the stopping condition (typically used to ensure that the body of the loop will execute at least once).

J. Michael Moore Nested Loops One loop executes inside of another loop(s). Example structure: Outer loop (runs n times) Inner loop (runs m times) Body of inner loop (runs n x m times) Example program var i : integer; var j : integer; for i := 1 to 2 do for j := 1 to 3 do writeln('i=', i, ' j=', j); writeln('All done!');

J. Michael Moore Testing Loops Make sure that the loop executes the proper number of times. Test conditions: 1)Loop does not run 2)Loop runs exactly once 3)Loop runs exactly ‘n’ times

J. Michael Moore Testing Loops: An Example program testLoops (input, output); begin var sum : integer; var i : integer; var last : integer; sum := 0; i := 1; write ('Enter the last number in the sequence to sum : '); readln (last); while (i <= last) do begin sum := sum + i; writeln('i=', i); i := i + 1; end; writeln ('sum=', sum); end.