Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 : Control Construct.

Similar presentations


Presentation on theme: "Chapter 4 : Control Construct."— Presentation transcript:

1 Chapter 4 : Control Construct

2 Key Concepts: logical values and operation true tables bool type
relational operators short-circuit evaluation if-else statement switch statement break statement enum statement for construct while construct do construct infinite loops invariants

3 Boolean Algebra Logical expressions have the one of two values - true or false A rectangle has three sides The instructor has a pleasant smile The branch of mathematics is called Boolean algebra Developed by the British mathematician George Boole in the 19th century Three key logical operators And Or Not

4 Boolean Algebra P Q P and Q True table of logical “and”
Truth tables Lists all combinations of operand values and the result of the operation for each combination P Q P and Q false false false false true false true false false true true true True table of logical “and”

5 Boolean Algebra True table of logical “or” P Q P or Q
Truth tables Lists all combinations of operand values and the result of the operation for each combination P Q P or Q false false false false true true true false true true true true True table of logical “or”

6 Boolean Algebra P not P false true true false
Truth tables Lists all combinations of operand values and the result of the operation for each combination P not P false true true false True table of logical “not”

7 Boolean Algebra Can create complex logical expressions by combining simple logical expressions Example not (P and Q) A truth table can be used to determine when a logical expression is true P Q P and Q not(P and Q) false false false true true false true true false true false true false true true false

8 A Boolean Type C++ contains a type named bool
Type bool has two symbolic constants true false Boolean operators The and operator is && The or operator is || The not operator is ! Warning & and | are also operators so be careful what you type

9 A Boolean Type Example logical expressions
bool P = true; bool Q = false; bool R = true; bool S = (P && Q); bool T = ((!Q) || R); bool U = !(R && (!Q));

10 Relational Operators Equality operators == != Examples int i = 32;
int k = 45; bool q = (i == k); bool r = (i != k);

11 Relational Operators Ordering operators < > >= <= Examples
int i = 5; int k = 12; bool p = (i < 10); bool q = (k > i); bool r = (i >= k); bool s = (k <= 12);

12 Operator Precedence Revisited
Precedence of operators (from highest to lowest) Parentheses (), [] Unary operators !, +, -, ++, --, *, &, … Multiplicative operators *, /, % Additive operators , - Relational ordering >, >=, <, <= Relational equality ==, != Logical and && Logical or || Assignment =, +=, -=, *=, /=

13 Operator Precedence Revisited
Consider 5 * == 13 && 12 < 19 || !false == 5 < 24 Yuck! Do not write expressions like this!

14 Operator Precedence Revisited
Consider 5 * == 13 && 12 < 19 || !false == 5 < 24 However, for your information it is equivalent to 5 * == 13 && 12 < 19 || !false == 5 < 24 ( ) ( ) ( ) ( ) ( ) ( ) ( ) ( )

15 Operator Precedence Revisited
Consider 5 * == 13 && 12 < 19 || !false == 5 < 24 However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19)) || ((!false) == (5 < 24)) Short-circuit evaluation bool b = (i != 0 ) && ((j/i) < 5);

16 Three Basic Constructs
In structural programming paradigm, any complex computing can be expressed by the statements of only three basic constructs 1. Sequence construct 2. Conditional construct 3. Iteration construct

17 Three Basic Constructs
Sequence construct A B C

18 Three Basic Constructs
Conditional construct Condition A B Yes No Condition A Yes No

19 Three Basic Constructs
Iteration construct Condition A Yes No Condition A Yes No

20 Basic Flow Diagram Symbols
Connections Start/End Procedure Condition Input/Output

21 Flow Diagram Example Start a < b Input a, b, c min = a min = b Yes
No c < min min = c Output min End Yes No

22 Conditional Constructs
Provide Ability to control whether a statement list is executed Two constructs If statement if if-else if-else-if Switch statement switch - case

23 The Basic if Statement Expression Action true false if (Expression)
Syntax If the Expression is true then execute Action Action is either a single statement or a group of statements within braces

24 Example if (iValue < 0) { iValue = -iValue; }
Is our number negative? iValue < 0 iValue = -iValue true false If Value is less than zero then we need to update its value to that of its additive inverse If Value is not less than zero then our number is fine as is Our number is now definitely nonnegative

25 Sorting Two Numbers cout << "Enter two integers: "; int iValue1;
cin >> iValue1 >> iValue2; if (iValue1 > iValue2) { int iTemp = iValue1; iValue1 = iValue2; iValue2 = iTemp; } cout << "The input in sorted order: " << iValue1 << " " << iValue2 << endl;

26 Semantics Are the numbers out of order Rearrange value1
iValue2 < iValue1 int iTemp = iValue1 iValue1 = iValue2 iValue2 = iTemp true false Are the numbers out of order Rearrange value1 and value2 to put their values in the proper order The numbers were rearranged into the proper order The numbers were initially in order The numbers are in order

27 What is the Output? int m = 10; int n = 5; if (m < n) ++m; ++n;
cout << " m = " << m << " n = " n << endl;

28 The if-else Statement Syntax if (Expression) Action1 else Action2
true false If Expression is true then execute Action1 otherwise execute Action2 if (v == 0) { cout << "v is 0"; } else { cout << "v is not 0"; }

29 Example: Finding the Max
cout << "Enter two integers: "; int iValue1; int iValue2; cin >> iValue1 >> iValue2; int iMax; if (iValue1 < iValue2) { iMax = iValue2; } else iMax = iValue1; cout << "Maximum of inputs is: " << iMax << endl;

30 Finding the Max Is Value2 larger than Value1 Yes, it is . So Value2 is
larger than Value1. In this case, Max is set to Value2 iValue1 < iValue2 Max = iValue2 Max = iValue1 true false No, its not. So Value1 is at least as large as Value2. In this case, Max is set to Value1 Either case, Max is set correctly

31 Selection It is often the case that depending upon the value of an expression we want to perform a particular action Two major ways of accomplishing this choice if-else-if statement if-else statements “glued” together switch statement An advanced construct

32 An if-else-if Statement
if ( nbr < 0 ) { cout << nbr << " is negative" << endl; } else if ( nbr > 0 ) { cout << nbr << " is positive" << endl; else { cout << nbr << " is zero" << endl;

33 A switch Statement switch( SwitchExpression ) { case CaseExpression1 :
Action1; break; case CaseExpression2 : Action2; ...... case CaseExpressionN : ActionN; default: Default action; } The case expression must be constant integral expression Actions are either a single statement or a group of statements

34 A switch Statement Example: 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; }

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

36 enum statement enum TypeName … SymbolicConstantN [ = n ]
C++ provides enum statement to define a collection of related symbolic constant It can also be used to define a programmer-defined types enum TypeName { SymbolicConstant1 [ = i ] , SymbolicConstant2 [ = j ] , SymbolicConstantN [ = n ] }; Note: 1. Here […] indicates the options 2. i, j and n must be integers If the SymbolicConstant is not assigned a integer value, the first will have 0, and the next will be increment automatically.

37 Example of enum type enum MONTHS_OF_YEAR { January = 1, February,
March , April , May , June , July , August , September , October , November , December }; enum DAY_OF_WEEK { Monday = 1, Tuesday , Wednesday , Thursday, Friday , Saturday, Sunday }; enum COLORS { Black, Red, Green, Blue, Yellow, Pink, White };

38 Example of enum type MONTHS_OF_YEAR emMonth = January;
DAY_OF_WEEK emDayOfWeek = Thursday; COLORS emColor = Green; int iDay = 30; switch(emMonth) { case January: iDay = 31; break; case February: iDay = 28; default: }

39 Iterative Constructs Mechanisms for deciding under what conditions an action should be repeated

40 Averaging

41 Determining Average Magnitude
Suppose we want to calculate the average apparent brightness of a list of five star magnitude values Can we do it Yes, it would be easy Suppose we want to calculate the average apparent brightness of a list of 8,479 stars visible from earth Yes, but it would be gruesome without the use of iteration Suppose we want to calculate the average apparent brightness of a list of five star magnitude values Can we do it? Yes, it would be easy

42 C++ Iterative Constructs
Three constructs while statement for statement do-while statement The while statement Syntax Logical expression that Determines whether the action is to be executed while ( Expression ) { Action; } Action to be iteratively performed until logical expression is false

43 while Semantics Expression is evaluated at the start of each
iteration of the loop Expression Action true false If Expression is true, Action is executed. If Expression is false, program Execution continues with next statement

44 // Computing an average
int iListSize = 4; int iProcessedNbr = 0; double dSum = 0.0; while (iProcessedNbr < iListSize) { double dValue; cin >> dValue; dSum += dValue; ++iProcessedNbr; } double dAverage = dSum / iProcessedNbr; cout << "Average: " << dAverage << endl;

45 Better Way of Averaging
// Computing an average int iProcessedNbr = 0; double dSum = 0.0; double dValue; while ( cin >> dValue ) { sum += dValue; ++iProcessedNbr; } double dAverage = dSum / iProcessedNbr ; cout << "Average: " << dAverage << endl; The value of the input operation corresponds to true only if a successful extraction was made What if list is empty?

46 Even Better Way of Averaging
// Computing an average int iProcessedNbr = 0; double dSum = 0.0; double dValue; while ( cin >> dValue ) { dSum += dValue; ++iProcessedNbr; } if ( iProcessedNbr > 0 ) double dAverage = dSum / iProcessedNbr ; cout << "Average: " << dAverage << endl; else cout << "No list to average" << endl;

47 const int TABLE_SIZE = 20;
int i = 0; long lEntry = 1; cout << "i" << "\t\t" << "2 ** i" << endl; while (i < TABLE_SIZE ) { cout << i << "\t\t" << lEntry << endl; lEntry = 2 * lEntry; ++i; } //Power of Two Table

48 The for Statement for (ForInit ; ForExpression; PostExpression) {
Syntax for (ForInit ; ForExpression; PostExpression) { Action; } Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; }

49 ForInit ForExpr false true Action PostExpr Evaluated once at
the beginning of the for statements's execution ForExpr Action true false ForInit PostExpr The ForExpr is evaluated at the start of each iteration of the loop If ForExpr is true, Action is executed After the Action has completed, the PostExpression is evaluated If ForExpr is false, program execution continues with next statement After evaluating the PostExpression, the next iteration of the loop starts

50 Table Revisiting //Power of Two Table const int TABLE_SIZE = 20;
long lEntry = 1; cout << "i" << "\t\t" << "2**i" << endl; for (int i = 0; i <= TABLE_SIZE; ++i) { cout << i << "\t\t" << lEntry << endl; lEntry *= 2; }

51 Table Revisiting //Power of Two Table const int TABLE_SIZE = 20;
long lEntry = 1; cout << "i" << "\t\t" << "2**i" << endl; for (int i = 0; i <= TABLE_SIZE; ++i) { cout << i << "\t\t" << lEntry << endl; lEntry *= 2; } cout << "i is" << i << endl; // illegal The scope of i is limited to the loop!

52 Fibonacci sequence The first 8 number of Fibonacci sequence:
1, 1, 2, 3, 5, 8, 13, 21 …

53 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 fSide = 0.4; RectangleShape S(W, x, y, Blue, fSide, fSide); S.Draw(); }

54 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(); }

55 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;

56 for into while for (ForInit ; ForExpression; PostExpression) { Action;
} ForInit; while( ForExpression ) { Action; PostExpression; }

57 Counting Characters int iNbrOfNonBlanks = 0; int iNbrOfUpperCase = 0;
char c; while (cin >> c) { ++iNbrOfNonBlanks; if ((c >= 'A') && (c <= 'Z')) { ++iNbrOfUpperCase; } cout << "Nonblank characters: " << iNbrOfNonBlanks << endl << "Uppercase characters: " << iNbrOfUpperCase << endl; Counting Characters Only extracts nonblank characters

58 Counting All Characters
int iNbrOfChars = 0; int iNbrOfLines = 0; char c; while ( cin.get(c) ) { ++ iNbrOfChas; if (c == '\n') { ++ iNbrOfLines; } cout << "Characters: " << iNbrOfChars << endl << "Lines: " << iNbrOfLines << endl; Counting All Characters Extracts all characters

59 File Processing #include <iostream> #include <fstream>
using namespace std; int main() { ifstream fin("mydata.txt"); int iValuesProcessed = 0; float fValueSum = 0; float fValue; while ( fin >> fValue ) fValueSum += fValue; ++iValuesProcessed; } if (iValuesProcessed > 0) ofstream fout("average.txt"); float fAverage = fValueSum / iValuesProcessed; fout << "Average: " << fAverage << endl; return 0; else cerr << "No list to average" << endl; return 1; File Processing

60 The Do-While Statement
Syntax do { Action; } while (Expression) Action true false Expression Semantics Execute Action If Expression is true then execute Action again Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces

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

62 Iteration Do’s Key Points
Make sure there is a statement that will eventually terminate the iteration criterion The loop must stop! Make sure that initialization of loop counters or iterators is properly performed Have a clear purpose for the loop Document the purpose of the loop Document how the body of the loop advances the purpose of the loop

63 Home works Exercises 4.1 ~ 4.3 Exercises 4.12~4.14

64 End of Chapter 4


Download ppt "Chapter 4 : Control Construct."

Similar presentations


Ads by Google