Lesson 7: Nested If Statements

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]


#include <iostream>
using namespace std;
 
 
int main(){
 
  //9>8 == true == 1, 1>7 ==false
 
  //nested if's
  //if inside of an if
  //Homework:  If the salesperson made less than 4000 in a month, they do not get any bonus
  //Fix all the if statements so that they work properly
  //Bonus: If the person made over 15000, they get a 100 bonus added to their check after commision has been factored in.
        // ==, < , > < !=, >=, < =, !, &&, ||
 
 
 
  double pay = 0.0, comission = 0.0, sales = 0.0;
  cout << "Enter the salesperson's sales for the month: ";
  cin >> sales;
 
  if (sales > 4000 && sales &lt;5000){
    comission = 0.01;
  }
  else if (sales >5000 && sales < 6000){
    comission = 0.02;
  }
  else if (sales >6000 && sales < 7000){
    comission = 0.03;
  }
  else if (sales >7000 && sales < 8000){
    comission = 0.04;
  }
  else if (sales >8000 && sales < 9000){
    comission = 0.05;
  }
  else{
    comission = 0.08;
  }
 
  pay = 400;
 
 
  //cout << "Pay = " << pay << " -- comission = " << comission << "\n\n";
  cout << "\nThe salesperson's pay for the month is: " << (pay*(1 + comission)) << endl;
 
  system("PAUSE");
  return 0;
}


[/spoiler]

Homework: http://beginnerscpp.com/forums/index.php/topic,61.0.html



Nested If Statements
Despite the title of this lesson, I did very little in the way of showing you nested if statements, and the reason why I opted to teach it this way was because I wanted to show that intelligent program design can get away from nesting. Sometimes nesting is unavoidable, and for those cases the following syntax remains true

if(firstConditional){
     if(secondConditional){
          //stuff Happens here
     }
     else{
          //Stuff can also happen here
     }
}
else{
     //If the first if was false
}

The only thing that I can advise you on when it comes to nested if statements is that you should be EXTREMELY strict when it comes to your indenting. Furthermore, some people like to document their code to remind them which if statement they are in, however I find this type of commenting somewhat excessive. A comment here and there to remind us what something does, or what we’re testing is fine, but when you see something like this, it’s a bit excessive.

if( condition ){//First if statement
     if( condition2){//inside second if statement
            ...
      }//end inner if
}//end first if
else{//outer else statement
     ...
}//end else

While I understand the intention of the person that made the comments, it actually adds to confusion over stating the implied usage on a single line like this:


//The following if statements will determine .... and if not they will go to the else and ...
if( condition ){
     if( condition2){
            ...
      }
}
else{
     ...
}