Lesson # 7 - Branching and Decisions

# 7 Branching and Decisions

# 7 Review Questions # 7 Assignment

Most of our work so far has been just performing statements in order. That is how most all programming languages start out. But we need to add more flexibility to our programs. Sometimes we need to have the program make a decision, then perform statements based on that decision. for example, suppose you are doing a web site to display the daily activities for your high school. But some activities are for freshmen only, and other activities are for senior only. So to personalize the page, we want to load the correct list of activities based on the user's response to an input box or a mouse click.

Conditions

The program reacts to conditions and whether they are true or false. (Note: true and false are called boolean values and are used for logical decisions.) Here is a list of conditional operators that JavaScript can respond to.

Equals (==)

We use a double equal sign, since a single = means 'assign the value on trhe left to the variable on the right'. This operator can compare two quantities and return true if they are equal, and false otherwise. Note that ("09" ==09 ) will be false because we are comparing a string of two characters with a number value. (1 ==4*.25) will evaluate to true because the multiplication will be done before the comparison. ("bob" =="Bob") will be false, since upper and lower case letters are considered different letters.

Not Equals ( !=)

The exclamation point mean NOT in many programming languages. This operator returns true only when the two items being compared are NOT equal.

Less Than (<) and Greater Than (>)

Numbers are compared just as you would expect, with the Less Than condition being true whenever the left side is a smaller number than the right side. Strings are compared in alphabetical order, so "cat" is less than "dog", and since upper case letters have a lower code value than lower case letters, "Cat" is considered less than "cat". Note that these operators will return false if the two quantities being compared happen to be equal.

Less Than or Equals (<=) and Greater Than or Equals (>=)

These two work like their cousins < and > except they also return true if the two quantities being compared are equal, as described above.

 

If Statements

If statements give us just a one-way branch, meaning when the condition is true, we perform an action, otherwise we skip it and go on to the next statement. Study these examples and the comments to see how they work.

var age = 16;

if (age < 16) // condition is false

    alert("Please let us know when you turn 16."); // does not execute

alert("This alert will always display.");

Sometimes we need to have several statements execute when the condition test true. We need to use the braces {...} to enclose a block of code, as shown in this example taken from a dice game, where a player would win if the dice total is a 7 or an 11. This uses the || operator to mean 'OR'. So if either a 7 or an 11 come up, it is a winning roll.

var diceTotal = die1 + die2;
if ( (diceTotal == 7) || (diceTotal == 11) ) // player wins this roll
    { // this entire block of code will execute
      totalMoney += betAmount;  // player wins his bet
      alert(" Way to go!  You won.");
    } // end of block

 

If...Else Statements

In the example above, the game should actually include some statements that execute when the player has lost the roll. In this game, the player will lose if the roll is a 2, 3, or 12, But if the roll is not a 2, 3, 7, 11, or 12, then the game goes on in a different phase with that number as a 'point' number. We are going to create a two-way branch. We do action A if the condition is true, and we do action B otherwise. The word else means 'otherwise'. This example shows an if...else structure, with another if...else structure nested inside it. We can nest all the branching and looping structures to do the jobs we need. But be very careful to use the {...} braces whenever you need a block of code. In general, it is good practice to use them all the time. It is a common programming error to forget the braces, then wonder why the block of code does not execute correctly.

var diceTotal = die1 + die2;
if ( (diceTotal == 7) || (diceTotal == 11) ) {// block starts here
     // this entire block of code will execute when player wins
      totalMoney += betAmount;  // player wins his bet
      alert(" Way to go!  You won.");
} // end of block
else { // new block handles when player does not win
     if ( (diceTotal == 2) || (diceTotal == 3)|| (diceTotal == 12) ) { // new if block
         totalMoney -= betAmount; // player lost his bet, poor sap
         alert("Sorry, you lost.");
      }  // end of this if block 
      else 
          // no {  } braces needed here, but it's a good idea to put them anyway
          continueRollingPhase(diceTotal); // send the total dice roll to this function.
} // end of else block

Take a moment to notice the way the lines are indented. Learning to indent like this will keep you sane when you begin troubleshooting your programs. It is also a sign to other programmers or web developers that you know what you are doing and take pride in doing it right.

Multi-way Branching with Switch Statements

Here is another way to look at how we might handle the problem of personalized list of activities based on what class the user enters into an input. The possible valid values are 9 through 12, so there are 4 possible grades that should have a list of activities. But we should also "idiot-proof" our program for those users who leave the input blank or enter a bogus grade such as 57. We use a switch to handle anything more than a 2 way branch that is based on the same variable or expression.

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch statement looks as follows:

switch (expression){ case label : statement; break; case label : statement; break; ... default : statement;}


The program first looks for a label matching the value of expression and then executes the associated statement. If no matching label is found, the program looks for the optional default statement, and if found, executes the associated statement. If no default statement is found, the program continues execution at the statement following the end of switch.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

var class = parseInt(this.value);// we get the value as a string, so convert to number
switch (class) {

     case 9:

        displayFroshList(); // calls a function to open a new freshman window
         break; // this statement exits the switch construct and continues with program
    case 10:

         displaySophList(); // calls a function to open a new sophomore window
         break;
    case 11:

       displayJuniorList(); // calls a function to open a new junior window
        break;
    case 12:

       displaySeniorList(); // calls a function to open a new senior window
        break;
    default: // what to do if not valid grade

        alert("Please enter a valid grade level 9 - 12.");

} // end of switch
alert("Remember that class meetings are manditory!");// appears after switch exits

Sample Cartoon Quiz Program

Let's write a little quiz program about some popular cartoon characters. This program is found in the file cartoon.htm. Open it with your browser to see how it works. Study the functions in the <head> section that score each question. You will also want to access its source code to do the Assignment 7 problem.

<html>
         <head>
         <title> Cartoon Quiz </title>
         <script language = "JavaScript" >
         <!-- hide from old browsers
         function scoreQ1(response) {
         if (response == "a") 
             alert("Incorrect answer.");
         if (response == "b") 
             alert("Good, you know your mice!");
         if (response == "c") 
             alert("Incorrect answer.");
         if (response == "d") 
             alert("Incorrect answer.");
         } // end scoreQ1         
function scoreQ2(response) {
           if (response == "a") 
               alert("Incorrect answer.");
           if (response == "b") 
               alert("Incorrect answer.");
           if (response == "c") 
               alert("Correct, you lucky dog!");
           if (response== "d") 
               alert("Incorrect answer.");
           } // end scoreQ2
function scoreQ3(response) {
           if (response == "a") 
               alert("Incorrect answer.");
           if (response == "b") 
               alert("Incorrect answer.");
           if (response == "c") 
               alert("Right, Winnie and Tigger forever!.");
           if (response == "d") 
               alert("Incorrect answer.");
           } // end scoreQ3
function scoreQ4(response) {
           if (response == "a") 
               alert("Incorrect answer.");
           if (response == "b") 
               alert("Incorrect Answer.");
           if (response == "c") 
               alert("Right, and Tweety gets away every time.");
           if (response == "d") 
               alert("Incorrect answer.");
           } // end scoreQ4
//end hiding-->
           </script>
</head>
<body>
           <h1> Test Your Cartoon Knowlege </h1>

           <b> 1. What is the name of Walt Disney's famous mouse's girlfriend?            </b><br>
           <input type="radio" name="ques1" value="a"  onClick = "scoreQ1(this.value);"> Mickey Mouse
           <input type="radio" name="ques1" value="b"  onClick = "scoreQ1(this.value);"> Minney Mouse
           <input type="radio" name="ques1" value="c"  onClick = "scoreQ1(this.value);"> Betty Boop
           <input type="radio" name="ques1" value="d"  onClick = "scoreQ1(this.value);"> Alice
           <br><br><br>
<b> 2. Pluto is a dog. What is Goofey? </b><br>
           <input type="radio" name="ques1" value="a"  onClick = "scoreQ2(this.value);"> a gorilla
           <input type="radio" name="ques1" value="b"  onClick = "scoreQ2(this.value);"> a computer Teacher
           <input type="radio" name="ques1" value="c"  onClick = "scoreQ2(this.value);"> a dog
           <input type="radio" name="ques1" value="d"  onClick = "scoreQ2(this.value);"> a chipmunk
<br><br><br>
           <b> 3. Who is Winnie the Pooh's best friend? </b><br>
           <input type="radio" name="ques1" value="a"  onClick = "scoreQ3(this.value);"> Goofey
           <input type="radio" name="ques1" value="b"  onClick = "scoreQ3(this.value);"> Eyore
           <input type="radio" name="ques1" value="c"  onClick = "scoreQ3(this.value);"> Tigger
           <input type="radio" name="ques1" value="d"  onClick = "scoreQ3(this.value);"> Donald Duck
<br><br><br>
           <b> 4. Sylvester the Cat is always trying to eat what?</b><br>
           <input type="radio" name="ques1" value="a"  onClick = "scoreQ4(this.value);"> Mickey Mouse
           <input type="radio" name="ques1" value="b"  onClick = "scoreQ4(this.value);"> Minney Mouse
           <input type="radio" name="ques1" value="c"  onClick = "scoreQ4(this.value);"> Tweety Bird
           <input type="radio" name="ques1" value="d"  onClick = "scoreQ4(this.value);"> Pepperoni Pizza
           </body>
           </html>

 

Return to Top of Page | Back to Main Menu