Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.

Similar presentations


Presentation on theme: "1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4."— Presentation transcript:

1 1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4

2 2 Introduction Three building blocks for C++ control –Sequence structure –Selection structure –Repetition structure Operators –Assignment operators –Increment/decrement operators

3 3 Algorithms Algorithm is a procedure of solving a problem in terms of –The actions to execute and –The order in which these actions execute Program control –Specify the order in which statements execute

4 4 Pseudocode –An artificial and informal language that helps programmer develop algorithms –Normally describes only executable statements (not variable declarations) Prompt the user to enter 1 st integer Input the first integer Prompt the user to enter the 2 nd integer Input the 2 nd integer Add first integer and second integer, store results Display result

5 5 Control Structures Sequential execution –Execute one statement after the other in which they are written Transfer of control –Next one in sequence may not be next statement to execute –Indiscriminate use of transfer of control (goto statement) cause tremendous difficulty for software developers Structured programming (Bohm and Jocopini) –Goto elimination –More likely to be bug free –Clear, easier to debug and modify –Reduced development time Control structures –Sequence structure –Selection structure –Repetition structure

6 6 Sequence Structure in C++ Sequence-structure activity diagram Initial state Final state Action state symbol Notes

7 7 Selection Statements in C++ Single-selection statement (if) –Selects or ignores a single action Double-selection statement (if…else) –Selects between two different actions Multiple-selection statement (switch) –Selects among many different actions (groups of actions)

8 8 Repetition Statements in C++ Performs statements repeatedly as long as a condition (loop-continuation condition) remains true Three types of repetition statements –while Perform the action(s) in its body zero or more times –For Perform the action(s) in its body zero or more times –do…while Perform the action(s) in its body at least once

9 9 C++ keywords autobreakcasecharconst continuedefaultdodoubleelse enumexternfloatforgoto ifintlongregisterreturn shortsignedsizeofstaticstruct switchtypedefunionunsignedvoid volatilewhile andand_eqasmbitandbitor boolcatchclasscomplconst_cast deletedynamic_castexplicitexportfalse friendinlinemutablenamespacenew notnot_eqoperatororor_eq privateprotectedpublicreinterpret_caststatic_cast templatethisthrowtruetry typeidtypenameusingvirtualwchar_t xorxor_eq C++ only keywords Keywords common to C and C++ languages

10 10 Common Programming Errors Related to Keywords Using a keyword as an identifier is a syntax error Spelling a keyword with any uppercase letters is a syntax error. All of C++’s keywords contain only lowercase letters

11 11 Connect Control Statements Model each control statement as an activity diagram –Initial state represents the entry point –Final state represents the exit point Control-statement stacking –Control statements are attached to one another by connecting the exit point of one to the entry point of the next Control-statement nesting –One control statement is contained inside another

12 12 if Single-selection Statement Decision symbol Associated guard condition Evaluates to be true or false Transition arrow Single-entry /single-exit Guard conditions can be boolean expressions or any expressions that evaluate to a number. Boolean expression: true or false Any expression: zero (false), non-zero (true)

13 13 if…else Double-selection Statement Conditional operator (?:): only ternary operator in C++ cout =60 ? “Passed” : “Failed”);

14 14 Nested if…else Statements if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A"; else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B"; else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C"; else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F";

15 15 Cont’ if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A"; else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B"; else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C"; else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F"; A nested if…else statement can perform much faster than a series of single-selection if statements because of the possible early exit In a nested if…else statement, test the most likely condition first to maximize the chance of early exit Programming Tips

16 16 Dangling- else Problem The C++ compiler always associates an else with the immediately preceding if unless told to do otherwise by the placements of braces. This behavior can lead to dangling-else problem. if ( x > 5 ) if ( y > 5 ) cout 5"; else cout << "x is <= 5"; if ( x > 5 ) { if ( y > 5 ) cout 5"; } else cout << "x is <= 5"; Dangling- else Correct

17 17 Blocks if selection statement and if…else statement normally expect only one body statement Enclose several statements in the body of an if or in either part of an if…else with a pair of curly braces A set of statements contained in a pair of braces is called compound statement or a block –A block can be placed anywhere in a program that a single statement can be placed –Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors –Always putting the braces in an if…else statement helps prevent their accidental omission Null Statement (Empty statement) –Placing a semicolon (;) where a statement would normally be –Placing a semicolon after the condition in an if statement leads to a logic error in single- selection if statements and a syntax error in double selection if…else statements (when the if part contains an actual body statement)

18 18 while Repetition Statement Joins the transitions from the initial state and the action state

19 19 Infinite Loop Cause: No action in the while body to cause the condition to become false. Results: Repetition statement never terminates Program appears to “hang” or “freeze” int i = 1; int factorial = 1; while(i>0) { factorial = factorial*i; i++; } Infinite Loop

20 20 Formulating Algorithms: Counter-Controlled Repetition Definite Repetition Problem statement: A class of ten students took a quiz. The grades for the quiz are available to you. Calculate and display the total of all student grades and the class average on the quiz. Set total to zero Set grade counter to one While grade counter is less than or equal to ten Prompt the user to enter the next grade Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the total of the grades for all students in the class Print the class average Pseudocode Repetition terminates when counter exceeds 10 Update the counter

21 21 Off-by-one-error Cause: Use a loop’s counter-control variable in a calculation after the loop Result: The loop terminates when the counter’s value is one higher than its last legitimate value (i.e., 11 in the case of counting from 1 to 10)

22 22 Formulating Algorithms: Sentinel-Controlled Repetition Problem statement: Develop a class average algorithm that process grades for an arbitrary number of students each time it is run. Initialize total to zero Initialize counter to zero //avoid off-by-one-error Prompt the user to enter the first grade Input the first grade (possibly the sentinel) While the user has not yet entered the sentinel Add this grade into the running total Add one to the grade counter Prompt the user to enter the next grade Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the total of the grades for all students in the class Print the class average Else Print “No grades were entered” Sentinel value is -1 Proper message with information on sentinel value

23 23 Sentinel-Controlled Repetition vs Counter-Controlled Repetition Counter-controlled repetition –Each iteration of the while statement reads a value from the user, for the specified number of iterations Sentinel-controlled repetition –The program reads the first value before reaching the while –The body of while may never execute (e.g., no grades were entered)

24 24 Explicit and Implicit Conversion between Fundamental Types double average; average = static_cast (total)/gradeCounter; Explicit conversion is done by unary cast operator gradeCounter is promoted to double (implicit conversion)

25 25 Formatting for Floating-Point Numbers Nonparameterized stream manipulator –endl, fixed, showpoint, left, right(default) –Do not require header file Parameterized stream manipulator –Require #include –cout << “Class average is “ << setprecision(2) << fixed << average << endl; Round number to 2 decimal places

26 26 Formulating Algorithms: Nested Control Statements Problem statement: You have been given a list of these 10 students. Next to each name is written a 1 if the student passed or a 2 if the student failed. You have been asked to summarized the results in terms of number of passes and fails. Initialize passes to zero Initialize failures to zero Initialize student counter to one While student counter is less than or equal to 10 Prompt the user to enter the next exam result Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” If…else is nested in while body

27 27 Arithmetic Assignment Operators Assignment operator Sample expression ExplanationAssigns Assume: int c=3, d=5, e=4, f=6, g=12; += c += 7 c = c + 710 to c -= d -= 4 d = d - 41 to d *= e *= 5 e = e * 520 to e /= f /= 3 f = f / 32 to f %= g %= 9 g = g % 93 to g

28 28 Increment and Decrement Operators OperatorCalledSample expression Explanation ++ Preincrement ++a Increment a by 1, then use the new value of a in the expression in which it resides ++ Postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1 -- Predecrement --b Decrement b by 1, then use the new value of b in the expression in which it resides -- Postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1

29 29 Example: Preimcrementing and Postincrementing int main() { int c; // demonstrate postincrement c = 5; // assign 5 to c cout << c << endl; // print 5 cout << c++ << endl; // print 5 then postincrement cout << c << endl; // print 6 cout << endl; // skip a line // demonstrate preincrement c = 5; // assign 5 to c cout << c << endl; // print 5 cout << ++c << endl; // preincrement then print 6 cout << c << endl; // print 6 return 0; // indicate successful termination } // end main

30 30 Operator Precedence OperatorsAssociativityType () Left to right Parenthesis ++ -- static_cast () Left to right Unary (postfix) ++ -- + - Right to left Unary (prefix) * / % Left to right Multiplicative + - Left to right Additive > Left to right Insertion/extraction >= Left to right Relational == != Left to right Equality ?: Right to left Conditional = += -= *= /= %= Right to left Assignment


Download ppt "1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4."

Similar presentations


Ads by Google