After readingthis thread in the pit, I’m curious as to what a “simple command line calculator program that will do basic arithmetic(±/*^())” would look like in the various languages available today. Most respondants in that thread seemed to think that this was a trivial excercise, so I want to see some code!
I’ll start, and as I’m a sysprog on a z/OS mainframe with not very much exposure to C, C++, VB, etc., I’m going to fall back on what I know, which is REXX. This program will do exactly what is asked for.
I don’t propose this to be a contest or anything like that, but I’m genuinely interested in how this problem is solved in different languages.
My contribution:
/*=============================== Rexx ===============================*/
true = (0 = 0)
false = (0 = 1)
continue? = true
Say 'Enter Expression:'
Parse External expr
Call Get_next_char
result = Expression()
If nextchar = '' & continue? Then
Say 'The Result is: ' result
Else
Say 'Syntax Error'
Exit
/*====================================================================*/
Get_next_char:
nextchar = ' '
Do Until nextchar ¬= ' ' | Length(expr) = 0
Parse Var expr nextchar 2 expr
End
Return
/*====================================================================*/
Expression: Procedure Expose nextchar continue? expr true false
value = Term()
Do Forever
Select
When nextchar = '+' Then
Do
Call Get_next_char
value = value + Term()
End
When nextchar = '-' Then
Do
Call Get_next_char
value = value - Term()
End
Otherwise
Leave
End
End
Return value
/*====================================================================*/
Term: Procedure Expose nextchar continue? expr true false
value = Factor()
Do Forever
Select
When nextchar = '*' Then
Do
Call Get_next_char
value = value * Factor()
End
When nextchar = '#' Then
Do
Call Get_next_char
value = value ** Term()
End
When nextchar = '/' Then
Do
Call Get_next_char
divisor = Factor()
If divisor ¬= 0 Then
value = value / divisor
Else
Do
Say 'Division by Zero'
Exit
End
End
Otherwise
Leave
End
End
Return value
/*====================================================================*/
Factor: Procedure Expose continue? nextchar expr true false
value = 0
count = 0
decimal_point? = false
If (nextchar <= 9) & (nextchar >= 0) Then
Do
Do While (nextchar <= 9 & nextchar >= 0)
value = value * 10 + nextchar
Call Get_next_char
If decimal_point? Then
count = count + 1
If nextchar = '.' Then
Do
Call Get_next_char
decimal_point? = true
End
End
Do i = 0 By 1 While i < count
value = value / 10
End
Return value
End
Else
Select
When nextchar = '-' Then
Do
Call Get_next_char
Return -1 * Factor()
End
When nextchar = '(' Then
Do
Call Get_next_char
value = Expression()
If nextchar ¬= ')' Then
Do
Say 'Mismatched Parentheses'
Exit
End
Else
Do
Call Get_next_char
Return value
End
End
When nextchar = '.' Then
decimal_point? = true
Otherwise
continue? = false
End
Return 0