Nate E.
Nate E.

Reputation: 134

for loop (but one variable needs an if)

I need to create a javascript that creates the following output (think of it as a tuition coupon book) ** Per assignment directions **

Grade would increment up to 8, classroom would increment up to 3, month would increment up to 9.

The problem I have is "grade 0 tuition has to be 80 per month" vs "grades 1- 8 are 60 per month".

How do I account for the different tuitions in my for loop code? Here is what I have so far ...

var grade = 0;
var rooms = 1;
var month = 1;
var tuition = 60;

for (grade = 0; grade <= 8; grade++) {
  for (rooms = 1; rooms <= 3; rooms++) {
    for (month = 1; month <= 9; month++) {
      document.write("Grade# " + grade + " Classroom# " + rooms + " Month: " + month + " Tuition $" + (tuition * grade) + "<br/>");
    }
  }
}

thanks in advance.

Upvotes: 1

Views: 67

Answers (3)

David Barker
David Barker

Reputation: 14620

Just check the grade and work out the tuition.

var grade = 0;
var rooms = 1;
var month = 1;

function getTuition(grade) {
    // Will return 80 if grade is less than or equal to 0
    // otherwise it will return 60
    return grade > 0 ? 80 : 60;
}

for (; grade <=8; grade++) {
    for (; rooms <=3; rooms++) {
        for (; month <=9; month++) {
            document.write("Tuition $" + getTuition(grade)  + "<br/>");
        }
    }
}

Upvotes: 1

DMO-NZ
DMO-NZ

Reputation: 71

How about putting the room and month loop code into a function, which takes the grade and tuition fee as arguments:

    function writeInformation(grade, tuition) {
        var rooms, month;
        var cost; // to track total cost of tuition.
        for (rooms = 1; rooms <= 3; rooms++) {
            for (month = 1; month <= 9; month++) {
                cost = tuition * month;
                document.write("Grade# " + grade + " Classroom# " + rooms + " Month: " + month + " Tuition $" + cost + "<br/>");
            }
        }
    }

Then, we can reuse the function to account for the different grade and tuition costs.

    var grade = 1;
    writeInformation(0, 80); // grade 0, tuition 80

    // grades 1-8, tuition 60
    for(grade = 1; grade <= 8; grade++) {
        writeInformation(grade, 60);
    }

With this, you avoid the need to use an if statement to check whether to change the tuition costs based on the grade or whatever.

Upvotes: 1

trincot
trincot

Reputation: 350137

Add this tuition = ... line after the first for loop starts:

for (grade = 0; grade <=8; grade++) {
    tuition = grade ? 60 : 80;

This will check if grade is non-zero. If so 60 is taken, else 80. That value is put in the tuition variable.

Upvotes: 2

Related Questions