Programming Fundamentals/Conditions/BASIC
Appearance
(Redirected from Computer Programming/Conditions/BASIC)
conditions.bas
[edit | edit source]' This program asks the user to select Fahrenheit or Celsius conversion
' and input a given temperature. Then the program converts the given
' temperature and displays the result.
'
' References:
' https://www.mathsisfun.com/temperature-conversion.html
' https://en.wikibooks.org/wiki/BASIC_Programming
DECLARE SUB Main
DECLARE FUNCTION GetChoice$
DECLARE FUNCTION GetTemperature(Scale$)
DECLARE FUNCTION CalculateCelsius(Fahrenheit)
DECLARE FUNCTION CalculateFahrenheit(Celsius)
DECLARE SUB DisplayResult(Temperature, From$, Result, To$)
Main
SUB Main
'Main could either be an If-Else structure or a Select-Case structure.
DIM Choice$
DIM Temperature
DIM Result
Choice$ = GetChoice$
'If-Else approach
IF Choice$ = "C" OR Choice$ = "c" THEN
Temperature = GetTemperature("Fahrenheit")
Result = CalculateCelsius(Temperature)
DisplayResult Temperature, "Fahrenheit", Result, "Celsius"
ELSE IF Choice$ = "F" OR Choice$ = "f" THEN
Temperature = GetTemperature("Celsius")
Result = CalculateFahrenheit(Temperature)
DisplayResult Temperature, "Celsius", Result, "Fahrenheit"
ELSE
PRINT "You must enter C to convert to Celsius or F to convert to Fahrenheit!"
END IF
'Select-Case approach
SELECT CASE Choice$
CASE "C"
Temperature = GetTemperature("Fahrenheit")
Result = CalculateCelsius(Temperature)
DisplayResult Temperature, "Fahrenheit", Result, "Celsius"
CASE "c"
Temperature = GetTemperature("Fahrenheit")
Result = CalculateCelsius(Temperature)
DisplayResult Temperature, "Fahrenheit", Result, "Celsius"
CASE "F"
Temperature = GetTemperature("Celsius")
Result = CalculateFahrenheit(Temperature)
DisplayResult Temperature, "Celsius", Result, "Fahrenheit"
CASE "f"
Temperature = GetTemperature("Celsius")
Result = CalculateFahrenheit(Temperature)
DisplayResult Temperature, "Celsius", Result, "Fahrenheit"
CASE ELSE
PRINT "You must enter C to convert to Celsius or F to convert to Fahrenheit!"
END SELECT
END SUB
FUNCTION GetChoice$
PRINT "Enter F to convert to Fahrenheit or C to convert to Celsius:"
INPUT Choice$
GetChoice$ = Choice$
END FUNCTION
FUNCTION GetTemperature(Label$)
DIM Temperature
PRINT "Enter " + Label$ + " temperature:"
INPUT Temperature
GetTemperature = Temperature
END FUNCTION
FUNCTION CalculateCelsius(Fahrenheit)
DIM Celsius
Celsius = (Fahrenheit - 32) * 5 / 9
CalculateCelsius = Celsius
END FUNCTION
FUNCTION CalculateFahrenheit(Celsius)
DIM Fahrenheit
Fahrenheit = Celsius * 9 / 5 + 32
CalculateFahrenheit = Fahrenheit
END FUNCTION
SUB DisplayResult(Temperature, FromLabel$, Result, ToLabel$)
PRINT STR$(Temperature) + "° " + FromLabel$ + " is " + STR$(Result) + "° " + ToLabel$
END SUB
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own BASIC compiler / interpreter / IDE.