For Loop and Switch Statement

  1. The for loop
    1. Pre-test loop that can replace any while loop
    2. Popular with programmers because it tells us three important things all on one line: 1) where the loop begins, 2) where it ends, and 3) how it gets from the beginning to the end
    3. Format:
      for (init; test; alteration)
      {
      	body
      }
      
    4. Example:
      // While loop that counts from 1 to 5
      c = 1;
      while (c <= 5)
      {
      	cout << c;
      	c++;
      }
      
      // Equivalent for loop
      for (c = 1; c <= 5; c++)
      	cout << c;
      
    5. Execution
      1. Initialization statement executes first
      2. Then the test for completion
      3. Then the body of the loop
      4. Then the alteration of the test condition
      5. Then the test, body, alteration, test, body, alteration, etc. until the test is false
      6. The init statement is only executed one time!
  2. The switch statement
    1. Helps simplify nested if-else statements that involve simple equality
    2. Can only be used with integers and character data types
    3. Example
      // Using nested if-else statements
      
      char color;
      cout << "Favorite color (B for Blue, R for Red, G for Green)? ";
      cin >> color;
      
      if (color == 'B')
      	cout << "You like blue";
      else if (color == 'R')
      	cout << "You like red";
      else if (color == 'G')
      	cout << "You like green";
      else 
      	cout << "You like something else";
      	
      // Equivalent switch statement
      switch (color)
      {
      	case 'B':
      		cout << "You like blue";
      		break;
      	case 'R':
      		cout << "You like red";
      		break;
      	case 'G':
      		cout << "You like green";
      		break;
      	default:
      		cout << "You like something else";
      }
      
    4. default statement is optional
    5. break is necessary or statements inside the switch will continue to execute
      switch (color)
      {
      	case 'B':
      		cout << "You like blue";
      		// break;
      	case 'R':
      		cout << "You like red";   // This executes if color was 'B'!	
      	...
      }
      
    6. By purposefully leaving out break statements, multiple case statements can be grouped together
      // Case-insensitive matching
      switch (color)
      {
      	case 'B':
      	case 'b':
      		cout << "You like blue";
      		break;
      	case 'R':
      	case 'r':
      		cout << "You like red";
      		break;
      	case 'G':
      	case 'g':
      		cout << "You like green";
      		break;
      	default:
      		cout << "You like something else";
      }