Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:

Similar documents
Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 3. More Flow of Control

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

C++ Programming: From Problem Analysis to Program Design, Third Edition

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

C Programming Basics

C++ Programming: From Problem Analysis to Program Design, Third Edition

CSI33 Data Structures

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

Introduction. C provides two styles of flow control:

Linear execution of statements. CISC 1600/1610 Computer Science I. Alternatives to linear execution. Linear execution of statements

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

INTRODUCTION TO COMPUTER SCIENCE - LAB

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Lecture 5 Tao Wang 1

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

LECTURE 5 Control Structures Part 2

REPETITION CONTROL STRUCTURE LOGO

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Chapter 4: Making Decisions

Chapter 4: Making Decisions

Programming for Engineers Iteration

Chapter 4: Control Structures I (Selection)

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Chapter 4 - Notes Control Structures I (Selection)

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

bool bool - either true or false

CSCI 1061U Programming Workshop 2. C++ Basics

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Lecture 3 Tao Wang 1

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

Announcements. HW0 is posted on schedule, due next Friday at 9pm (pretty easy)

Chapter 4. Flow of Control

Boolean Algebra Boolean Algebra

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Add Subtract Multiply Divide

Introduction to Computer Science Midterm 3 Fall, Points

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Flow Control. CSC215 Lecture

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CT 229 Java Syntax Continued

LECTURE 04 MAKING DECISIONS

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Announcements. Homework 0: using cin with 10/3 is NOT the same as (directly)

Chapter 5: Control Structures II (Repetition)

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

ECE 2400 Computer Systems Programming Fall 2018 Topic 1: Introduction to C

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Announcements. HW 0 due tonight (check that it compiles on CSE labs) (make sure you submit the code part)

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

Introduction to C Programming

CSCE 206: Structured Programming in C++

In this chapter you will learn:

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Decisions. Arizona State University 1

If Control Construct

SFU CMPT Topic: Control Statements

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Software Design & Programming I

Introduction to Programming

Computer Programming : C++

Introduction to Programming Using Java (98-388)

VARIABLES & ASSIGNMENTS

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

5. Control Statements

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

The Arithmetic Operators

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

To become familiar with array manipulation, searching, and sorting.

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Absolute C++ 6th Edition Savitch TEST BANK Full download at:

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Increment and the While. Class 15

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Decision Making in C

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

QUIZ: What value is stored in a after this

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Transcription:

Chapter 3

In this chapter, you will learn about: Using Boolean Expressions Multiway Branches More about C++ Loop Statements Designing Loops

Boolean Expressions Take the Value true or false Boolean Value is produced using Relational Operations: = =, <, >, <=, >= Boolean Operations &&,,! Boolean Variable (okay) Declaration bool okay // okay takes value true or false

Let s review evaluating Arithmetic Expressions Rule: PEMDAS (x + 1) * ( x + 3) Boolean Expression Evaluation Truth Tables and Precedence Rules Let s review Truth Tables for &&, and! Example:!( ( y < 3) ( y > 7) )!( false true )!( true ) false Assume y 8

When parenthesis are omitted from boolean expressions, computer groups items using rules known as Precedence Rules: Boolean & Arithmetic Operators Unary: +, -, ++, --, and! Binary: *, /, % Binary: +, - <, >, <=, >= ==,!= && Order Highest Precedence Perform! Operation first Perform relational operations next Perform relational operations next Perform && operations next Perform operations last

1. First Evaluate Operators with higher precedence 2. When Operators have equal Precedence: If Binary Operators Evaluate expression from left to right If Unary Operators Evaluate item from right to left

( x+1) > 2 (x + 1) < -3 is equivalent to: ( (x + 1) > 2 ) ( (x + 1) < -3 ) Why? Boolean & Arithmetic Operators Unary: +, -, ++, --, and! Highest Precedence Perform! Operation first Order Binary: *, /, % Binary: +, - <, >, <=, >= ==,!= && Perform relational operations next Perform relational operations next Perform && operations next Perform operations last

( x+1) > 2 (x + 1) < -3 is equivalent to: x + 1 > 2 x + 1 < -3 Why? What is the order of operation? Boolean & Arithmetic Operators Unary: +, -, ++, --, and! Highest Precedence Perform! Operation first Order Binary: *, /, % Binary: +, - <, >, <=, >= ==,!= && Perform relational operations next Perform relational operations next Perform && operations next Perform operations last

! If value of the leftmost sub-expression determines the final value of entire expression, the trailing expressions are not evaluated Example: ( x >= 0) && ( y > 1) false && ( y > 1) false Assume x -1 Check Truth Table for && Short Circuit Evaluation and Complete Evaluation give the same result

! " Consider C++ statement: if ( ( kids!= 0) && ( ( pieces/kids) >= 2 ) ) cout << Each child may have tow pieces!\n ; Assume kids 0 Complete Evaluation: if ( false && ( ( pieces/0) >= 2 ) ) Run-time error (divide by 0) Short Circuit Evaluation: if ( false && ( ( pieces/kids) >= 2 ) ) false Second sub-expression is not evaluated

#$%&#$ Variables of type bool take values true or false C++ also converts integers to Boolean values: A Non-zero number (e.g., -10, -1, 1, 4, 10..) is true Zero (0) is false Let s examine pitfalls associated with Boolean expressions

1. % if (!(time > limit) ) cout << CS23021 Lab Session\n ; else cout << End of CS23021 Lab Session\n ; Output: CS23021 Lab Session time 30 Assume limit 60 2. if (!time > limit ) cout << CS 23021 Lab Session\n ; else cout << End of CS 23021 Lab Session\n ; What s!time?!(true) false 0 Hence, if (0 > 60) false Output: End of CS23021 Lab Session Avoid using not (!) operator

#$ Type enum refers to a list of constants of type int Example Declaration: enum MonthLength {JAN_LENGTH = 31, FEB_LENGTH = 28 Default enum values: MAR_LENGTH = 31, APRIL_LENGTH = 30, MAY_LENGTH = 31, JUNE_LENGTH = 30}; Identifiers are assigned consecutive values starting with zero Value assigned to a trailing identifier is one more than previous value Examples. enum Direction { NORTH, SOUTH, EAST, WEST }; enum myenum { ONE =17, TWO, THREE, FOUR = -3, FIVE };

What is the output of the code segment? enum Direction {N, S, E, W}; cout << W<< << E << << S << <<N << endl; Output: 3 2 1 0 What is the output of the code segment? enum Direction {N, S, E, W}; cout << << Direction::E << << Direction::S << <<Direction::N << endl; Output: 2 1 0

What is the output of the code segment? enum Direction {N = 5, S = 7, E = 1, W}; cout << W << << E << << S << <<N << endl; Output: 2 1 7 5 What is the output of the code segment? enum Direction {N = 5, S = 7, E = 1, W}; cout << Direction::W << << Direction::E << << Direction::S << <<N << endl; Output: 2 1 7 5

' What is the output of the code segment? int x =2; cout << Start\n ; if (x <= 3) if (x!=0) cout << Hello from the second if.\n ; else cout << Hello from the else.\n ; cout << End\n ; cout << Start again\n ; if (x > 3) if (x!=0) cout << Hello from the second if.\n ; else cout << Hello from the else.\n ; cout << End again\n ; output Hello from the second if. End Start again End again Compiler pairs the else with the nearest previous if

Output ' Braces tell the compiler how to group statements Always Use braces to take control of ifelse constructs Hello from the second if End Start again Hello from the else End again int x =2; cout << Start\n ; if (x <= 3) { if (x!=0) cout << Hello from the second if.\n ; } else { cout << Hello from the else.\n ; } cout << End\n ; cout << Start again\n ; if (x > 3) { if (x!=0) cout << Hello from the second if.\n ; } else { cout << Hello from the else.\n ; } cout << End again\n ;

$! ( ) An if-else-statement includes one or more blocks of ifelse-statements if (guess > number) cout << Higher. ; else if (guess < number) cout << Lower. ; else if (guess == number) cout << Correct Number ; if (guess > number) cout << Higher. ; else if (guess < number) cout << Lower. ; else cout << Correct Number ; Use the if-else-if construct for nested if constructs

$ ) $ if (Boolean _Expression_1) Statement_1 else if (Boolean Expression_2) Statement-2 else if (Boolean Expression_n) Statement_n else Default_statements

$ ) What is the output of the code segment? int x = 200; cout << Start\n ; if ( x < 100 ) cout << First Output. \n ; else if (x > 10) cout << Second Output.\n ; else cout << Third Output.\n ; cout << Start\n ; Output: Second Output. Start

$ ) What is the output of the code segment? int x = SOME_CONSTANT; cout << Start\n ; if ( x < 100 ) cout << First Output. \n ; else if (x > 100) cout << second Output.\n ; else cout << x << endl; cout << End\n ; Assume that code does not output First Output or Second Output Output 100 End

Switch Statement Example 1 What is the output of the code segment? switch (grade) { case A : cout << Excellent. You need to take the final.\n ; break; case B : cout << Very good. ; cout << You midterm grade is now << grade << endl; break; case C : cout << Passing.\n ; break; case D : case E : cout << Not good. Go study.\n break; default: cout << That is not a possible grade.\n } Assume: 1. char grade; A Excellent. You need to take the final 2. char grade; D Not good. Go study

Switch Statement Example 2 What is the output of the code segment? int first_choice = 1; switch (first_choice + 1) { case 1: cout << Roast beef \n ; break; case 2: cout << Roast worms\n ; break; case 3: cout << Chocolate ice cream\n ; break; case 4: cout << Onion ice cream\n ; break; default: cout << Bon appetit! \n ; } What if 1. int first_choice; 3 Onion ice cream 2. int first_choice; 6 Bon appetit!

Switch Statement Syntax switch (Controlling expression) { case Constant_1: statement_sequence_1 break; case Constant_2: statement_sequence_2 break; } case Constant_n: statement_sequence_n break; default: default_statement_sequence

Switch Statement Controlling Expression The switch controlling expression must return one of the value Types: A Character An Integer An enum constant A bool The returned value is subsequently compared with each case value. If there is a match the corresponding case statement is executed

! * The break statement ends execution of the switch-statement If the break statement is omitted, the code for the trailing case(s) will be executed! Use this technique if you wish to execute multiple case labels for one section of code

! + The default statement is executed if no case label has a constant that matches the controlling expression If the default statement is missing, nothing happens when the switch statement is executed Always include a default section in a switch statement

! Switch and if-else-statements allow the use of multiple statements in a branch Multiple statements in a branch can make the switch or if-else-statement difficult to read Use function calls instead of multiple statements Function calls are easier to read

* %)* Each branch of a switch or if-else statement is a separate sub-task If the action of a branch is too simple to warrant a function call, use multiple statements between braces A block is a section of code enclosed by braces Variables declared within a block, are local to the block or have the block as their scope. Variable names declared in the block can be reused outside the block (not a good practice though)

*,% When you declare a single identifier as a variable in two distinct blocks, where one block is within the other, you end up with two different variables with the same name (identifier) One of the variables exists only within the inner block and cannot be accessed outside the inner block The other variable exists only in the outer block and cannot be accessed in the inner block

,% What is the output of the code segment int main( ) { int x = 1; cout << x << endl; { cout << x << endl; int x = 4; cout << x << endl; } cout << x << endl; return 0; }

,% What is the output of the code segment int main( ) { int x = 1; cout << x << endl; { cout << x << endl; int x = 4; cout << x << endl; } cout << x << endl; return 0; } // Declares Local integer variable in block1 // Declares Local integer variable in second block Output 1 1 4 1

- Statement number++; Increments value stored in variable number by 1 int number = 41; number++; cout << number; Outputs 42

- Expression 2 * (number++); First return the value stored in variable number to be multiplied by 2; then increment value stored in variable number by 1 int number = 4; int value_produced = 2 * (number++); cout << value_produced; cout << number << endl; Outputs 8 5

-..%%.. ++number; First increment by 1 the value stored in variable number then use the incremented value in the expression number++; First return the current value stored in variable number to be used in the expression; then increment the current value in variable number by 1

..%%.. int number = 2; int value_produced = 2 * (number++); cout << value_produced << " " << number; Output: 4 3 int number = 2; int value_produced = 2* (++number); cout << value_produced << " " << number; Output: 6 3

+ Statement number--; Decrements value stored in variable number by 1 int number = 41; number--; cout << number; Outputs 40

- Expression 2 * (number--); First return the value stored in variable number to be multiplied by 2; then decrement value stored in variable number by 1 int number = 4; int value_produced = 2 * (number--); cout << value_produced; cout << number << endl; Outputs 8 3

+ ))%%)) --number; First decrement by 1 the value stored in variable number then use the decremented value in the expression number--; First return the current value stored in variable number to be used in the expression; then decrement the current value in variable number by 1

))% %)) int number = 2; int value_produced = 2 * (number--); cout << value_produced << " " << number; Output: 4 1 int number = 2; int value_produced = 2* (--number); cout << value_produced << " " << number; Output: 2 1

/!0 +1- Can you determine the output of the following code segments? int count = 3; while ( count-- > 0) cout << count << ; int n = 1; do cout << n << ; while ( n++ <= 3);

for 0 for statement: Similar to while loop Ideal for adding numerals for loop with single statement: sum = 0; for ( n = 1; n <= 4; n++) sum = sum + n; cout << sum << endl; sum: 0 1 3 6 10 Output: 10

0 Compound statement sum = 0; for ( n = 1; n <= 4; n++) { sum = sum + n; cout << sum << ; } sum: 0 1 3 6 10 Output: 1 3 6 10 Use braces when for loop body contains multiple statements

0 Initialization Action Update Action: Done after each iteration for ( n = 1; n <= 4; n++) Boolean Expression Repeat loop if true

for Loop Syntax for (Initialization_Action; Boolean Expression; Update_Action) { Statement_1 Statement_2 } Statement_n The body of a for loop can be a single statement or multiple statements enclosed in braces

for Loop Local Variable Declaration We can declare a local variable within a for loop statement sum = 0; for ( int n = 1; n <= 4; n++) { sum = sum + n; cout << sum << ; } sum = 0; for ( int n = 1; n <= 4; n++) sum = sum + n; cout << sum << ; Create variable n and initialize to 1 Variable n cannot be accessed outside the loop body * * ANSI C++ standard

for Loop More Update Actions for (n = 1; n < = 10; n = n + 2) for (n = 0 ; n > -100 ; n = n -7) Increment by 2 Decrement by 7 Increment by fraction for ( double size = 0.75; size <= 5; size = size + 0.05) for (double x = pow(y,3.0); x > 2.0; x = sqrt(x) ) Update by function call y is computed within the loop

Empty body statement C++ Empty Statement A Standalone semicolon It is executed by the compiler but does nothing sum = 0; ; Empty Statement

for Loop Empty body statement How does the compiler execute a trailing semicolon in a for statement? sum = 0; for ( n = 1; n <= 4; n++); sum = sum + n; cout << sum << endl; Body of for loop is an empty statement Variable n is outside of the for loop n is undefined (Error in assignment statement!!) Can you determine the output of the code segment? for ( n = 1; n <= 4; n++); cout << Game Over\n cout << endl;

for Loop break statement break; Use the break statement to abruptly exit the loop containing the break statement Why? Code detects abnormal conditions Avoid possible runtime errors

for Loop break statement Can you determine the output of the code segment? int n =5; while (--n > 0) { if ( n == 2) break; cout << n << ; } cout << End of Loop.\n ;