Working with Loops

Up to now each line of code in your JavaScript program has been run just once. You need to create a code that runs this JavaScript an indeterminate number of times. To provide the program with this capability, you must use a program loop. A loop is a set of instructions that is executed repeatedly. There are two types of loops: loops that repeat a set number of times before quitting, and loops that repeat until a certain condition is met. You will create the first type using a For statement.

The For loop allows you to create a group of commands that will react like a counter, tracking the number of times the command block has run. The general syntax of the For loop is:

for(start; stop; update) {

JavaScript Commands

}

where start is the starting value of the counter, stop is the ending value of the counter or the condition under which the loop quits, and update specifies how the counter changes in value each time the command block is executed. The command block in the For loop is set off by curly braces {}. For more information on For loop commands, refer to pages 7.31-7.32 in your textbook.

The Wile loop runs a command group as long as a specific condition is met. The general syntax of the While loop is:

while(condition) {

JavaScript Commands

}

where condition is an expression using logical or comparison operators that can be either true or false. As long as the condition is true, the group of statements will be executed by JavaScript.

With an brief understanding of program loops (for a more extensive explanation, see tutorial 7 in your textbook), you are ready to modify the Xmas/days function so that is works for any day of the year.

Find the line that reads MonthCount[11]=30; and insert a blank line under it and type the following:

var MonthTotal=0

for (i=Month;i<12;i++) {

MonthTotal = MonthTotal+MonthCount[i];

}

Change the line: var DayCount = (25 - Day) + MonthCount[10] + MonthCount[11]; to:

var DayCount = (25 - Day) + MonthTotal;

 

Using the If Statement

The If statement has the following general syntax:

if(condition){

JavaScript Commands

}

where condition is an expression that is either true or false.

For leap year, an expression should be entered so that the value returned is not one day off.

Below the line: "MonthCount[11]=30;" insert the following lines (indented to make your code easier to follow):

if(Year % 4 == 0) {

MonthCount[2]=29;

}

Just Plain Stupid