Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated.

Slides:



Advertisements
Similar presentations
Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
If Statements & Relational Operators Programming.
True or false A variable of type char can hold the value 301. ( F )
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 9/24/07CS150 Introduction to Computer Science 1 Relational Operators and the If Statement.
Programming Switch command. COMP102 Prog. Fundamentals: Switch command / Slide 2 Multiple Selection: The switch Statement value1 action 1 value2 action.
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)
Chapter 6 Control Structures.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
CS 117 Spring 2002 Review for Exam 2 March 6, 2002 open book, 1 page of notes.
CSC 200 Lecture 4 Matt Kayala 1/30/06. Learning Objectives Boolean Expressions –Building, Evaluating & Precedence Rules Branching Mechanisms –if-else.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
1 Chapter 10 Various Topics User defined Types Enumerated Types Type Casting Syntactic Sugar Type Coercion.
True or False: Boolean Expression Boolean expression are expressions which evaluate to "true" or "false“ Primary operators to combine expressions: && (and),
CS102 Introduction to Computer Programming Chapter 4 Making Decisions Continued.
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.
Chapter 4 Selection Structures: Making Decisions.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
CS31: Introduction to Computer Science I Discussion 1A 4/9/2010 Sungwon Yang
CONTROLLING PROGRAM FLOW
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
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.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Chapter 3. Outline Relational Operators Loops Decisions Logical Operators Precedence Summary.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Chapter 5 Logic; Got Any?. Flow of Control The order in which the computer executes statements in a program Control Structure A statement used to alter.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
CSIS 113A Lecture 3 Conditional & Switch Glenn Stevenson CSIS 113A MSJC.
Chapter 05 (Part III) Control Statements: Part II.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
1 09/15/04CS150 Introduction to Computer Science 1 Life is Full of Alternatives Part 2.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
1 Chapter 4, Part 1 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
1 CS161 Introduction to Computer Science Topic #8.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Introduction to Computer Programming
Chapter 3 Control Statements
Computing and Statistical Data Analysis Lecture 2
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.
A mechanism for deciding whether an action should be taken
Engineering Problem Solving with C++, Etter/Ingber
مبانی برنامه‌سازی با C++ جلسه دوم
Selection CSCE 121 J. Michael Moore.
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
2.6 The if/else Selection Structure
Engineering Problem Solving with C++ An Object Based Approach
Chapter 5: Control Structures II (Repetition)
Life is Full of Alternatives
The switch Statement When we want to compare a variable against several values to see which one it has, we can use the switch statement: switch (status)
Presentation transcript:

Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated types To introduce the notion of enumerated types To explore the switch statement as an alternative to multiway if-else statements To explore the switch statement as an alternative to multiway if-else statements To examine the for -statement as a looping option To examine the for -statement as a looping option To demonstrate the design of good nested loops To demonstrate the design of good nested loops To view the conditional statement as a alternative to a simple if-else statement To view the conditional statement as a alternative to a simple if-else statement

Chapter 3CS 140Page 2 Precedence Rules for Boolean Expressions With the addition of Boolean operators, the precedence rules that C++ uses to evaluate expressions become more complex. Parentheses still take the highest precedence Parentheses still take the highest precedence Multiplication, division, and modulus come second. Multiplication, division, and modulus come second. Addition and subtraction take the next precedence. Addition and subtraction take the next precedence. Precedence ties are still handled in left-to-right fashion. Precedence ties are still handled in left-to-right fashion. Order-related inequality operators (, =) are next. Order-related inequality operators (, =) are next. The pure equality/inequality (==, !=) operators are next. The pure equality/inequality (==, !=) operators are next. The Boolean AND operator (&&) takes the next precedence. The Boolean AND operator (&&) takes the next precedence. The Boolean OR operator (||) takes the lowest precedence. The Boolean OR operator (||) takes the lowest precedence.

Chapter 3CS 140Page 3 Precedence Rules Examples int x = 7, y = 7, z = 7; if (x == y == z) cout << “YES”; cout << “YES”;else cout << “NO”; cout << “NO”; int a = 5, b = 4, c = 3; if (a < b < c) cout << “YES”; cout << “YES”;else cout << “NO”; cout << “NO”; Output: NO The left equality is checked and evaluates to true (numerical 1), which is not equal to the z-value! Output: NO The left equality is checked and evaluates to true (numerical 1), which is not equal to the z-value! Output: YES The left inequality is checked and evaluates to false (numerical 0), which is less than the c-value! Output: YES The left inequality is checked and evaluates to false (numerical 0), which is less than the c-value!

Chapter 3CS 140Page 4 Boolean Expressions - Short-Circuit Evaluation of && When a Boolean expression using the && operator is evaluated, the first subexpression is evaluated first. if it evaluates to false, then the second subexpression is ignored. if ((x != 0) && (y/x > 1)) z = 100; z = 100;else z = -1; z = -1; if ((y/x > 1) && (x != 0)) z = 100; z = 100;else z = -1; z = -1; When this code segment is encountered and x ’s value is zero, z will be assigned either the value 100 or the value -1. When this code segment is encountered and x ’s value is zero, the program crashes due to the attempt to divide by zero!

Chapter 3CS 140Page 5 Boolean Expressions - Short-Circuit Evaluation of || When a Boolean expression using the || operator is evaluated, the first subexpression is evaluated first. if it evaluates to true, then the second subexpression is ignored. if ((ct == 0) || (total/ct > 70)) cout << “NO PROBLEMO”; cout << “NO PROBLEMO”; if ((total/ct > 70) || (ct == 0)) cout << “NO PROBLEMO”; cout << “NO PROBLEMO”; When this code segment is encountered and ct ’s value is zero, the message is output. When this code segment is encountered and ct ’s value is zero, the program crashes due to the attempt to divide by zero!

Chapter 3CS 140Page 6 Enumerated Types To enhance the readability of one’s code, a programmer can define an enumerated type, which consists of a set of integer constants. #include using namespace std; enum MonthNumber { JANUARY = 1, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; void main() { MonthNumber monthCount = JANUARY; double monthlyRate = 12.34, totalCost = 0.0; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Computing Annual Costs:\n\n"; while (monthCount <= DECEMBER) { totalCost += monthlyRate; monthCount = MonthNumber(monthCount + 1); } cout << endl << endl << "Total: $" << totalCost << endl << endl; return; }

Chapter 3CS 140Page 7 switch Statements C++ switch statements provide a simple alternative to the use of convoluted nested if-else statements. if (month == 2) { if (year % 4 == 0) if (year % 4 == 0) daysInMonth = 29; daysInMonth = 29; else else daysInMonth = 28; daysInMonth = 28;} else if ((month == 4) || (month == 6) || (month == 6) || (month == 9) || (month == 11)) (month == 9) || (month == 11)) daysInMonth = 30; daysInMonth = 30;else daysInMonth = 31; daysInMonth = 31; switch (month) { case 2: { case 2: { if (year % 4 == 0) if (year % 4 == 0) daysInMonth = 29; daysInMonth = 29; else else daysInMonth = 28; daysInMonth = 28; break; break; } case 4: case 4: case 6: case 6: case 9: case 11: { daysInMonth = 30; break; } case 9: case 11: { daysInMonth = 30; break; } default: { daysInMonth = 31; break; } default: { daysInMonth = 31; break; }}

Chapter 3CS 140Page 8 #include using namespace std; void main() { char letter; bool gotAVowel = false; do { cout << "Please enter a letter: "; cin >> letter; switch(letter) { case 'a': case 'A': cout << "Apple\n";gotAVowel = true; break; case 'e': case 'E': cout << "Egg\n"; gotAVowel = true; break; case 'i': case 'I': cout << "Iodine\n";gotAVowel = true; break; case 'o': case 'O': cout << "Oval\n";gotAVowel = true; break; case 'u': case 'U': cout << "Upper\n"; gotAVowel = true; break; default: cout << "That is not a vowel. Please try again.\n"; } }while(!gotAVowel); } The break statements ensure that the switch statement is exited once the appropriate case is handled. Without the break statements, all cases might execute. The default case is executed if no other case value matches.

Chapter 3CS 140Page 9 Conditional Statements C++ conditional statements provide a concise alternative to the use of relatively simple if-else statements. if (year % 4 == 0) daysInMonth = 29; daysInMonth = 29;else daysInMonth = 28; daysInMonth = 28; daysInMonth = (year % 4 == 0) ? 29 : 28; if (val > 0) cout << “GOOD”; cout << “GOOD”;else cout << “BAD”; cout << “BAD”; (val > 0) ? (cout 0) ? (cout << “GOOD”) : (cout << “BAD”);

Chapter 3CS 140Page 10 The for Statement The C++ for statement is designed to facilitate looping when the control of the loop contains three standard features: An initialization action that is performed just before the loop is started the first time. An initialization action that is performed just before the loop is started the first time. A Boolean expression that is checked just before entering the loop at each iteration. A Boolean expression that is checked just before entering the loop at each iteration. An update action that is performed just after each iteration of the loop is completed. An update action that is performed just after each iteration of the loop is completed. for (initAction; booleanExp; updateAction) bodyOfLoop bodyOfLoop

Chapter 3CS 140Page 11 #include using namespace std; const double PAY_RATE = 10.15; void main() { double payForWeek = 0.0; int dayOfWeek; double hoursWorked; for(dayOfWeek = 1; dayOfWeek <= 7; dayOfWeek++) { cout << "How many hours did you work on day " << dayOfWeek << "? "; cin >> hoursWorked; (dayOfWeek == 1) ? (payForWeek += 1.5 * hoursWorked * PAY_RATE) : (payForWeek += hoursWorked * PAY_RATE); } cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << endl << endl << "Your Pay For \n" << "The Week Is $" << payForWeek << endl << endl; } dayOfWeek is initialized to 1 when the for -loop is first encountered. This inequality is checked just before the body of the loop is entered (or re-entered). This increment statement is executed right after each execution of the body of the loop. A for -loop Example

Chapter 3CS 140Page 12 #include using namespace std; void main() { int iterationNbr, repetitionNbr, indentSpaceNbr; for (iterationNbr = 1; iterationNbr <= 25; iterationNbr++) for (repetitionNbr = 1; repetitionNbr <= 1000; repetitionNbr++) { cout << '\r'; for (indentSpaceNbr = 1; indentSpaceNbr <= iterationNbr; indentSpaceNbr++) cout << ' '; cout << "HAPPY NEW YEAR!"; } cout << endl << endl; return; } Nested for -loops