Sunday, October 5, 2008

Evaluation of prefix using stack

 most of us know how to evaluate a postfix using stack.now let us see for the prefix version.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace prefix_eval_using_stack
{
    class Program
    {
        public static void Main(string[] args)
        {
            Stack s = new Stack();
            Console.WriteLine("Enter the prefix expression");
            string str = Console.ReadLine();
            int temp, x, y;
            char[] c = new char[26];
            int[] val = new int[26];
            int top = 0, index = -1;
            for (int i = str.Length-1; i >=0; i--)
            {

                switch (str[i])
                {
                    case '+':
                        x = Convert.ToInt32(s.Pop());
                        y = Convert.ToInt32(s.Pop());
                        s.Push(y + x);
                        break;
                    case '-':
                        x = Convert.ToInt32(s.Pop());
                        y = Convert.ToInt32(s.Pop());
                        s.Push(y - x);
                        break;
                    case '*':
                        x = Convert.ToInt32(s.Pop());
                        y = Convert.ToInt32(s.Pop());
                        s.Push(x * y);
                        break;
                    case '/':
                        x = Convert.ToInt32(s.Pop());
                        y = Convert.ToInt32(s.Pop());
                        s.Push(y / x);
                        break;
                    default:
                        index = -1;
                        for (int j = 0; j < top; j++)
                        {
                            if (str[i] == c[j])
                                index = j;
                        }
                        if (index == -1)
                        {
                            Console.WriteLine("Enter the value of {0}", str[i]);
                            temp = int.Parse(Console.ReadLine());
                            c[top] = str[i];
                            val[top] = temp;
                            top++;
                            s.Push(temp);
                        }
                        else
                            s.Push(val[index]);
                        break;
                }
            }
            Console.WriteLine("Result {0}", s.Peek());
            Console.ReadLine();

        }
    }
}

No comments: