# writing a parser

will somebody please give me an idea on how to write a parser for algebraic expressions.
thanks!
###### Who is Participating?

Commented:
Hi,
A very known method for parsing any kind of expressions is using a stack.

The algorithm goes like this :
1. Scan the input stream squentaly.
2. If you find an operand or an operator push it to the stack.
3. When finding a second operand pop the previusly pushed two items. Now if the operator is of high priority (i.e. in your case multiplication or division) calculate it's value and push it back, otherwise push back all 3 items.
4. The result of the first scan will be that in the stack only low priority operations are left. So now scan the stream again using the same loop, but this time it will calculate the final result cause there is no priority diffrences.

In general you have to scan the stream / stack for every different level of priority (precidence).

For validity checks always make sure that you poped from the stack an operator and an operand. If not so the input is wrong.
0

Author Commented:
i give 20 because, i also need some example of what you are talking about.
0

Commented:
Hi,
here is some example written in pseudo
code since I'm a little short at time :

Suppose you want to calculate the value of an arhitmetic expression, given as an input string.
First define a stack to which you can push strings (the stack could be made using an array or a linked list)

Second define a function which cuts the next operator or operand from the string
- GetNextParamFromStr(), assuming the arguments are seperated by spaces and the string ends at NULL.

For example a series of cals to the function over the input string
"5 * 4 - 3" will return :

5
*
4
-
3

1. loop : Get a param from the string and save it's type i.e. operator / operand.
2. Match the type of the param with the type you are looking to get (in case of the first param it should be an operand). Inform the user of an error in case of a dismatch.
3. if this is the first param push it to the stack (i.e. using the previous example push '5' to the stack)
4. else if this is an arithmetic operation push it to the stack as well. Using the previous example '*' will be pushed.
5. if this is a number but not the first time pop the previusly pushed operation and number. Now if the poped operation is a high order operation ('*' '/') calculate it's value and push it back to the stack, else push all three parameters back to the stack (i.e. the first number, the operation and the second number).
6. return to step 1 until reaching the end of the string.

Now when the above algorithm is done, your stack will contain only '+' or '-' operations so you can pop the stack parameter at a time and incrementaly calculate the final result.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.