How to Write a Program to Model a Simple Calculator

All useful computer programs combine three traits: they take input, process it in some way, and write output. A simple example used in many classes is to challenge students to create a simple calculator application. This requires the student to read input from a user (the operands and operator), process it to perform the calculation, and print the output back to the user. This example uses Ruby as the programming language, since it comes installed by default on both Mac and Linux computers and can be downloaded free for Windows, but the same task could be achieved with only minor changes in syntax for other languages.

Instructions

    • 1

      Open a text editor.

    • 2

      Paste the following code to retrieve the information from the user:

      puts "Enter the first number:"

      x = Float(readline)

      puts "Enter the operator (+, -, *, //):"

      opS = readline

      puts "Enter the second number:"

      y = Float(readline)

    • 3

      Paste the following code to perform the calculation:

      if opS[0].chr == "+":

      result = x + y

      elsif opS[0].chr == "-":

      result = x - y

      elsif opS[0].chr == "*":

      result = x * y

      elsif opS[0].chr == "/":

      result = x / y

      else

      puts "Invalid operator."

      end

    • 4

      Paste the following to print the results to the user:

      puts "Answer is:"

      puts result

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured