## Derek Bridge

### Department of Computer Science, University College Cork

Aims:

• to learn how to write cascading conditionals
• to learn to reason about whether programs are equivalent
• to learn to reason about their relative efficiency, clarity, and maintainability

• By using `elseif`, we can have a conditional with more than two arms:

``` if ( Boolean expression ) {    zero, one or more statements } elseif ( Boolean expression ) {    zero, one or more statements } else {    zero, one or more statements } ```

• You can have as many `elseif`s as you need

# Example

```if ( \$grade < 40 )
{
echo '<p>Fail</p>';
}
{
echo '<p>Pass degree</p>';
}
else
{
echo '<p>Honours degree</p>';
}```

# Class exercise

• Describe how would you alter the previous program to handle the following criteria from the National University of Nerdland
less than 40%Fail
40% and above but less than 45%Pass
45% and above but less than 50%Third class Hons
50% and above but less than 60%Second class Hons Grade 2
60% and above but less than 70%Second class Hons Grade 1
70% and aboveFirst class Hons

# Another example

• Following the election of a new Nerdlandish government, tax is now computed as follows
If your salary is overBut not overYour whole salary is taxed at
02000015%
200005000028%
5000045%
• Suppose `tax.html` contains this form:
```<form action="tax.php" method="get">
<input type="salary" name="salary" value="0" />
<input type="submit" />
</form>```
• The next slide shows one possible version of `tax.php`

# Version 1 of `tax.php`

```\$salary = (int) \$_GET['salary'];
if ( \$salary <= 20000 )
{
\$tax = 0.15 * \$salary;
}
elseif ( \$salary <= 50000 )
{
\$tax = 0.28 * \$salary;
}
else
{
\$tax = 0.45 * \$salary;
}
echo "<p>Send us {\$tax} eurines or your first-born child</p>";```

# Class exercise

• For each of versions 2-5,
• Is it equivalent to version 1, i.e. does it give the same output for all inputs as version 1?
• If you think they are not equivalent, give a piece of test data on which they would differ
• If you think they are equivalent, is one of them more efficient? clearer? more maintainable?

# Version 2

```if ( \$salary <= 50000 )
{
\$tax = 0.28 * \$salary;
}
elseif ( \$salary <= 20000 )
{
\$tax = 0.15 * \$salary;
}
else
{
\$tax = 0.45 * \$salary;
}```

# Version 3

```if ( 0 <= \$salary && \$salary <= 20000 )
{
\$tax = 0.15 * \$salary;
}
elseif ( 20000 < \$salary && \$salary <= 50000 )
{
\$tax = 0.28 * \$salary;
}
elseif ( 50000 < \$salary )
{
\$tax = 0.45 * \$salary;
}```

# Version 4

```if ( 20000 < \$salary && \$salary <= 50000 )
{
\$tax = 0.28 * \$salary;
}
elseif ( 0 <= \$salary && \$salary <= 20000 )
{
\$tax = 0.15 * \$salary;
}
elseif ( 50000 < \$salary )
{
\$tax = 0.45 * \$salary;
}```

# Version 5

```if ( 0 <= \$salary && \$salary <= 20000 )
{
\$tax = 0.15 * \$salary;
}

if ( 20000 < \$salary && \$salary <= 50000 )
{
\$tax = 0.28 * \$salary;
}

if ( 50000 < \$salary )
{
\$tax = 0.45 * \$salary;
}```