1 / 56

Section 3 - Selection and Repetition Constructs

Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition. Selection – choosing between alternatives. Relational Operators. Used to compare numbers, characters and strings to determine relative order Operators:. Relational Expressions.

luana
Download Presentation

Section 3 - Selection and Repetition Constructs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Section 3 - Selection and Repetition Constructs

  2. Control Structures 1. Sequence 2. Selection 3. Repetition

  3. Selection – choosing between alternatives

  4. Relational Operators • Used to compare numbers, characters and strings to determine relative order • Operators:

  5. Relational Expressions • Result is a Boolean value – true or false • Examples: • 12 > 5 is true • 7 <= 5 is false • if x is 10, then • x == 10 is true • x != 8 is true • x == 8 is false

  6. Examples int i = 5; int k = 12; bool p = (i < 10); bool q = (k > i); bool r = (i >= k); bool s = (k <= 12);

  7. Comparison Operators

  8. Relational Expressions • Can be assigned to a variable • result = x <= y; • Assigns 0 for false, 1 for true • Do not confuse = and ==

  9. The if Statement • Allows statements to be conditionally executed or skipped over • Models the way we mentally evaluate situations • “If it is raining, take an umbrella.” • Syntax • if (expression) • statement;

  10. if statement – what happens • To evaluate • if (expression) • statement; • If (expression) is true, then statement is executed. • If (expression) is false, then statement is skipped – not executed

  11. if statement – what happens expression expression is false expression is true statement

  12. Expanding the if Statement • To execute more than one statement as part of an if statement, enclose them in { } • if (score > 90) • { • grade = “Excellent”; • cout << “Well done!\n"; • } • { } creates a block of code

  13. Example if (radius >= 0) { area = radius * radius * PI; cout << "The area for the circle of " << " radius " << radius << " is " << area; }

  14. The if/else Statement • Allows choice between statements if (expression) is true or false • Syntax • if (expression) • statement1; // or block • else • statement2; // or block

  15. expression expression is false expression is true statement1 statement2 if/else – what happens

  16. Example if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';

  17. Finding the Max cout << "Enter two integers: "; int Value1; int Value2; cin >> Value1 >> Value2; int Max; if (Value1 < Value2) { Max = Value2; } else { Max = Value1; } cout << "Maximum of inputs is: " << Max << endl;

  18. The if/else/if Statement • Chain of if statements that test in order until one is found to be true • Also models thought processes: • “If it is raining, take an umbrella, else, if it is windy, take a hat, else, • take sunglasses”

  19. if/else/if format • if (expression) • statement1; // or block • else if (expression) • statement2; // or block • . • . // other else ifs . • else if (expression) • statementn; // or block

  20. 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; }

  21. Example

  22. The switch Statement • Used to select among statements from several alternatives • May be used instead of if/else if statements

  23. switch Statement switch (weather) { // sunny case 0: take sunglasses; break; // windy case 1: take hat; break; // rainy case 2: take umbrella; break; // not any of the above default: flip a coin!; }

  24. switch statement format switch (expression) //integer { case exp1: statement1; case exp2: statement2; ... case expn: statementn; default: statementn+1; }

  25. switch statement requirements • expression must be an integer or char variable, or an expression that evaluates to an integer value • exp1 through expn must be constant integer expressions or literals, and must be unique in the switch statement • default is optional but recommended “catch-all”

  26. The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; } The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.

  27. switch statement – how it works • expression is evaluated • The value of expression is compared against exp1 through expn. • If expression matches value expi, the program branches to the statement(s) following expi • Note: Must “break out”of switch construct after statement(s) • executed. • 4. If no matching value is found, the program branches to the statement after default

  28. break statement • Used to stop execution in the current block • Also used to exit a switch statement • Useful to execute a single case statement without “falling through” and executing the statements following it

  29. Example switch (ch) { case 'a': cout << ch; case 'b': cout << ch; case 'c': cout << ch; } If ch equals ‘a’, what happens? switch (ch) { case 'a': cout << ch; break; case 'b': cout << ch; break; case 'c': cout << ch; }

  30. A 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; }

  31. 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; } Example

  32. Logical Operators - examples int x = 12, y = 5, z = -4;

  33. Common Error 1: Forgetting Necessary Braces

  34. Common Error 2: Wrong Semicolon at the if Line

  35. Common Error 4: Redundant Testing of Boolean Values

  36. Common Error 3: Mistakenly Using = for == if (count = 1) cout << "count is zero" << endl; else cout << "count is not zero" << endl;

  37. Repetition - looping

  38. Suppose that you need to print a string (e.g. "Welcome to C++!") a hundred times. - It would be tedious to have to write the following statement a hundred times: cout << "Welcome to C++!" << endl; So, how do you solve this problem? Answer: Use one of the three looping constructs available

  39. The while Loop • Loop: a statement or set of statements that may execute more than one time (repeats) Syntax • while (expression) • statement; • Will execute statement repeatedly while expression evaluates to true • statement can also be a block of statements enclosed in { }

  40. while Loop • no ; after (expression) • while is a pre-test loop – expression is evaluated before the loop executes • Loop may not be executed at all! – pre-test • loop must contain code to make expression become false • Infinite loop: loop that does not stop

  41. Example int count = 0; while (count < 100) { cout << "Welcome to C++!\n"; count++; }

  42. while Loop Example • int val = 5; • while (val <= 8) • cout << val++ << endl; produces output: • 5 • 6 • 7 • 8

  43. Counters • Counter: variable that is incremented or decremented each time a loop repeats • Can be used to control execution of the loop (called a loop controlvariable) • Must be initialized before entering loop • May be incremented/decremented either inside the loop or in the loop test

  44. Letting the User Control a Loop int num = 1, limit; cout << "Table of squares\n"; cout << "How high to go? "; cin >> limit; cout << "number square\n"; while (num <= limit) { cout << num <<“ “ << num*num << endl; num++; }

  45. The do-while Loop • do-while: a post-test loop – execute the loop, then test the expression Syntax • do • statement; // or block in { } • while (expression); • Note ; after (expression)

  46. do-while Loop • Loop always executes at least once – post-test • Execution continues as long as expression is true, stops repetition when expression becomes false • Useful in menu-driven programs to bring user back to menu to make another choice

  47. Statement(s) true Expression false

  48. for Loop • Useful for counter-controlled loop Syntax • for (initialization; test; update) • statement; // or block in { } • Or, re-stated with a counter variable • for (i = initialValue; i < endValue; i++) • statement; // or block in { }

More Related