Chapter 3 More Flow Of Control.

Slides:



Advertisements
Similar presentations
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
Advertisements

True or false A variable of type char can hold the value 301. ( F )
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.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
CSC 200 Lecture 4 Matt Kayala 1/30/06. Learning Objectives Boolean Expressions –Building, Evaluating & Precedence Rules Branching Mechanisms –if-else.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
Chapter 4 Making Decisions
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 4 Making.
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.
Today’s Lecture  Boolean Expressions  Building, Evaluating & Precedence Rules  Branching Mechanisms  if-else  switch  Nesting if-else  Loops  While,
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
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.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
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.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. CIS_IS20_CSLO 1. Explain computer programming concepts CSLO1.6. Explain the purpose of general.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
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.
A First Book of C++ Chapter 5 Repetition.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 3 Control Statements
REPETITION CONTROL STRUCTURE
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 4B More Repetition Richard Gesick
Chapter 7 Additional Control Structures
Chapter 3 Even More Flow of Control 1
Control Statements Paritosh Srivastava.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Chapter 3 More Flow Of Control

Boolean Expression < <= > >= == != ! && || Expression that yields bool result Include: 6 Relational Operators < <= > >= == != 3 Logical Operators ! && ||

Boolean Expression (examples) taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is between 21 and 60 age is 21 or 22

Boolean Expression (examples) (taxRate > .25) && (income < 20000) (temperature <= 75) || (humidity < .70) (age >= 21) && (age <= 60) (age == 21) || (age == 22)

Precedence Chart ++, --, !, - (unary minus), + (unary plus) *, /, % + (addition), - (subtraction) <<, >> <, <=, >, >= ==, != && || = Highest Lowest

“Short-Circuit” Evaluation C++ uses short circuit evaluation of logical expressions This means logical expressions are evaluated left to right and evaluation stops as soon as the final truth value can be determined

Short-Circuit Example (age > 50) && (height > 60) When age is less than 50, evaluation can stop now because result of && is only true when both sides are true. It is already determined that the entire expression will be false. (age > 50) || (height > 60) When age is greater than 50, evaluation can stop now because result of is true if one side is true. It is already determined that the entire expression will be true. However, when age is less than 50, evaluation must continue because result of the entire expression has not been determined.

Short-Circuit Benefits One Boolean expression can be placed first to “guard” a potentially unsafe operation in a second Boolean expression Time is saved in evaluation of complex expressions using operators || and && Optimize code by placing most telling condition first.

Boolean evaluation on Arithmetic Expressions All yields either 1 or 0. Thus, !5 = 0, !(-5) = 0, !0 = 1 In C++, these values (0 and 1) can be used arithmetically, there is no difference between a 1 derived from !5 and 1 derived from 3 - 2.

Enumeration Types Is a type whose values are defined by a list of constants type int. enum Fruits {ORANGE, GRAPE, APPLE};

Enumeration Types (Notes) Sets must be finite Members are called enumerators- unique identifier Members are constants of type int with default value starting from 0 Can initialize values to other than 0: enum sizes {small, medium = 10, large = 20} Values need not be unique enum economy {recession = -1, depression = -2, growth = 1} Positive or negative numbers can be associated Can declare type and variable of that type at same time. enum economy {recession = -1, depression = -2, growth = 1} bear ;

Enumeration Types (Notes) Can use in switch as case label->integral constants Can compare 2 different enumerated type variables by casting to int Ex: int(jan_len) < int(false) Cannot read or write directly because the compiler doesn’t know the rules for this type. Why use enumerated types? Used for program clarity Compiler will do type checking - prevent mixing types Use 6 for Saturday and 6 for Date allows incorrect comparison.

Multiway Branches When there are more than 2 options to consider Used in: Nested if statements Multiway if-else statements switch statements

Nested if Statements An if statement nested inside another if statement Indent each statement. Use braces for clarity.

Dangling else in nested if statements Compiler matches else with most recent if: if (fuel-gauge_reading < 0.75) if (fuel-gauge_reading <0.25) cout<<”Fuel very low. Caution!\n”; else cout<<”Fuel over 3/4. Don’t stop now!\n”; If fuel is 0.8, there is no ouput. If fuel is 0.5, output is: Fuel over 3/4. Don’t stop now! Need to force compiler to match if-else correctly.

Dangling else in nested if statements (Solutions) Use braces to set off inner else if (fuel-gauge_reading < 0.75) { if (fuel-gauge_reading <0.25) cout<<”Fuel very low. Caution!\n”; } else cout <<”Fuel over 3/4. Don’t stop now!\n”; Use null statement for else else;

Multiway if-else Statements Is another form of nested if EXACTLY 1 of these statements will be executed. Syntax if ( Expression1 ) Statement1 else if ( Expression2 ) Statement2 . else if ( ExpressionN ) StatementN else Statement N+1

Multiway if-else Statements (Notes) Order is important. More efficient to put most probable result first. if (grade<70) cout<<’F’; else if ( grade>=70) cout<<‘C’; else if (grade>=80) cout<<‘B’; else cout<<‘A’; If grade is 82: C if (grade>=90) cout<<‘A’; else if (grade>=80) cout<<‘B’; else if (grade>=70) cout<<‘C’ else cout<<‘F’; If grade is 82: B

switch Statement Replaces the multiple alternative if statement Work with exact value only Computer evaluates value of grade and finds case label that matches that value. Value must be of integral type (enum, int, char, bool) Will not work on string, double or float. For efficiency, put most likely options first.

switch Statement (Syntax) switch ( Integral Expression ) { case Constant1 : Statement(s); // optional case Constant2 : . default : // optional }

switch Statement (break use) Switch statement does action after case statement until it reaches break. No {} needed for multiple statements. If no break occurs in that case, execution will “fall through” and do the next case, etc. until a break is reached. break statement returns control to next line outside switch statement.

switch Statement (default case) default can be used for values not represented by any case label. Only 1 default statement in a switch.

switch Statement (Example) char finalGrade; …. // get value for finalGrade switch ( finalGrade ) { case ‘A’ : cout << “Excellence!” << endl ; break ; case ‘B’ : cout << “Good!” << endl ; case ‘C’ : cout << “Pass!” << endl ; case ‘D’ : cout << “Sorry!” << endl ; case ‘F’ : cout << “You failed!” << endl ; default : cout << “It is not a grade! “ << endl ; break ; // not needed } finalGrade Output A Excellence! B Good! C Pass! D Sorry! You failed! F You failed! Anything else It is not a grade

break and exit break exits that particular control statement. Used to break out of loops, switches. exit exits the program and can return a value EXIT_SUCCESS and EXIT_FAILURE (defined in stdlib.h) to the invoking process. (Not recommend to use in this class)

Blocks A compound statement which contains local variables – denoted by braces {}. Scope: Visibility: Local variables can only be seen within the block. Other functions and the main program do not know they exist. Therefore, there is no conflict and other functions or programs can use variables of the same name. Viability: Local variables are created and destroyed within the block. Saves on memory. Block allows use of global variables and local variables. local variable: visibility and viability is within block only! Blocks can be nested inside other blocks.

Blocks (Example) float price 50.0; int num; … // Get num { float subtotal; subtotal = price * num; } cout << “The total for “ << num << “ is “ << subtotal; Syntax error! float price 50.0; int num; … // Get num { float subtotal; subtotal = price * num; cout << “The total for “ << num << “ is “ << subtotal; } Legal

Chapter 2 Review Open Chapter 2 slides Review While and Do-While Loops Review Increment and Decrement

FOR Loop Used when Syntax: Example: for (initialize; test condition; update) { … //loop body } Example: int sum = 0; for (int i=1; i<=10; i++) //i is a local variable sum = sum + i;

FOR Loop (Notes) Can use commas to do more than 1 action in any part for(i=1,sum=0;i<10; sum+=i++); //complete loop-no body needed Can eliminate any part of loop for (; Test; Action)- start missing - allows the same loop to be used for different starting points as long as initialized before used. (allows flexibility) Ex: cin>>i; for(; i<10; i++); Increment in loop rather than in loop body for (i=0; i<10; i++) Omit everything for (;;) // (infinite loop) { //body of loop if (I % 5 == 0) break; // use break to exit loop } Accidentally eliminating loop body by placing a semicolon at the end for (i=0; i<10; i++); cout << i << endl; // Only 10 in the output

Designing Loops What kind of loop to use What do we need to know? Must iterate at least once? Do-While Must iterate at least never? While Numerically increases/decreases by a set amount? While Know exactly how many times to execute. For Execution depends on events? While What do we need to know? What is the process being repeated? THE BODY How must the process be initialized and updated? INITIALIZATION. What is the ending condition for our loop? EXIT CONDITIONS

Loop For Sums and Products Used when a value (accumulator) is to be increased/decreased by the new value. Notes: Accumulator for a sum must be initialized to 0. Accumulator for a product must be initialized to nonzero.

Loop Ending List headed by size Count controlled loop Input list known beforehand Count controlled loop number of iterations known before loops begin Ask before iteration Used for menus and for repeated processing Using SENTINELS A special value which has no valid meaning to the program and is entered by the user to terminate a loop Running out of input Cannot read any more input from a file Using boolean flag Raise flag when something happened

Nest Loops A loop within a loop. Example: for (int i=0; i<3; i++) { cout << “Row# “ << i << “: ”; for (int j=0; j<5; j++) cout << j << “ ”; cout << endl; } Row# 0: 0 1 2 3 4 Row# 1: 0 1 2 3 4 Row# 2: 0 1 2 3 4

Debugging Loops Set breakpoint at the beginning of the loop. Check the LCV value when this breakpoint is hit. Set breakpoint at the first line of the loop body. Check if the execution stops at this breakpoint. Repeat 2 above steps would help to find problem with the loops