Meeting 7
Controlling Program Flow
7.1 Homework Discussion
Professor: Did you have any trouble with your homework?
Mike: The first one wasn’t that dicult. We discovered tha t it is even possible to
write it with a single conditional operator, combined with the rema inder operator for
checking whether the num ber is divisible by two. We use the concatenation opera-
tor to make the message mo re explanatory. Parentheses are necessary be cause the
concatenation operator has pr ecedence over the conditional one. This is the code:
var valueToCheck = prompt("Enter an integer.");
document.write("The entered number is " +
(valueToCheck % 2 == 0 ? "even." : "odd."));
Professor: I like your solu tion and I see that you understand how JavaScript operators
work.
What about the second homework?
Maria: It was much harder. As a mater of fact, w e could solve it only f or numbers up
to 20.
Professor: Why 20?
Maria: OK, w e could have written the program for any number but its size would
then grow beyond the limits. Maybe we overlooked some important detail? This is
our so lution:
var x = prompt("Enter an integer greater than one.");
var counter = 0;
counter = x % 2 == 0 && x != 2 ? counter + 1 : counter;
counter = x % 3 == 0 && x != 3 ? counter + 1 : counter;
counter = x % 5 == 0 && x != 5 ? counter + 1 : counter;
127
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.140.33