Names:                                                                   

If Statements and Decisions, COSC 106 A, Tom Linton, April 23, 2004

Introduction

One very powerful and common control structure in programming that we haven't seen yet is the conditional structure. This aspect of programming will allow us to both ask and answer questions, and then respond differently based on the result of these questions or tests. Our tests will all yield boolean values (true or false). Some common tests result from mathematical comparisons, expressions like x > 5, or x <= 2, which, for each value of x are either true or false. The goal of today's activity will be to familiarize ourselves with this conditional control structure in JavaScript.

Basic Syntax

Suppose we had implemented a web-page that played a simple dice rolling game. The user was initially given a score of 5, and was allowed to roll a die against the computer. The computer would then roll another die, and the highest roll would win (the computer wins all ties). If the computer won a roll, the player would have one credit subtracted from their score. If the user won, they would have one credit added to their score. One key aspect of the JavaScript code behind this game would be the need to compare the two rolls, decide who won, and either add or subtract one credit from the user's score. That is, we need to run a test and execute different code based on the results of that test. The JavaScript command that allows us to do this is the if statement. Here is the basic syntax for an if statement (it should perhaps be called an if block, since it normally includes several statements, but there is some advantage to thinking of the entire block as a single command, so if statement is used most of the time).

if ( test )
{
   statements to perform if the test is true
}
else
{
   statements to perform if the test is false
}

It is important to realize that either the true statements are executed and the false statements are skipped, OR the true statements are skipped and the false statements are executed. You will never execute both groups of statements. It is common to refer to the collection of statements to perform when the test is true as the true block, and the collection of statements to perform when the test is false as the false block.

Examples

Assuming we're attempting to perform the key aspect of our dice rolling game above, here is what we need to do: When the computer's roll is bigger than or equal to the user's roll, we want to subtract one from the user's score. Our test will be computerRoll >= userRoll. If the test is false, then it must be the case that the user's roll is larger than the computer's roll (if x is NOT bigger than or equal to y, then y is bigger than x), so we should add one to the user's score. Once we've updated the user's score, we need to display its new value on our form. The actual code might look like this:


if (computerRoll >= userRoll)
{
   score = score - 1;
}
else
{
   score = score + 1;
}
document.myForm.scoreBox.value = score;

  1. In the space below, alter the code above to fit the following modification of this game: The user wins all ties, but when the computer wins a roll, the user loses 2 credits (if the user wins a roll, they still get one credit added to their score).















     

  2. One common operation required in programs is calculating the bigger of two numbers (i.e. the maximum of 2 values). We might accomplish this with a function named max, which takes the 2 numbers as inputs (parameters) and returns the larger of the 2 values (it can return either one if they are equal). Here is an algorithm for this function (I'm assuming the formal parameters are called num1 and num2):
         if num1 is bigger than or equal to num2, return num1, otherwise return num2.
    Complete the body of this function below using an if statement.
         function max(num1, num2)
         {











         }

     

  3. Finding the maximum of 3 numbers with if statements gets pretty messy (you need to run several tests before you know which is the maximum). Consider the following function definition (it uses your max function above):
    function max3(a, b, c)
    {
       var m = max(a, b);
       return max(m, c);
    }

    1. What is the result of the function call max3(2,-5,8)?








       

    2. What is the result of the function call max3(100, 786, -2)?










       

    3. Explain why max3(x,y,z) always returns the maximum of x, y, and z.
















       

  4. Sometimes the decisions we make have more than 2 possible outcomes. Suppose we have another dice game where only the user rolls. If they roll a 1 or 2, they lose 2 credits. If they roll a 3 or 4, they lose one credit. If they roll a 5, they win one credit, and if they roll a 6, they win 3 credits. While we could code this using four separate if statements (most would have an empty false block, and, for example, the first test would determine if the roll was a 1 or 2, etc.), there is a better way. The else-if block allows us to nest if statements, when we have more than 2 possible outcomes. The basic syntax looks like this:
       if (test 1)
       {
          true block 1;
       }
       else if (test 2)
       {
          true block 2;
       }
       else if (test 3)
       {
          true block 3;
       }
          and so on
       else if (last test)
       {
          last true block;
       }
       else
       {
          block if all tests are false;
       }
       first statement after if-else block;

    JavaScript will execute this block as follows. It starts by evaluating test 1. If test 1 is true, the commands in true block 1 will be executed and then JavaScript will jump to the first statement after the if-else block (skipping all other blocks and all other tests). If test 1 is false, it will run test 2. If test 2 evaluates to true, block 2 is run and then JavaScript jumps to the first statement after the if-else block. When test 2 evaluates to false, JavaScript will run test 3, and so on. If test 1, test 2, ... , and last test are all false, JavaScript will execute the all false block and then move to the statement after the if-else block. It is advantageous to utilize the fact that test 2 is run, only after we know test 1 was false (otherwise test 2 would have skipped). This can make expressing your tests much simpler. The code for our modified dice game might look like this:

       if (userDice <= 2)
       {
          score = score - 2;
       }
       else if (userDice <= 4) //we know userDice cannot be <= 2 here, so this is correct
       {
          score = score - 1;
       }
       else if (userDice == 5) //tests for equality use the double equals sign
       {
          score = score + 1;
       }
       else //if we get here, we know they rolled a 6
       {
          score = score + 3;
       }
       document.myForm.scoreBox.value = score;

    Write an else-if block that adds one to score1 when num1 > num2, adds one to score2 when num2 > num1, and subtracts one from both socre1 and score2 when num1 is equal to num2. You may assume that all of these variables are already declared and initialized.




























     

  5. In the board game RISK, players simulate wars by rolling dice. One player is the attacker and one player is the defender. When both players have lots of armies, the attacker rolls 3 dice while the defender rolls 2 dice. The largest roll of the attacker's 3 dice is compared to the largest roll of the defender's dice, and the second largest roll of the attacker's dice is compared to the second largest roll (which is also the smallest roll) of the defender's dice. Each of these comparisons results in the player with the lower roll losing an army. The defender wins all ties. As an example, suppose that the attacker rolls 3, 6, 2, while the defender rolls 3, 4. The first comparison is between the attacker's 6 and the defender's 4. The attacker's 6 is larger so the defender loses one army. The second comparison is between the attacker's 3 and the defender's 3, which is a tie. The defender wins all ties, so the attacker loses an army for the second comparison. In this case, each player loses one army. I have written a web page that implements the backbone structure for simulating this type of "war". As it is now, there are buttons that roll the dice, and an auxiliary function, named secondLargest, that returns the second largest value of any 3 numbers. This auxiliary function won't work until you add code for your max and max3 functions (since secondLargest calls those functions). A results button displays some output in a textarea named outputBox. Your job is to complete this page, so that when the results button is pressed, the values of the dice are read in, and a message similar to:

    When the attacker rolls 3, 6, 2, and the defender rolls 3, 4,
    the first comparison results in the defender losing an army
    and the second comparison results in the attacker losing an army.

    is added to the top of the output area. You will also need to define a function which returns the minimum (second largest) of any 2 input numbers. My backbone web-page is located at http://www.central.edu/homepages/lintont/classes/spring04/webprog/chp12/risk.htm, and is available on Blackboard and the this class's webpage. When you complete the risk game web-page, submit it via blackboard's assignment area.