Notes
Slide Show
Outline
1
"Brad Rippe"
  • Brad Rippe
2
"Using Boolean Expressions"
  • Using Boolean Expressions
  • Multi-way Branches
  • More about C++ Loop Statements
  • Designing Loops
3
Questions???
4
Some Rules
  • If both operands are type int
    • Then the result is an int type


    • 23 * 38 = integer result
    • 23 / 38 = integer result


  • If one of the operands is a double
    • Then the result is a double type
    • 23.56 * 38 = double result
    • 23.56 / 38 = double result
    • 5 / 2.0 = double result
5
Variable Types and Operations
  • What results from the following operations?
  •  2+2
  • 2.0 * 4.0
  • 3/2
  • 3.0/2
6
Type Coercion
  • Type Coercion: automatic conversion of an operand to another data type
  • Promotion: convert to a higher type
  • Demotion: convert to a lower type


7
Rules Are
  • When operating on values of different data types, the lower one is promoted to the type of the higher one.


  • When using the = operator, the type of expression on right will be converted to type of variable on left


8
if-else statement
  • if(count == 1) {
  • …do some work…
  • } else if(count == 2) {
  • …do some other work…
  • } else {
  • …do some other work…
  • }
9
while loops
  • while(count < 9) {
  • … do some work…
  • }


  • do {
  • …do some work…
  • } while(count < 9);
10
while loops
  • int count = 0;
  • while(count < 3) {
  • cout << “Count is “ << count
  •       << endl;
  • count++;
  • }
  • cout << “I’m out!!!\n”;
11
Counter-Control Loop
  • Count-controlled loops are those loops that are executed a fixed number of times. The number of iterations is known before commencing the loop.


  • int  i = 1;
  • while (i <= 5)  {
  •      cout << "Square of " <<  i;
  • cout << " is "  << (i * i);
  • cout << endl;
  •      ++i;
  • }
12
Sentinel-Control Loop
  • Event-controlled loops are those loops that are executed an indefinite number of times until some condition occurs.


  • const int SENTINEL = -1;
  • int posInt;
  • int sum = 0;
  • cout << ”Enter number: \n”;
  • cin >> posInt;
  • while (posInt != SENTINEL) {
  • sum += posInt;
  • cout << “Enter number: \n”;
  • cin >> posInt ;
  • }
13
Pseudocode
  • Informal language
  • Doesn’t execute on a computer
  • Helps with developing algorithms
  • Described in executable statements
  • Can be easily translated into C++


14
Pseudocode Example
  • Prompt the user for their current salary
  • Input the current salary
  • Calculate the user’s retro pay for six months and output the retro pay
  • Calculate the new annual salary and output the annual salary
  • Calculate the new monthly salary and output the new monthly salary
15
Boolean Expressions
  • Type bool allows declaration of variables that have a value of true or false
  • Operators
    • <, >, !=, ==, <=, >=
    • &&, ||, !


  • bool executeIf  = true;
  • if(executeIf) {
  • cout << “executed if\n”;
  • }
16
&& - Truth tables
  • if ( gender == 1 && age >= 65 )
  • seniorFemales++;



17
|| - Truth tables
  • if ((semesterAverage >= 90) ||
  • (finalExam >= 90))
  • cout << "Student grade is A" << endl;


18
Truth Table Example
19
Short Circuit Evaluations
  •  && - logical and
  • || - logical or


  • if(x > 3 || y > 3)
    • cout << “x > 3 or y > 3” << endl;
20
bool type
  • Evaluates to a true or false value
  • New to C++
  • C uses 0 (zero) for false and a positive integer for true
  • Side effects of C
  • This is a compilation error in Java
21
Enums
  • Enumerations are types with a set of integer values


  • enum Speed { FAST, NORMAL, SLOW };
  • Speed speed; // expects one of the enums


  • Enums are capitalized because they are defined a constants
  • They are user-defined types, not given to us like int, char, double, etc.
22
Enums
  • Can be set to explicit values or not


  • enum Speed
  •      { FAST = 120, NORMAL = 65, SLOW = 20 };


  • if(speed == FAST) {
  • // mash the pedal
  • } else if(speed == NORMAL) {
  • // let mom drive
  • } else if(speed == SLOW) {
  • // let grandma drive
  • }
23
Blocks of Code
  • if(freeway == 91) {
  • // prepare to go slow


  • } else if(freeway == 91 && day == FRIDAY) {
  • // prepare to stop


  • }
24
Is the following legal?
  • int temperature = 80;
  • if(temperature >= 100) {
  • string msg = "Wow scorching day!\n";
  • } else if(temperature >= 90) {
  • string msg = "It's a hot day!\n";
  • } else if(temperature >= 80) {
  • string msg = "Not bad!\n";
  • } else {
  • string msg = "Wonderful weather!\n";
  • }
  • cout << msg << endl;
25
Nested if, if/else
  • string grade;
  • // declaration and initialization of
  • // finalscore & midterm


  • if (finalscore >= 90)
  •   if (midterm >= 90)
  •     grade = “A+”;
  •   else
  •     grade = “A”;
  • else if (finalscore >= 80)
  •     grade = “B”;
  •   else if (finalscore >= 70)
  •             grade = “C”;
  •        else
  •             grade = “F”;




  • cout << “grade= ” << grade << endl;
26
Who owns the else?
  • if (a >= 5) {
  •   c = c + 1;
  •   if (b < 20)
  •     b = 2;
  • } else {
  •   d = 5;
  • }
  • // why the second set of
  • // {} braces
  • if (a >= 5)
  •   c = c + 1;
  •   if (b < 20)
  •     b = 2;
  • else
  •   d = 5;
27
Nested if, if/else
  • string grade;
  • // declaration and initialization of
  • // finalscore & midterm


  • if (finalscore >= 90) {
  •     if (midterm >= 90) {
  •         grade = “A+”;
  •     } else {
  •         grade = “A”;
  •     }
  • } else if (finalscore >= 80) {
  •     grade = “B”;
  • } else if (finalscore >= 70) {
  •     grade = “C”;
  • } else {
  •     grade = “F”;
  • }




  • cout << “grade= ” << grade << endl;
28
Block rules
29
multi-way if/else example
  • score = 8
  • gpa declared, initialized
  • false
  • true
  • gpa = B




  • display gpa as B
  • What is advantage of the additional elses?


    • int score = 8;
    • char gpa = ‘ ‘;
    • if (score >= 9) {
      • gpa = ‘A’;
    • } else if (score >= 8) {
      • gpa = ‘B’;
    • } else if (score >= 7) {
      • gpa = ‘C’;
    • } else {
      • gpa = ‘F’;
    • }
    • cout << “grade=” << gpa;
    • // value of gpa?
30
Multi-way if/else advantage




    • int score = 8;
    • char gpa = ‘ ‘;
    • if (score >= 9) {
      • gpa = ‘A’;
    • } else if (score >= 8) {
      • gpa = ‘B’;
    • } else if (score >= 7) {
      • gpa = ‘C’;
    • } else {
      • gpa = ‘F’;
    • }
    • cout << “grade=” << gpa;
    • // value of gpa?
31
multi-way if/else example
  • score = 8
  • gpa declared, initialized
  • true
  • gpa = ‘C’
  • skip the else block
  • display gpa=C still WRONG



    • int score = 8;
    • char gpa = ‘ ‘;
    • if (score >= 7) {
      • gpa = ‘C’;
    • } else if (score >= 8) {
      • gpa = ‘B’;
    • } else if (score >= 9) {
      • gpa = ‘A’;
    • } else {
      • gpa = ‘F’;
    • }
    • cout << “grade=” << gpa;
    • // value of gpa?
32
Switch Statement
  • Syntax:
    • switch (value) {  // must be an integer result
      • case value1:
        • statements;
        • …
        • break;
      • case valueN:
        • statements;
        • …
        • break;
      • default:
        • statements;
        • ...
    • }
33
 
34
switch statement
  • char drink = ‘ ’;
  • cin >> drink;
  • switch(drink) {
  • case 'a':
  • price += 3.50;
  • break;
  • case 'b':
  • price += 3.00;
  • break;
  • default :
  • drink = 'q';
  • break;
  • }
35
more switch
  • What happens with the following code?


  • If break statements are not used with the case statements, execution falls through to the next case


36
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 executing the statements following it


  • Can be used to break out of loop blocks as well as switch blocks


37
switch statements
  • Contains case labels
  • Optional default case
  • Similar to the if/else if statement


  • switch(expression) {
  • case ‘a’:
  • break;
  • }
38
number++ vs ++number
  • (number++) returns the current value of number,
    then increments number
    • An expression using (number++) will use
      the value of number BEFORE it is incremented
  • (++number) increments number first and returns
     the new value of number
    • An expression using (++number) will use
      the value of number AFTER it is incremented
  • Number has the same value after either version!
39
Increment and Decrement Operators
  • Pre-increment Operator
    • ++a
    • int a = 2;
    • int b = (++a)*22;
  • Post-increment Operator
    • a++
    • int a = 2;
    • int b = (a++)*22;
40
for loop structure syntax
  • for (<initializing statement>;
  •      <continuation assertion>;
  •      <increment statement>) {
    • <body statement>;
    • ...
    • <body statement>;
  • }
41
for statement
42
For code example
43
Break and Continue
  • break quits the loop without executing the rest of the statements in the loop.
    • Used in switch statements
    • Can be used in loops, but not common
    • interrupts the current loop

  • continue stops the execution of the current iteration and goes back to the beginning of the loop to begin the next iteration. Executes if continuation condition is true.
    • used with loops, but not common
    • interrupts the current loop
44
Break Example
  • for(int i = 0; i < 10; i++) {
  • if(i == 5)
  • break;
  • cout << “i is “ <<  i << endl;
  • }


  • Output:
  • i is 0
  • i is 1
  • i is 2
  • i is 3
  • i is 4
45
Continue Example
  • for(int i = 0; i < 10; i++) {
  • if( i < 5 )
  • continue;
  • cout << “i is “ << i << endl;
  • }


  • Output:
  • i is 5
  • i is 6
  • i is 7
  • i is 8
  • i is 9
46
Nested for loop
  • for(int j = 0; j < 5; j++) {
  • cout << "outer: j is " << j << endl;
  • for(int i = 0; i < 5; i++) {
  • cout << " inner: i is " << i << endl;
  • }
  • }
47
What does the following output?


  • for (int a = 1; a <= 1; a++) {
  • cout << a++;
  • cout << a;
  • }
48
Debugging Loops
  • Common errors involving loops include
    • Off-by-one errors in which the loop executes
      one too many or one too few times
    • Infinite loops usually result from a mistake
      in the Boolean expression that controls
      the loop


49
Fixing Off By One Errors
  • Check your comparison:
      should it be < or <=?
  • Check that the initialization uses the
    correct value
  • Does the loop handle the zero iterations
    case?


50
Fix Infinite Loops
  • Check the direction of inequalities:
      <  or  > ?
  • Test for  <  or  >  rather than equality (= =)


  • Check to see that you didn’t use the assignment operator (=) instead of the comparison (==)
51
Starting Over
  • Sometimes it is more efficient to throw out a
    buggy program and start over


    • The new program will be easier to read
    • The new program is less likely to be as buggy
    • You may develop a working program faster than if you repair the bad code
      • The lessons learned in the buggy code will help you
        design a better program faster