NASutils Knowledge BaseUnofficialPolski

BASIC · lesson 22 of 30 · Files and errors · bonusBuild a calculator

Put input, token, switch and a check for zero into one program.

Programming on the NAS › BASIC in 30 lessons

22-calculator.yab Download 22-calculator.yab

rem A calculator: 12 * 4, one sum on a line, empty line ends
dim part$(1)
print "Type a sum like 12 * 4. An empty line ends."
do
  line input "> " line$
  if line$ = "" break
  if token(line$, part$(), " ") <> 3 then
    print "Type number, sign, number with spaces"
    continue
  endif
  a = val(part$(1))
  b = val(part$(3))
  switch part$(2)
    case "+": print a + b: break
    case "-": print a - b: break
    case "*": print a * b: break
    case "/"
      if b = 0 then
        print "You cannot divide by zero"
      else
        print a / b
      endif
      break
    default
      print "Signs: + - * /"
  end switch
loop
print "Bye"

Terminal

$ yabasic 22-calculator.yab
Type a sum like 12 * 4. An empty line ends.
> 12 * 4
48
> 7 / 2
3.5
> 5 / 0
You cannot divide by zero
> 5
Type number, sign, number with spaces
> 
Bye

Exercise

Add ^ as a fifth sign.