1. DATA STRUCTURES
ASSIGNMENT # 2
“Infix to Prefix Conversion, Evaluation and Pseudo code”
SUBMITTED TO:
Zaheer Sani
SUBMITTED BY:
Ahmed Khateeb
SP12-BCS-028
BSCS – IIIC
Department of Computer Science
2. A) CONVERSION INFIX EXPRESSION TO PREFIX.
B) EVALUATION OF INFIX EXPRESSION (AND VERIFICATION).
C) PSEUDO CODE TO CONVERT INFIX TO PREFIX
PART A
- Let have an Infix Expression
( (A+B) * (C+D) / (E-F) ) + G
- Reading Expression from “right to left” character by
character.
- We have Input, Prefix_Stack & Stack.
- Now converting this expression to Prefix.
Input Prefix_Stack Stack
G G (empty)
+ G +
) G + )
) G + ) )
F GF + ) )
- GF + ) ) -
E GFE + ) ) -
( GFE- + )
/ GFE- + ) /
) GFE- + ) / )
D GFE-D + ) / )
+ GFE-D + ) / ) +
C GFE-DC + ) / ) +
3. ( GFE-DC+ + ) /
* GFE-DC+ + ) / *
) GFE-DC+ + ) / * )
B GFE-DC+B + ) / * )
+ GFE-DC+B + ) / * ) +
A GFE-DC+BA + ) / * ) +
( GFE-DC+BA+ + ) / *
( GFE-DC+BA+*/ +
(empty) GFE-DC+BA+*/+ (empty)
- Now pop-out Prefix_Stack to output (or simply reverse).
Prefix expression is
+ / * + A B + C D – E F G
PART B
4. - First I’m assigning values to all operands.
A = 14
B = 12
C = 10
D = 8
E = 6
F = 4
G = 2
- Evaluating Infix expression using above values.
( (14+12) * (10+8) / (6-4) ) + 2
( 26 * 18 / 2 ) + 2
( 468 / 2 ) + 2
( 234 ) + 2
236
- Evaluating Infix expression using above values.
+ / * + 14 12 + 10 8 - 6 4 2 (14+2 & 10+8 & 6-4)
+ / * 26 18 2 2 (26 * 18)
+ / 468 2 2 (468 / 2)
+ 234 2 (234 + 2)
236
- Both are same, so our conversion is correct!
PART C
5. Arr = (Infix Expression)
Set loop_counter to length_ of_ Arr
do
character = arr[loop_counter]
if character is operator
push character to prefix_stack
if character is ‘)’
push character to stack
if character is ‘(’
do
pop character and push it to prefix_stack
until character equals ‘(‘
if character is operator
if character_precedence is greater OR is equal to stack[top]_ precedence
push to stack
else
do
pop from stack and push to prefix_stack
until condition satisfices
loop_counter = loop_counter - 1
While loop_counter IS NOT EQUAL to 0
Pop out prefix_stack and display each element