Script Example: Body Mass Index

Home, Up: Scripts

 

On the first page in this chapter we created our first script, which prompts for height and weight and calculates the body mass index, rounding it to one digit after the decimal point -- here is it again:

 

PROMPT $cm enter height in cm:

PROMPT $kg enter weight in kg:

$kg $cm 100 / SQ / 1 ROUND

 

To demonstrate the use of IF ... conditions, let us modify the script so that it accepts input not only in centimeters and kilograms, but also in feet, inches and pounds.

In this example we take advantage of the fact that heigth measurement numbers in centimeters and feet do not overlap -- if the number is larger than 10, it has to be centimeters, otherwise it has to be feet.

 

PROMPT $height enter height in cm or in ft (without inches):

IF $height 10 >> THEN PROMPT $kg enter weight in kg:

ALSO: $kg $height 100 / SQ / 1 ROUND

ELSE: PROMPT $in enter inches:

ALSO: PROMPT $lb enter weight in pounds:

ALSO: $lb :kg $height $in 12 / + :m SQ / 1 ROUND

 

If the condition $height 10 >> is true ($height is larger than 10) then the user is prompted for weight in kg, and the following ALSO: line computes the BMI.

If the condition is not true (that is, the value entered is not larger than 10), then the ELSE: line and the two ALSO: lines that follow it are executed.

In that case the last line converts pounds to kg, then it divides inches by 12 and adds that fraction to the feet (the variable $height), convertes the result to meters, squares it, and then divides the weight by that number (weight in kg divided by the square of height in m).

 

There are several other ways how this script could be written -- for instance, we could use the SKIP command instead of the ELSE: line and its two connected ALSO: lines:

 

PROMPT $height enter height in cm or in ft (without inches):

IF $height 10 >> THEN PROMPT $kg enter weight in kg:

ALSO: $kg $height 100 / SQ / 1 ROUND

ALSO: SKIP

PROMPT $in enter inches:

PROMPT $lb enter weight in pounds:

$lb :kg $height $in 12 / + :m SQ / 1 ROUND

 

The SKIP command gets executed when height was entered in centimeters (that is, when $height is larger than 10 and thus the IF ... condition is met), so that the lines that follow are only reached when this condition was not met, that is, when $height had been entered in feet.

If you run either version of this script, assuming you use feet, inches and pounds you will get something like this:

 

? _bmi

  Enter height in cm or in ft (without inches):

? $height = 5

  Enter inches:

? $in = 11

  Enter weight in pounds:

? $lb = 160

= 22.3

 

We will return to this example in the context of loops.

 

Home, Up: Scripts, Prev: Introduction to Scripts, Next: Script Example: Centimeters to Feet and Inches