if Statements

if Statement without else

  1. if.C: An if statement.
  2. quarters.C: another example. Singular vs. plural.

else/if statements

  1. consecutive1.C and consecutive2.C.
    The last two if statements in consecutive1.C are a pair of consecutive, mutually exclusive if statements.
    No matter what happens, one if statement will be true, and one if statement will be false.

    It could be hard to recognize when a pair of logical expressions are mutually exclusive:

            if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0) {
                    cout << year << " is a leap year.\n";
            }
    
            if (year % 400 != 0 && (year % 100 == 0 || year % 4 != 0)) {
                    cout << year << " is not a leap year.\n";
            }
    
  2. threeway1.C and threeway2.C.
    Steer the computer in one of three possible directions.
  3. 12hour.C. Steer the computer in one of three possible directions to output the current hour on a 12-hour clock.
    In this program, why is hour <= 12 better than hour < 13?
  4. Exercise. Imitating the three-way else/if you just saw in threeway2.C and 12hour.C, add a three-way else/if to morning.C to output one of three possible messages:
    1. Good morning if the hour is less than 12 (noon); otherwise …
    2. Good afternoon if the hour is less than 17 (5:00 pm); otherwise …
    3. Good evening.
    Does your cash machine display these messages?
  5. leap.C. Steer the computer in one of four possible directions.
    Could have done this with just one complicated if statement; see above.
  6. Exercise. Imitating the four-way else/if you just saw in leap.C, make morning.C output one of four possible messages:
    1. Good morning if the hour is less than 12 (noon); otherwise …
    2. Good afternoon if the hour is less than 17 (5:00 pm); otherwise …
    3. Good evening if the hour is less than 21 (9:00 pm); otherwise …
    4. Good night
  7. ordinal.C. Steer the computer in one of five possible directions.
  8. The Metro North Evacuation Instructions. Steer the computer in one of four possible directions.
            if (you can remain inside the train) {
                    remain inside the train;
            } else if (you can go to next car through end doors) {
                    go to next car through end doors;
            } else if (you can open side door and go out) {
                    open side door and go out;
            } else {
                    go out emergency windows;   //as a last resort
            }
    

Nested if statements

  1. performancebug1.C and performancebug2.C.
    If we’re making money, performancebug1.C tells the computer to do unnecesary work.
    performancebug2.C always produces the same output as performancebug1.C, but never does unnecesary work.
    Exercise. If there is a performance bug in the following code, correct it.
            if (fahrenheit >= 100.0) {
                    cout << "It's hot as hell!\n";
            }
    
            if (fahrenheit >= 212.0) {
                    cout << "In fact, it's hot enough to boil water!\n";
            }
    
  2. performancebug3.C and performancebug4.C.
    If we’re losing money, performancebug3.C tells the computer to do unnecesary work.
    performancebug4.C always produces the same output as performancebug3.C, but never does unnecesary work.

A situation where you can avoid nested if statements

  1. and1.C: nested ifs.
  2. and2.C: only need one if. && means “and”; no space between the two ampersands.

Put the bigger, more complicated section of the if on the bottom

We can easily flip an if/else upside down, taking advantage of three pairs of opposite operators:

  1. == vs. != (“equals” vs. “not equals”)
  2. < vs. >= (“less than” vs. “greater than or equal to”)
  3. > vs. <= (“greater than” vs. “less than or equal to”)
In the following example, the big section of the if/else is in yellow, the smaller section is in orange.

        if (harris == trump) {
		cout << "The Electoral College is hung!\n";
		cout << "What do we do now?\n";
        } else {
		cout << "The Electoral College has reached a decision.\n";
        }
        if (harris != trump) {
		cout << "The Electoral College has reached a decision.\n";
        } else {
		cout << "The Electoral College is hung!\n";
		cout << "What do we do now?\n";
        }

It is especially important to put the big section on the bottom when the big section contains another if statement:

        if (n >= 0) {
		if (n == 0) {
		        cout << "The number is zero.\n";
		} else {
		        cout << "The number is positive.\n";
		}
        } else {
		cout << "The number is negative.\n";
        }
        if (n < 0) {
		cout << "The number is negative.\n";
        } else {
		if (n == 0) {
		        cout << "The number is zero.\n";
		} else {
		        cout << "The number is positive.\n";
		}
        }
because now we can easily change it to a chain of else/ifs:
        if (n < 0) {
		cout << "The number is negative.\n";
	} else if (n == 0) {
	        cout << "The number is zero.\n";
	} else {
	        cout << "The number is positive.\n";
	}

Side by side, without color:

	//Original

	if (n >= 0) {
		if (n == 0) {
		        cout << "The number is zero.\n";
		} else {
		        cout << "The number is positive.\n";
		}
        } else {
		cout << "The number is negative.\n";
        }
	//More straightforward, don't you think?

	if (n < 0) {
		cout << "The number is negative.\n";
	} else if (n == 0) {
	        cout << "The number is zero.\n";
	} else {
	        cout << "The number is positive.\n";
	}

Exercise. In morning1.C, do what we just did. Does this make the program easier to read and understand and check for bugs?

Anoher exercise. Unsnarl morning2.C.

switch as an alternative to if

The else/ifs in ordinal.C did not all use the same variable. Some used lastTwoDigits, and others used lastDigit. But the else/ifs in switch1.C all use the same variable (weekday) and all use the comparison ==.

  1. switch1.C. Comparing the same int variable (weekday) over and over again with == to test for equality.
  2. switch2.C. One switch statement instead of a chain of if/elses.
  3. switch3.C. Remove the breaks.

Exercise. In switch4.C, change the else/ifs to one big switch statement. Imitate what we just did in switch2.C.

An if statement in a loop

  1. product4.C: an if statement inside the for loop we saw here.
  2. checkerboard.C: draw a checkerboard. Just like rectangle.C, but with an if/else in the inner loop.
  3. toolow.C: a guessing game with hints.
    Looks like the infinite loop we saw in infinite.C, but we break out of the for loop.
    Exercise. Count how many guesses it took. See for1.C and toolow2.C.
  4. pi.C: use a Monte Carlo method to estimate the value of π from a lot of random numbers. Is there a way we could get rid of the sqrt so we could loop faster?
    		//While we iterate a billion times, show our progress.
    		if (i % 10000000 == 0) {   //Once every 10,000,000 loops,
    			cout << i << "\n";
        		}
    
  5. Non-solid flags
    1. ukraine.C and ukraine.png
      Change the size of the flag.
      Exercise: change 10 to nrows/2 so you only need to change one statement when you change the nuber of rows.
    2. france.C and france.png
      Exercise: change 10 to ncols/3, and change 20 to ncols*2/3, so you only need to change one statement when you change the nuber of columns.
    3. japan.C and japan.png.
      #include <cmath> for the sqrt function.
    4. usa.C and usa.png.
      This table of remainders shows how the stripes alternate between red and white.

Unfinished business with if statements

  1. An if statement in a for loop: colombia.png.
    1. colombia1.C: the comments are wrong
    2. colombia2.C: corrected the comments, put the {curly braces} in the conventional positions.
    3. colombia3.C: now we can resize the flag simply by changing the initial value of nrows. Nothing else needs to be changed.
    4. colombia4.C and colombia4.png: The top stripe is now half the height of the flag, as in the real flag of Colombia. I also used the official colors.
  2. A three-way if statement: past, present, and future. monkey1.C and monkey4.C.
    Created the variable currentYear but then didn’t use it: MonkeyHW.C.