# Programming Order of Operations

Page 1 of 1

## 5 Replies - 3440 Views - Last Post: 09 December 2012 - 08:36 PM

### #1 DavidM.

Reputation: 0
• Posts: 7
• Joined: 09-December 12

# Programming Order of Operations

Posted 09 December 2012 - 06:42 PM

I apologize if this is the wrong forum. It seemed like a catchall category and this is a general question.

I'm writing a calculator and am thinking about how to implement order of operations. Infix notation seems like a pain to get order of operations implemented. Postfix seems like a much nicer alternative. Would you suggest using postfix notation or something different?

Along the same lines of the question, how would you parse something like 3+sin(40)-(4*5)? The sin seems like a bit of a stumbling point.

Is This A Good Question/Topic? 0

## Replies To: Programming Order of Operations

### #2 tlhIn`toq

• Freelance developer

Reputation: 6226
• Posts: 13,734
• Joined: 02-June 10

## Re: Programming Order of Operations

Posted 09 December 2012 - 07:05 PM

From my FAQ list:

Q: I am making a calculator as my school homework project and ...
A: Calculator tutorial

### #3 cfoley

• Cabbage

Reputation: 2338
• Posts: 4,889
• Joined: 11-December 07

## Re: Programming Order of Operations

Posted 09 December 2012 - 07:17 PM

Don't ask the user to enter postfix. That's just nasty! Its not difficult to convert infix to postfix if that's what you want to work with.

### #4 DavidM.

Reputation: 0
• Posts: 7
• Joined: 09-December 12

## Re: Programming Order of Operations

Posted 09 December 2012 - 07:19 PM

That's what I meant. I would accept Infix as input but perform my calculations in postfix.

### #5 DavidM.

Reputation: 0
• Posts: 7
• Joined: 09-December 12

## Re: Programming Order of Operations

Posted 09 December 2012 - 07:25 PM

Apparently I can't edit.

TlhIn`Toq, that link provides a very simple calculator example. From what I read of it the program only accepts two inputs and an operator. I'm doing something more like a graphing calculator where you can enter an entire equation then have the program evaluate it.

For standard number input 4+(6-4/2)*6 would be evaluated to 28. I'm asking about order of operations. Should I convert the above to postfix 4 6 4 2 / - YEAR 6 * + and evaluate from there or is another method easier or better to work with?

### #6 blackcompe

• D.I.C Lover

Reputation: 1158
• Posts: 2,538
• Joined: 05-May 05

## Re: Programming Order of Operations

Posted 09 December 2012 - 08:36 PM

The only other alternative to converting infix to postfix is to write a top-down parser for an expression grammar. I'm sure that's overkill, so converting to postfix is probably your best bet. It will maintain the correct order of operations and allow you to declare precedence amongst the operators.