  Javascript Tutor - Lesson 24

Exercise: Using my random number code, write a script that gets a random number between 1 and 100 when you click on a link. If the number returned is less than 50, throw up one message ("Hey, 32 is less than 50."). If it's 50 or greater, throw up an alternate message ("Yo, 77 is greater than or equal to 50.").

Here is a solution.

Exercise: Add a for statement to loop through the thing five times with every click of the link.

Here is a solution.

Exercise: Now, instead of looping five times, have it loop a random number of times (between 1 and 8). Before the loop starts, throw up an alert box stating "I will execute the loop X times.", X being the random number between 1 and 8, then execute the loop X times. Confusing? Probably, but hey, we're way beyond Hello World and I did warn you that things could get rough. Besides, if you've made it this far, and you at least have half a clue what you're doing, then I'd say you're doing just fine! Keep plugging away!

Here is a solution.

Exercise: Alter your last exercise to loop a random number of times between 4 and 9 rather than 1 and 8. Do not alter the random number generator. Use getRandom() exactly as-is for both tasks.

Here is a solution.

This is an example of creative problem solving. I've told you that programming is an exercise in logic. Well, it's just as much an exercise in problem solving... how to trim that square peg so it fits neatly into the round hole.

Here is a simple function that might come in handy from time to time. Send it three numbers and it averages them...

```function myAverager(num1,num2,num3)
{
averaged = ( (num1*1) + (num2*1) + (num3*1) ) / 3;
}
```

(We multiply each number by 1 just in case the browser thinks numX is a string. If we don't, 13 + 39 might end up as 1339)

Notice that right now, the function simply performs the arithmetic. It doesn't return anything. We can make it return "averaged" by adding the following line...

```function myAverager(num1,num2,num3)
{
averaged = ( (num1*1) + (num2*1) + (num3*1) ) / 3;
return averaged;
}
```

Or even more simply...

```function myAverager(num1,num2,num3)
{
return ( (num1*1) + (num2*1) + (num3*1) ) / 3;
}
```

Exercise: Using the myAverager() function above without any changes, create a script with three text input boxes and a button. When the button is pressed, an alert box is thrown up that says something like...

```The average of 10, 22 and 13 is 15.
```

Your solution should be to grab the three values, send them to myAverager() and pop up an alert box with the answer.

Here is a solution.

Exercise: Make your last exercise round the answer to two decimal places.

Here is a solution.

 Javascript Tutor Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Javascript Authoring Guide      JavaScript FAQ HTML 4.0 Reference      Google Groups (Advanced Search) 