J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Control Constructs Mechanisms for deciding when and how often an action should be taken.

Slides:



Advertisements
Similar presentations
1 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD © 2002 McGraw-Hill, Inc.
Advertisements

What is the Result and Type of the Following Expressions? int x=2, y=15;double u=2.0,v=15.0; -xx+yx-y x*vy / xx/yy%xx%y u*vu/vv/uu%v x * u(x+y)*uu /(x-x)
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
If Statements & Relational Operators Programming.
True or false A variable of type char can hold the value 301. ( F )
Branching Constructs Review l what are branching constructs? what type of branching constructs have we studied? l what is nested if? l what is multiway.
Iterative Constructs – chapter 4 pp 189 to 216 This lecture covers the mechanisms for deciding the conditions to repeat action. Some materials are from.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Loops. COMP104 Loops / Slide 2 Shortcut Assignment * C++ has a set of operators for applying an operation to a variable and then storing the result back.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
1 CS 105 Lecture 4 Selection Statements Wed, Jan 26, 2011, 6:05 pm.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Iterative Constructs Mechanisms for deciding under what conditions an action should be repeated JPC and JWD © 2002 McGraw-Hill, Inc.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Basic Of Computer Science
CONTROLLING PROGRAM FLOW
CPS120: Introduction to Computer Science Decision Making in Programs.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
1 COMS 261 Computer Science I Title: String Class Date: October 3, 2005 Lecture Number: 14.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
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.
Control structures Algorithm Development Conditional Expressions Selection Statements 1.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
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.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Boolean values Gateway to decision making. Background Our problem-solving solutions so far have the straight-line property –They execute the same statements.
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,
Control statements Mostafa Abdallah
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
CPS120: Introduction to Computer Science Decision Making in Programs.
Algorithms JPC and JWD © 2002 McGraw-Hill, Inc. 2 Algorithms 2 An Algorithm is a finite set of precise instructions for performing a computation or for.
What is the Result and Type of the Following Expressions? int x=2, y=15;double u=2.0,v=15.0; -xx+yx-y x*vy / xx/yy%xx%y u*vu/vv/uu%v x * u(x+y)*uu /(x-x)
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 15, 2004 Lecture Number: 11.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
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):
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Decision Structures Michele Co CS 101-E. 2 UVa CS101E Spring 2007 Today if statements Logical expressions –Truth tables –Boolean algebra –DeMorgan’s laws.
Programming Loops (continued).
C++ Iterative Constructs
Chapter 4 : Control Construct.
A mechanism for deciding whether an action should be taken
Branching Constructs Review
COMS 261 Computer Science I
Expression Review what is the result and type of these expressions?
Intro to Programming Week # 4 Control Structure Lecture # 8
Chapter 7 Conditional Statements
Flow Control Statements
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
Iterative Constructs Mechanisms for deciding under what conditions an action should be repeated JPC and JWD © 2002 McGraw-Hill, Inc.
COMS 261 Computer Science I
COMS 261 Computer Science I
Chap 7. Advanced Control Statements in Java
Presentation transcript:

J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Control Constructs Mechanisms for deciding when and how often an action should be taken

Ch 4 / Foil 2 Boolean Algebra l Logical expressions have the one of two values - true or false n A rectangle has three sides. n The instructor has a pleasant smile l The branch of mathematics that deals with this type of logic is called Boolean algebra n Developed by the British mathematician George Boole in the 19th century l Three key logical operators n And n Or n Not

Ch 4 / Foil 3 Boolean Algebra l Truth tables n Lists all combinations of operand values and the result of the operation for each combination l Example PQ P and Q False FalseFalse False TrueFalse True FalseFalse True TrueTrue

Ch 4 / Foil 4 Boolean Algebra l Truth table for or PQ P or Q False FalseFalse False TrueTrue True FalseTrue True TrueTrue

Ch 4 / Foil 5 Boolean Algebra l Truth table for not PNot P False True True False

Ch 4 / Foil 6 Boolean Algebra l Can create complex logical expressions by combining simple logical expressions l Example n not (P and Q) l A truth table can be used to determine when a logical expression is true PQ P and Qnot (P and Q) False FalseFalseTrue False TrueFalseTrue True FalseFalseTrue True TrueTrueFalse

Ch 4 / Foil 7 A Boolean Type C++ contains a type named bool Type bool has two symbolic constants true false l Boolean operators The and operator is && The or operator is || The not operator is ! l Warning & and | are also operators

Ch 4 / Foil 8 A Boolean Type l Example logical expressions bool P = true; bool Q = false; bool R = true; bool S = P && Q; bool T = !Q || R; bool U = !(R && !Q);

Ch 4 / Foil 9 Relational Operators l Equality operators == != l Examples int i = 32; int k = 45; bool q = i == k; bool r = i != k;

Ch 4 / Foil 10 Relational Operators l Ordering operators < > >= <= l Examples int i = 5; int k = 12; bool p = i < 10; bool q = k > i; bool r = i >= k; bool s = k <= 12;

Ch 4 / Foil 11 Operator Precedence Revisited l Precedence of operators (from highest to lowest) n Parentheses n Unary operators n Multiplicative operators n Additive operators n Relational ordering n Relational equality n Logical and n Logical or n Assignment

Ch 4 / Foil 12 Operator Precedence Revisited l Examples 5 != 6 || 7 <= 3 (5 !=6) || (7 <= 3) 5 * == 13 && 12 < 19 || !false == 5 < 24

Ch 4 / Foil 13 Conditional Constructs l Provide n Ability to control whether a statement list is executed l Two constructs n If statement –If –If-else –If-else-if n Switch statement

Ch 4 / Foil 14 The Basic If Statement l Syntax if (Expression) Action If the Expression is true then execute Action l Action is either a single statement or a group of statements within braces l Example if (Value < 0) { Value = -Value; } Expression Action truefalse

Ch 4 / Foil 15 Sorting Two Numbers cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; if (Value1 > Value2) { int RememberValue1 = Value1; Value1 = Value2; Value2 = RememberValue1; } cout << "The input in sorted order: " << Value1 << " " << Value2 << endl;

Ch 4 / Foil 16 The If-Else Statement l Syntax if (Expression) Action 1 else Action 2 l If Expression is true then execute Action 1 otherwise execute Action 2 if (v == 0) { cout << "v is 0"; } else { cout << "v is not 0"; } Expression Action 1 Action 2 true false

Ch 4 / Foil 17 Finding the Larger of Two Values cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; int Larger; if (Value1 < Value2) { Larger = Value1; } else { Larger = Value2; } cout << "Larger of inputs is: " Larger << endl;

Ch 4 / Foil 18 Selection l It is often the case that depending upon the value of an expression we want to perform a particular action l Two major ways of accomplishing of this choice n If-else-If statement –If-else statements “glued” together n Switch statement –An advanced construct

Ch 4 / Foil 19 The If-Else-If Statement l Example if ((ch == 'a') || (ch == 'A")) cout << ch << " is a vowel" << endl; else if ((ch == 'e') || (ch == 'E")) cout << " ch << " is a vowel" << endl; else if ((ch == 'i') || (ch == 'I")) cout << ch << " is a vowel" << endl; else if ((ch == 'o') || (ch == 'O")) cout << ch << " is a vowel" << endl; else if ((ch == 'u') || (ch == 'U")) cout << ch << " is a vowel" << endl; else cout << ch << " is not a vowel" << endl;

Ch 4 / Foil 20 Switch Statement switch (ch) { case 'a': case 'A": case 'e': case 'E": case 'i': case 'I": case 'o': case 'O": case 'u': case 'U": cout << ch << " is a vowel" << endl; break; default: cout << ch << " is not a vowel" << endl; }

cout << "Enter simple expression: "; int Left; int Right; char Operator; cin >> Left >> Operator >> Right; cout << Left << " " << Operator << " " << Right << " = "; switch (Operator) { case '+' : cout << Left + Right << endl; break; case '-' : cout << Left - Right << endl; break; case '*' : cout << Left * Right << endl; break; case '/' : cout << Left / Right << endl; break; default: cout << "Illegal operation" << endl; }

Ch 4 / Foil 22 Iterative Constructs l Provide n Ability to control how many times a statement list is executed l Three constructs n while statement n for statement n do-while statement

Ch 4 / Foil 23 The While Statement l Syntax while (Expression) Action l Semantics n If Expression is true then execute Action n Repeat this process until Expression evaluates to false l Action is either a single statement or a group of statements within braces Expression Action truefalse

Ch 4 / Foil 24 Power of Two Table const int TableSize = 20; int i = 0; long Value = 1; cout << "i" << "\t\t" << "2 ** i" << endl; while (i <= TableSize) { cout << i << "\t\t" << Value << endl; Value *= 2; ++i; }

Ch 4 / Foil 25 Character Counting int NumberOfNonBlanks = 0; int NumberOfUpperCase = 0; char c; while (cin >> c) { ++NumberOfNonBlanks; if ((c >= 'A') && (c <= 'Z')) { ++NumberOfUpperCase;}

Ch 4 / Foil 26 Counting Characters char c; int NumberOfCharacters = 0; int NumberOfLines = 0; while (cin.get(c)) { ++NumberOfCharacters; if (c == '\n') ++NumberOfLines } cout << "Characters: " << NumberOfCharacters << endl; cout << "Lines: " << NumberOfLines << endl;

int main() { cout > Value) { ValueSum += Value; ++ListSize; } if (ListSize > 0) { float Average = ValueSum / ListSize; cout << "Average: " << Average << endl; } else { cout << "No list to average" << endl; } return 0; } Ch 4/ Foil 27 The value of the input operation corresponds to true only if a successful extraction was made

Ch 4 / Foil 28 The For Statement l Syntax for (ForInit ; ForExpression; PostExpression) Action l Semantics n Execute ForInit statement n While ForExpression is true –Execute Action –Execute PostExpression l Example for (int i = 0; i < 20; ++i) { cout << "i is " << i << endl; }

Ch 4 / Foil 29 Iteration Using the For Statement ForExpression Action truefalse ForInit PostExpression

Ch 4 / Foil 30 Table Revisiting const int TableSize = 20; long Value = 1; cout << "i" << "\t\t" << "2**i" << endl; for (int i = 0; i <= TableSize; ++i) { cout << i << "\t\t" << Value << endl; Value *= 2; } The scope of i is limited to the loop!

Ch 4 / Foil 31 Displaying A Diagonal SimpleWindow W("One diagonal", 5.5, 2.25); W.Open(); for (int j = 1; j <= 3; ++j) { float x = j * ; float y = j * ; float Side = 0.4; RectangleShape S(W, x, y, Blue, Side, Side); S.Draw(); }

Ch 4 / Foil 32 Sample Display

Ch 4 / Foil 33 Displaying Three Diagonals SimpleWindow W("Three diagonals", 6.5, 2.25); W.Open(); for (int i = 1; i <= 3; ++i) { for (int j = 1; j <= 3; ++j) { float x = i j * ; float y = j * ; float Side = 0.4; RectangleShape S(W, x, y, Blue, Side, Side); S.Draw(); } The scope of i includes the inner loop. The scope of j is just the inner loop.

Ch 4 / Foil 34 Sample Display

int Counter1 = 0; int Counter2 = 0; int Counter3 = 0; int Counter4 = 0; int Counter5 = 0; ++Counter1; for (int i = 1; i <= 10; ++i) { ++Counter2; for (int j = 1; j <= 20; ++j) { ++Counter3; } ++Counter4; } ++Counter5; cout << Counter1 << " " << Counter2 << " " << Counter3 << " " Counter4 << " " Counter5 << endl; Ch 4/ Foil 35

Ch 4 / Foil 36 For Into While l Observation n The for statement is equivalent to { ForInit; while (ForExpression) { Action; PostExpression; }

Ch 4 / Foil 37 Iteration l Key Points n Make sure there is a statement that will eventually nullify the iteration criterion (i.e., the loop must stop) n Make sure that initialization of any loop counters or iterators is properly performed n Have a clear purpose for the loop –Document the purpose of the loop and how the body of the loop advances the purpose of the loop

Ch 4 / Foil 38 Riddle l Four hobos traveling across the country in need of money l Farmer offers 200 hours of work that could be done over the next couple of weeks l The laziest hobo convinces the other three hobos to draw straws l Each straw would be marked with an amount n The amount would represent both the number of days and the numbers of hours per day that the hobo would work n Example –If the straw was marked three then the hobo who drew it would work for three hours per day for three days l What are the best markings of the straws for a clever, lazy hobo?

Ch 4 / Foil 39 Observations l Need to find sets of whole numbers a, b, c, and d such that n a 2 + b 2 + c 2 + d 2 = 200 l Maximal legal number is 14 as 15 2 equals 225 which is greater than 200 l Minimal legal number is 1 l No advantage to listing the combinations more than once n Implication –Generate the solutions systematically n We will make sure that a <= b <= c <= d

Ch 4 / Foil 40 Method l Generate all possibilities for a where for each a possibility n Generate all possibilities of b where for each b possibility –Generate all possibilities for c where for each c possibility l Generate all possibilities for d where for each d possibility n Determine whether the current combination is a solution

Ch 4 / Foil 41 for (int a = 1; a <= 14; ++a) { for (int b = a; b <= 14; ++b) { for (int c = b; c <= 14; ++c) { for (int d = c; (d <= 14); ++d) { if (a*a + b*b + c*c + d*d == 200) { cout << a << " " << b << " " << c << " " << d << endl; } Nested For Loop Solution

Ch 4 / Foil 42 Simple Visualization l What statements can we make about the following data set? l Statistical analysis analysis indicates that observations come from interval 0 … 10 with an average value of 4.97 and a standard deviation of 2.95 l Another approach is to detect whether the sequence of observations represents a patter n Are the numbers arranged for example in Fibonacci order? l If no patterns are recognized, try data visualization n Plot the data set values in a two-dimensional manner –y-axis correspond to data set values –x-axis correspond to positions in the data set sequence

#include // Program 4.12 #include #include "rect.h" using namespace std; int ApiMain() { const float Unit = 0.25; cout << "Enter size of data set: "; int n; cin >> n; SimpleWindow W("Data set display", n+2, 10); W.Open(); for (float x = 1; x <= n; ++x) { cout << "Enter data value (n): "; float y; cin >> y; RectangleShape Point(W, x, y, Blue, Unit, Unit); Point.Draw(); } return 0; }

Ch 4 / Foil 44 Sample Run l Data values do have structure

Ch 4 / Foil 45 The Do-While Statement l Syntax do Action while (Expression) l Semantics n Execute Action n if Expression is true then execute Action again n Repeat this process until Expression evaluates to false l Action is either a single statement or a group of statements within braces Action true false Expression

Ch 4 / Foil 46 Waiting for a Proper Reply char Reply; do { cout << "Decision (y, n): "; if (cin >> Reply) Reply = tolower(Reply); else Reply = 'n'; } while ((Reply != 'y') && (Reply != 'n'));