1 Control Structures The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4) st. line.

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
Chapter 5: Control Structures II (Repetition)
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Flow of Control Part 1: Selection
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
C++ An Introduction to Computing, 3rd ed. 1 Repetition Chapter 7.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Calvin College Controlling Behavior The if, switch and for Statements.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
COMP Loop Statements Yi Hong May 21, 2015.
Control Structures 1 The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Controlling Behavior The if and for Statements. Function Behavior The behavior of a function is determined by the statements within the function. Statements.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Loop Design What goes into coding a loop. Considerations for Loop Design ● There are basically two kinds of loops: ● Those that form some accumulated.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
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.
Chapter 3 Selection Statements
Controlling Behavior The if and for Statements.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Ch 7: JavaScript Control Statements I.
Alternate Version of STARTING OUT WITH C++ 4th Edition
3 Control Statements:.
Computing Fundamentals
Let’s all Repeat Together
2.6 The if/else Selection Structure
Controlling Behavior The if and for Statements.
Presentation transcript:

1 Control Structures The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4) st. line

Basic Kinds of Control Statements that simply execute in sequence. Statements that select one of several alternatives. Statements that repeat another statement. 2 The behavior of main() (and other functions) is determined by the statements within it. Statements fall into one of three categories called control structures: EVERY PROGRAM CAN BE WRITTEN USING THESE 3 CONTROL STRUCTURES. See flowcharts in §5.4 & 5.5 List seq, sel, rep

Sequential execution The design of computers in which program instructions are stored in memory along with the data processed by the program is known as the architecture. A special register, called the instruction counter (IC), stores the address of the memory location where the next instruction to be executed is found. It is initialized with the address of the first instruction and execution proceeds as follows: 3 Fetch the instruction whose address is in the IC Decode it to find the opcode and the operands Execute the operation IC++ (unless the IC is changed in some other way) Named after mathematician /physicist John von Neumann (see Ch.1, p. 8) von Neumann Diagram: IC, memory, CPU

The last step (IC++) indicates that the default manner of executing statements is sequential. In C++, a list of statements enclosed in curly braces { Statement 1 Statement 2... Statement N } 4 is known as a compound statement (or block). It is a statement that produces sequential execution of the statements enclosed by the { and }. Note: A compound statement is a single statement and can thus be used any place a statement is needed.  STYLE TIP Indent& align the statements they enclose. Nested blocks; Pascal: BEGIN…END

A variable declared within a block is called a local variable. It exists (has memory allocated to it) only from its declaration to the end of the block. We say that its scope extends from its declaration to the end of the block. For example, in the code... cin >> item; while (item != -999) { int i = 0;... cin >> item; i++; } cout << "Value of i = " << i; the last line won't compile because local variable i is out of scope. The "lifetime" of i ends at the }. 5 Scope This is one of several scope rules. Others will be described later. Move int I = 0-; Will have blocks inside blocks

Selective Execution (§ 5.4) In contrast to sequential execution, there are situations in which a problem's solution requires that a statement be executed selectively, based on a condition (a boolean expression): The C++ if statement is a statement that causes selective execution, allowing a program to choose exactly one of two statements and execute it. if (Condition) Statement 1 else Statement 2 optional 6 Note again: An if statement is a single state- ment, even if it extends over many lines. Statements can be blocks

The Simple if The C++ if statement has several different forms. The first form has no else or Statement 2, and is called the simple if: if (Condition) Statement If Condition is true, Statement is executed; otherwise Statement is skipped. Condition Statement T F 7 Proceed or bypass Some programmers use else;

Examples: 8 // Display date in mm/dd/yyyy format if (month < 10) cout << 0; cout << month << '/'; if (day < 10) cout << 0; cout << day << '/' << year << endl; // if value is negative, make it positive if (value < 0) value = -value; Efficient alternative to abs(value); endl

9 // Stop program if a is 0 // (in quadratic equation solver) if (a == 0) { cerr << "*** Coefficient of x^2 cannot be 0 ***\n"; exit(1); // Stop execution & return 1 to OS } Examples showing Statement can be a compound statement: // if a < b, interchange a and b (integers) if (a < b) { int temp = a; a = b; b = temp; } cout is buffered; cerr is not. Common Alternative Style: if (a < b){ int temp = a; a = b; b = temp; } Lab 4: Exer. 4.3 Visual aligns either format; User-friendly assert

The Two-Branch if In the second form of if, the else and Statement 2 are present: if (Condition) Statement 1 else Statement 2 If Condition is true, Statement 1 is executed and Statement 2 is skipped; otherwise Statement 1 is skipped and Statement 2 is executed. Condition Statement 1 T F Statement 2 10 STYLE TIP Align if and else and indent & align the statements in each part.

Example: 11 // Continuation of quadratic equation solver // Legal quadratic equation, so find roots (if any) double discrim = b*b - 4*a*c; if (discrim >= 0) { double root1 = (-b + sqrt(discrim)) / (2*a), root2 = (-b - sqrt(discrim)) / (2*a); cout << "Solutions: " << root1 << ", " << root2 << endl; } else cout << "No real roots\n"; Example:

The Multi-branch if The final form of the if statement is: 12 if (Cond 1 ) Stmt 1 else if (Cond 2 ) Stmt 2... else if (Cond N ) Stmt N else Stmt N+1 of the statements will be selected and executed, namely, the one corresponding to the first that is true. Exactly one of the statements Stmt i will be selected and executed, namely, the one corresponding to the first Cond i that is true. STYLE TIP Align if, else if s, and else and indent & align the statements in each part.

The intent is to implement a multi-alternative selection structure of the following form, where exactly one of the alternatives is selected and executed: 13 Stmt 1 Stmt 2 Stmt N Stmt N+1 Stmt 3 F T F T F T F T Click switch

Actually, however, it implements a "waterfall" selection structure of the following form: Cond 1 Stmt 1 T F Stmt 2 Cond 2 TF Stmt N Cond N TF Stmt N

15 if (Cond 1 ) Stmt 1 else if (Cond 2 ) Stmt 2 else if (Cond 3 ) Stmt 3... else if (Cond N ) Stmt N else Stmt N+1 This form is surely more difficult to type with all its staggered indents. It also does not display as clearly the different alternatives and that exactly one of them will be selected. And it is treated by the compiler as a sequence of nested ifs in which each else clause (except the last) is another if-else statement: move if up

If Cond 1 is true, Stmt 1 is executed and the remaining statements are skipped; otherwise, control moves to Cond 2 ; if Cond 2 is true, Stmt 2 is executed and the remaining statements are skipped; otherwise, control goes to the next condition... if Cond N is true, Stmt N is executed and Stmt N+1 is skipped; otherwise, Stmt N+1 is executed. 16 if (Cond 1 ) Stmt 1 else if (Cond 2 ) Stmt 2... else if (Cond N ) Stmt N else Stmt N+1

17 if (score > 100 || score < 0) cerr << "Invalid score!\n"; else if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; Example: Assigning letter grades: Using the nested-if form:

18... or the preferred if-else-if form: if (score > 100 || score < 0) cerr << "Invalid score!\n"; else if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; Here's an example of program efficiency — not doing unnecessary computations. Note the simple conditions; we don't need (score = 90) (score = 80) (score = 70) (score = 60) Do you understand why? menu processing - Lab 4

19 (§ 5.5) Repetitive Execution (§ 5.5) There are three parts to the repetition mechanism: Initialization Repeated execution Termination Now we look at one repetition statement in C++, the for statement: Finally, there are situations where solving a problem requires that a statement be repeated, with the repetition being controlled by a condition. for, while, do-while

20 for (InitializerExpr; LoopCondition; ModifierExpr) Statement where Statement can be either a single statement, or a compound statement. Does the initialization Causes termination — think "while this is true, do the following" Usually modifies something each time through the loop Need not all be on one line And again, note: A for statement is a single statement, even if it extends over many lines. Compared to for statements in other programming languages, C++'s has an unusual syntax. for (int I = 1; I <= 10; i++)

The for Loop for (InitializerExpr; LoopCondition; ModifierExpr) Statement Statement will be executed so long as LoopCondition is true. InitializerExpr LoopCondition Statement ModifierExpr F T Statement is often called the body of the loop. 21 STYLE TIP Indent and align the statements in the body of the loop.

22 for (InitializerExpr; LoopCondition; ModifierExpr) Statement Each execution of LoopCondition Statement ModifierExpr is called one repetition or iteration of the loop. InitializerExpr LoopCondition Statement ModifierExpr F T true false

for (InitializerExpr; LoopCondition; ModifierExpr) Statement When LoopCondition becomes false,control proceeds to the statement following the loop. InitializerExpr LoopCondition Statement ModifierExpr F T Note: if the LoopCondition is initially false, then the body of the loop will not be executed. For this reason this is called a pretest loop. 23

24 Counting The "" use of the for loop is to count: The "normal" use of the for loop is to count: int limit; cin >> limit; for (int count = 1; count <= limit; count++) { cout << count << endl; } Output (suppose limit = 5): limit is 0? What if limit is 1? How get 1, 3, 5,... ? 1 no output count += 2 Scope Rule Could omit { }; loop body contains a single statement Declare and initialize the loop- control variable Check if loop-control variable has gone through all its values Inc-/dec-rement loop-control variable InitializerExpr LoopCondition Statement ModifierExpr F T Scope: Need count after loop? Move initializer up

Nested Loops Loops can also be nested: 1*1 = 1 1*2 = 2 1*3 = 3 2*1 = 2 2*2 = 4 2*3 = 6 Output (suppose limit1 = 2, limit2 = 3): 25 for (int val1 = 1; val1 <= limit1; val1++) { for (int val2 = 1; val2 <= limit2; val2++) { cout << val1 << '*' << val2 << " = " << val1 * val2 << endl; } Could omit { } since each loop body contains a single statement Table output

Input Loops 26 There are two different types of input loops: 1.Counting approach: Ask for the number of inputs to be entered and use a for loop. —This method requires knowing in advance how many inputs there are. Example: The Nyhoffian method of assigning letter grades: Find the mean of the numeric scores. This is the B- cutoff. Halfway between the mean and 100% is the A- cutoff. Halfway betwe en the mean and 50% is the C- cutoff. 50% is the D- cutoff.

Example /* Program to display a grading scale (Nyhoffian) for a test. Input: A list of test scores Output: Letter grade cutoffs */ #include using namespace std; int main() { cout << "Program finds letter grade cutoffs for a test.\n\n"; // First find the average double score, sum = 0.0, average; int numScores = 0; 27

cout << "Enter number of scores: "; cin >> numScores; for (int count = 1; count <= numScores; count++) { cout << "Enter a score: "; cin >> score; sum += score; } if (numScores > 0) average = sum / numScores; else { cerr << "\n*** No scores! Stopping program ***\n"; exit(1); } // Compute and display letter grade cutoffs. cout << "\nA-: " << (100 + average) /2 << "%\n" << "B-: " << average << "%\n" << "C-: " << (average + 50) / 2 << "%\n" << "D-: " << 50 << "%\n"; } 28

Execution of our example program: Program finds letter grade cutoffs for a test. Enter number of scores: 5 Enter a score: 77 Enter a score: 88 Enter a score: 66 Enter a score: 77 Enter a score: 99 A-: 90.7% B-: 81.4% C-: 65.7% D-: 50% 29

The second kind of input loop: 2. Sentinel approach: Values are entered until the end of input is signaled by entering a sentinel (or flag) ― a value that signals the end of input. - A while loop is commonly used in many programming languages. -This method requires the availability of an appropriate sentinel value. 30 Second part of lab

The while Loop Pattern: while (Condition) Statement Condition T F Statement Statement can be either a single or a compound statement, but is almost always compound. Repetition continues so long as Condition is true. 31

Using while for an Input Loop Pattern: Prompt for first value Read value while (value != sentinel) { Process the value Prompt for another value Read value } 32 Need the first input value so it can be compared with sentinel Get the next value Condition T F Statement

Example /* Program to display a grading scale (Nyhoffian) for a test. Input: A list of test scores Output: Letter grade cutoffs */ #include using namespace std; int main() { cout << "Program finds letter grade cutoffs for a test.\n\n"; // First find the average double score, sum = 0.0, average; int numScores = 0; 33

cout << "Enter a test score (-1 to quit): "; cin >> score; while (score >= 0) { count++; sum += score; cout << "Enter another score (-1 to quit): "; cin >> score; } if (numScores > 0) average = sum / numScores; else { cerr << "\n*** No scores! Stopping program ***\n"; exit(1); } // Compute and display letter grade cutoffs. cout << "\nA-: " << (100 + average) /2 << "%\n" << "B-: " << average << "%\n" << "C-: " << (average + 50) / 2 << "%\n" << "D-: " << 50 << "%\n"; } 34 sentinel

Execution of our example program, but using the while-loop version : Program finds letter grade cutoffs for a test. Enter a test score (-1 to quit): 77 Enter another score (-1 to quit): 88 Enter another score (-1 to quit): 66 Enter another score (-1 to quit): 77 Enter another score (-1 to quit): 99 Enter another score (-1 to quit): -1 A-: 90.7% B-: 81.4% C-: 65.7% D-: 50% 35

Textbook: Chap. 1, pages 8-9 In other early computers, the instructions were stored outside the machine on punched cards or some other medium and were transferred into the machine one at a time for interpretation and execution. In 1945, Princeton mathematician John von Neumann wrote “First Draft of a Report on the EDVAC (Electronic Discrete Variable Automatic Computer)” computer in which he described a scheme that required program instructions to be stored internally before execution. This led to his being credited as the inventor of the stored-program concept. The architectural design he described is still known as the von Neumann architecture. The advantage of executing instructions from a computer’s memory rather than directly from a mechanical input device is that it eliminates time that the computer must spend waiting for instructions. Instructions can be processed more rapidly and more importantly, they can be modified by the computer itself while computations are taking place. The introduction of this scheme to computer architecture was crucial to the development of general- purpose computers.

Using while for an Input Loop while (value != sentinel) { Prompt for a value Read value Process the value } 37 Condition T F Statement