Selection and Flow Charts PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Selection and Flow Charts

Some students find flow charts helpful to understand if statements. Below are
three code examples from the textbook with corresponding flow charts. To help
you better understand if statements, read each code example and compare it to
its corresponding flow chart.
It is often useful to write one if statement inside another if statement or inside
the else part of an if statement. Consider the problem to write a program that
reads from the keyboard the total weekly sales for a sales person and then outputs
the sales person’s commission according to this table.

If the sales amount is greater than or equal And the sales amount is less than Then the commission rate is
to

0 $300 0%

$300 $600 2.0%

$600 $1000 2.5%

$1000 ∞ 3.0%

This can be easily written using nested if statements as shown in the following
code example.
Example 11
var sales = parseFloat(document.getElementById('sales'));
var rate;
if (sales < 300) {
rate = 0;
}
else if (sales < 600) {
rate = 0.02;
}
else if (sales < 1000) {
rate = 0.025;
}
else {
rate = 0.03;
}
var commission = sales * rate;
var output = 'The employee earned ' + commission;
document.getElementById('commission').innerHTML = output;
As another example, consider a sports team that wants to provide discounted
tickets to students and senior citizens and that wants to reward loyal fans that
attend multiple games according to this table.

Age Games Attended Ticket Price

0-17 0-5 $8.00

0-17 6-10 $6.00

0-17 11 and up $5.00

18-54 0-10 $10.00

18-54 11 and up $8.00

55 and older 0-10 $8.00

55 and older 11 and up $6.00

This could also be solved using nested if statements.


Example 12
function ticketPrice() {
var age = parseInt
(document.getElementById('age').value);
var gamesAttended = parseInt
(document.getElementById('games').value);
var price;
if (age < 18) {
if (gamesAttended < 6)
price = 8.0;
else if (gamesAttended < 11)
price = 6.0;
else
price = 5.0;
}
else if (age < 55) {
if (gamesAttended < 11)
price = 10.0;
else
price = 8.0;
}
else {
if (gamesAttended < 11)
price = 8.0;
else
price = 6.0;
}
document.getElementById('price').innerHTML = price;
}
Sometimes nested if statements can be a little tricky as shown in this example
which has two if statements but only one else clause.
Example 13
var div = document.getElementById('output');
if (x < 2) {
if (y > 8) {
div.innerHTML = 'Hello';
}
}
else {
div.innerHTML = 'Goodbye';
}
Copyright © 2019 by Brigham Young University - Idaho. All Rights Reserved.

You might also like