Script Example: Body Mass Index

Home, Up: Scripts

 

On the first age 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 less than 10, it cannot be centimeters and 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

 

In the last line pounds get converted to kg, inches get divided by 12 and added to feet (the variable $height) and the result gets converted to meters, then the body mass index gets calculated (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: the SKIP command gets executed when height was entered in centimeters (that is, when $height is larger than 10 and thus the IF ... condition was 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.

 

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

 

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