Link to home
Start Free TrialLog in
Avatar of michael306
michael306

asked on

To Postfix conversion and valuation

I am working on the infix to postfix conversion,+ valuating the obtained postfix expression from a given file.
I am using the Turbo pascal compiler version 5.0 and have started up with the following code.Can any please suggest on how to remove the errors and proceed further.

The code below has compilation, run time errors.
Any kind of help will be appreciated,
Thank you in advance.

program PostFix (Input, Output);

uses wincrt;

{Evaluate a postfix expression}

{Declaration of type string1}

             const
             Capacity = 20; {Predefined maximum length}
             type
              String1 = packed array [1.. Capacity] of Char;
               

{             String1 = record
              Contents : StringType;
              Len : Integer  end;  }
           

            {Declaration of Stack}

            const
             MaxStack = 100;

             type
               StackElement = Char;

                Stack = record
                         Top : 0.. MaxStack;
                                  Items : array [1..MaxStack] of StackElement
             end; {Stack}

             var

             OpStack : Stack;
             Expression : String;
             NextCh : Char;
             Index : Integer;
             Op1, Op2,
             NewOp,
             Result : Integer;
             Success : Boolean;


             procedure CreateStack (var S : Stack);
               begin {CreateStack}
               S.Top := 0;
               end; {CreateStack}


            procedure Push (var S : Stack;
                X : StackElement;

                var Success : Boolean);
                begin {Push}
                      if S.Top >= MaxStack then
                          Success := False
                      else
                          begin
                          S.Top := S.Top + 1;
                          S.Items[S.Top] := X;
                          Success := True
                      end {if}
            end; {Push}


            procedure Pop (var S : Stack;
               var X : StackElement;
               var Success : Boolean);

               begin {Pop}
               if S.Top <= 0 then
               Success := False
               else
                begin
                   X := S.Items[S.Top];
                      S.Top := S.Top - 1;
                         Success := True
               end {if}
            end; {Pop}



            function IsEmpty (S : Stack) : Boolean;
            begin {IsEmpty}
            IsEmpty := S.Top <=0
            end; {IsEmpty}



             
              function GetChar (Str : String;
                  Index : Integer) : Char;
                  begin {GetChar}  
                    if (Index < 1) or (Index > Length(Str)) then
                      WriteLn ('String index out of range')
                        else
                           GetChar := Str.Contents[Index]
             end; {GetChar}
               


               procedure GetInteger (Expression {input} : String;
                      var Index {input/output},
                      NewOp {output} : char);
                      begin {GetInteger}
                        NewOp := ' ';
                        NextCh := GetChar(Expression, Index);
                         while (NextCh in ['0'..'9']) and (Index <= Length(Expression)) do
                           begin
                           NewOp := (10 * NewOp) + Ord(NextCh) - Ord('0');
                           Index :=Index + 1;
                           NextCh := GetChar(Expression, Index)
                         end; {while}
                           if not (NextCh in ['0'..'9']) then
                           Index := Index - 1;
                           end; {GetInteger}


             function Eval (NextCh : Char;
               Op1, Op2 : Integer) : Integer;

                    begin {Eval}
                    if NextCh in ['+', '-', '*', '/'] then
                    case NextCh of
                       '+' : Eval := Op1 + Op2;
                          '-' : Eval := Op1 - Op2;
                             '*' : Eval := Op1 * Op2;
                                '/' : Eval := Op1 div Op2;
                   end {case}
                      else
                         WriteLn ('Error in operator symbol')
             end; {Eval}

             begin {Postfix}
             Write ('Enter your expression> ');
             ReadLn (Input , Expression);
             CreateStack (OpStack);
             Index := 1;
             Success := True;
             while Success and (Index <=Length(Expression)) do
                begin
                NextCh := GetChar(Expression, Index);
                if NextCh in ['0'..'9'] then
                   begin
                   GetInteger(Expression, Index, NewOp);
                   Push (OpStack, NewOp, Success);
                   if not success then
                   WriteLn ('Stack overflow error')
                   end
                   else if NextCh in ['+','-','*','/'] then
               begin
               Pop (OpStack, Op2, Success);
               Pop (OpStack, Op1, Success);
               if not Success then
               WriteLn ('Invalid expression');
               else
               begin
               Result := Eval(NextCh, Op1, Op2);
               Push (OpStack, Result, Success);
               if not Success then
               WriteLn ('Stack overflow');
               end
             end;
             Index := Index + 1;
             end;

             if Success then
             Pop (OpStack, Result, Success);
             if Success and IsEmpty(OpStack) then
             WriteLn ('Expression value is ', Result :1)
             else
             WriteLn ('Invalid expression')
             end.
 
Avatar of hongjun
hongjun
Flag of Singapore image

Perhaps this might help a bit. I have forgotten Pascal totally. Below is its equivalent in C Programming.


/*****************************/
/* Programmer : Loh Hon Chun */
/* Adm No     : 9852152      */
/* Class      : 3A07         */
/* Description: Practical 3  */
/*****************************/

/*************************************************************/
/*************************************************************/
/*                 ASSUMING INFIX EXPRESSION                 */
/*                             IS VALID                          */
/*                              !!!!!!!!                          */
/*************************************************************/
/*************************************************************/

/* include necessary preprocessor header files */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

/* constants */
#define TRUE 1
#define FALSE 0

/* structure for stack */
typedef struct
{
      char data[20];  /* array to hold stack contents */
      int tos;        /* top of the stack pointer */
} STACK;


/* function prototypes */
void initStack(STACK *stack);
void get_infix(char infix[]);
void convertToPostfix(char infix[], char postfix[]);
int isOperator(char c);
int precedence(char operator1, char operator2);
int pred_level(char ch);
void push(STACK *stack, char value);
char pop(STACK *stack);
char stackTop(STACK *stack);
int isEmpty(STACK *stack);
int isFull(STACK *stack);
void printResult(char infix[], char postfix[]);
void print_msg(void);

/* program entry point */
int main(void)
{
      char infix[20], postfix[20]="";

      /* convert from infix to postfix main function */
      convertToPostfix(infix, postfix);
      /* display the postfix equivalent */
      infix[strlen(infix)-2] = '\0';
      printResult(infix, postfix);

      return EXIT_SUCCESS;
}

/* initalise the stack */
void initStack(STACK *stack)
{
      stack->tos = -1;  /* stack is initially empty */
}

/* get infix expression from user */
void get_infix(char infix[])
{
      int i;

      printf("Enter infix expression below (max 18 characters excluding spaces) : \n");
      fflush(stdin);
      /* to read in only 18 characters excluding spaces */
      for ( i=0; i<18; )
      {
            if ( (infix[i] = getchar()) == '\n' )
            {
                  i++;
                  break;
            }
            else if ( !(isspace(infix[i])) )
                  i++;
      }

      infix[i] = '\0';
}

/* convert the infix expression to postfix notation */
void convertToPostfix(char infix[], char postfix[])
{
      int i, length;
      int j=0;
      char tos_ch;
      STACK stack;

      initStack(&stack); /* initialise stack */
      get_infix(infix);  /* get infix expression from user */
      length = strlen(infix);

      /* if strlen if infix is more than zero */
      if ( length )
      {      
            push(&stack, '(');
            strcat(infix, ")");
            length++;
            
            for ( i=0; i<length; i++ )
            {
                  /* if current operator in infix is digit */
                  if ( isdigit(infix[i]) )
                  {
                        postfix[j++] = infix[i];
                  }
                  /* if current operator in infix is left parenthesis */
                  else if ( infix[i] == '(' )
                  {
                        push(&stack, '(');
                  }
                  /* if current operator in infix is operator */
                  else if ( isOperator(infix[i]) )
                  {
                        while ( TRUE )
                        {
                              /* get tos */
                              tos_ch = stackTop(&stack);

                              /* no stack left */
                              if ( tos_ch == '\0' )
                              {
                                    printf("\nInvalid infix expression\n");
                                    print_msg();
                                    exit(1);
                              }
                              else
                              {
                                    if ( isOperator(tos_ch) )
                                    {
                                          if ( pred_level(tos_ch) >= pred_level(infix[i]) )
                                                postfix[j++] = pop(&stack);
                                          else
                                                break;
                                    }
                                    else
                                          break;
                              }
                        }
                        push(&stack, infix[i]);
                  }
                  /* if current operator in infix is right parenthesis */
                  else if ( infix[i] == ')' )
                  {
                        while ( TRUE )
                        {
                              /* get tos */
                              tos_ch = stackTop(&stack);

                              /* no stack left */
                              if ( tos_ch == '\0' )
                              {
                                    printf("\nInvalid infix expression\n");
                                    print_msg();
                                    exit(1);
                              }
                              else
                              {
                                    if ( tos_ch != '(' )
                                    {
                                          postfix[j++] = tos_ch;
                                          pop(&stack);
                                    }
                                    else
                                    {
                                          pop(&stack);
                                          break;
                                    }
                              }
                        }
                        continue;
                  }
            }
      }

      postfix[j] = '\0';
}

/* determine if c is an operator */
int isOperator(char c)
{
      if ( c == '+' || c == '-' || c == '*' ||
             c == '/' || c == '%' || c == '^' )
      {
            return TRUE;
      }
      else
            return FALSE;
}

/* determine precedence level */
int pred_level(char ch)
{
      if ( ch == '+' || ch == '-' )
            return 1;
      else if ( ch == '^' )
            return 3;
      else
            return 2;
}

/* determine if the precedence of operator1 is less than,
   equal to, greater than the precedence of operator2 */
int precedence(char operator1, char operator2)
{
      if ( pred_level(operator1) > pred_level(operator2) )
            return 1;
      else if ( pred_level(operator1) < pred_level(operator2) )
            return -1;
      else
            return 0;
}

/* push a value on the stack */
void push(STACK *stack, char value)
{
      if ( !(isFull(stack)) )
      {
            (stack->tos)++;
            stack->data[stack->tos] = value;
      }
}

/* pop a value off the stack */
char pop(STACK *stack)
{
      char ch;

      if ( !(isEmpty(stack)) )
      {
            ch = stack->data[stack->tos];
            (stack->tos)--;
            return ch;
      }
      else
            return '\0';
}

/* return the top value of the stack without popping the stack */
char stackTop(STACK *stack)
{
      if ( !(isEmpty(stack)) )
            return stack->data[stack->tos];
      else
            return '\0';
}

/* determine if stack is empty */
int isEmpty(STACK *stack)
{
      /* empty */
      if ( stack->tos == -1 )
            return TRUE;
      /* not empty */
      else
            return FALSE;
}

/* determine if stack is full */
int isFull(STACK *stack)
{
      /* full */
      if ( stack->tos == 19 )
            return TRUE;
      /* not full */
      else
            return FALSE;
}

/* display the result postfix expression */
void printResult(char infix[], char postfix[])
{
      /*system("cls");*/
      printf("\n\n");
      printf("Infix notation  : %s\n", infix);
      printf("Postfix notation: %s\n\n", postfix);
      print_msg();
}

/* print exit message */
void print_msg(void)
{
      printf("Hit <RETURN> to exit......");
      fflush(stdin);
      getchar();
}



hongjun
Avatar of michael306
michael306

ASKER

I greatly appreciate your work.i am thank full to see in C.Dear expert, i even also dont have enough knowledge about C.
  I started with pascal to learn. since i needed to build something on it.
    Pls help if u can in pascal ...
Thank you
Avatar of Mike McCracken
Are you still interested in getting some help here?

mlmcc
Here is the JavaScript version of the same :

<!--BEGIN INFIX-POSTFIX JAVASCRIPT-->
<script language="JavaScript">
/*
  Infix ~ Postfix Conversion
  - Converts an Infix(Inorder) expression to Postfix(Postorder) and vice-versa
  - Valid Operators are +,-,*,/,^,()
  JavaScript Implementation
  - ) 2002 Premshree Pillai
  See algorithms at
  -http://www.qiksearch.com/articles/cs/infix-postfix/index.htm
  -http://www.qiksearch.com/articles/cs/postfix-evaluation/index.htm
  Web : http://www.qiksearch.com
*/

function push_stack(stackArr,ele)
{
 stackArr[stackArr.length]=ele;
}

function pop_stack(stackArr)
{
 var _temp=stackArr[stackArr.length-1];
 delete stackArr[stackArr.length-1];
 stackArr.length--;
 return(_temp);
}

function isOperand(who)
{
 return((!isOperator(who) && (who!="(") && (who!=")"))? true : false);
}

function isOperator(who)
{
 return((who=="+" || who=="-" || who=="*" || who=="/" || who=="^")? true : false);
}

function topStack(stackArr)
{
 return(stackArr[stackArr.length-1]);
}

function isEmpty(stackArr)
{
 return((stackArr.length==0)? true : false);
}

/* Check for Precedence */
function prcd(who)
{
 if(who=="^")
  return(5);
 if((who=="*")||(who=="/"))
  return(4);
 if((who=="+")||(who=="-"))
  return(3);
 if(who=="(")
  return(2);
 if(who==")")
  return(1);
}

function InfixToPostfix(infixStr,postfixStr)
{
 var postfixStr=new Array();
 var stackArr=new Array();
 var postfixPtr=0;
 infixStr=infixStr.split('');
 for(var i=0; i<infixStr.length; i++)
 {
  if(isOperand(infixStr[i]))
  {
   postfixStr[postfixPtr]=infixStr[i];
   postfixPtr++;
  }
  if(isOperator(infixStr[i]))
  {
   if(infixStr[i]!="^")
   {
    while((!isEmpty(stackArr)) && (prcd(infixStr[i])<=prcd(topStack(stackArr))))
    {
     postfixStr[postfixPtr]=topStack(stackArr);
     pop_stack(stackArr);
     postfixPtr++;
    }
   }
   else
   {
    while((!isEmpty(stackArr)) && (prcd(infixStr[i])<prcd(topStack(stackArr))))
    {
     postfixStr[postfixPtr]=topStack(stackArr);
     pop_stack(stackArr);
     postfixPtr++;
    }
   }
   push_stack(stackArr,infixStr[i]);
  }
  if(infixStr[i]=="(")
  {
   push_stack(stackArr,infixStr[i]);
  }
  if(infixStr[i]==")")
  {
   while(topStack(stackArr)!="(")
   {
    postfixStr[postfixPtr]=pop_stack(stackArr);
    postfixPtr++;
   }
   pop_stack(stackArr);
  }
 }
 while(!isEmpty(stackArr))
 {
  if(topStack(stackArr)=="(")
   pop_stack(stackArr)
  else
   postfixStr[postfixStr.length]=pop_stack(stackArr);
 }
 var returnVal='';
 for(var i=0; i<postfixStr.length; i++)
 {
  returnVal+=postfixStr[i];
 }
 return(returnVal);
}

function PostfixToInfix(postfixStr)
{
 var stackArr=new Array();
 postfixStr=postfixStr.split('');
 for(var i=0; i<postfixStr.length; i++)
 {
  if(isOperand(postfixStr[i]))
  {
   push_stack(stackArr,postfixStr[i]);
  }
  else
  {
   var temp=topStack(stackArr);
   pop_stack(stackArr);
   var pushVal=topStack(stackArr)+postfixStr[i]+temp;
   pop_stack(stackArr);
   push_stack(stackArr,pushVal);
  }
 }
 return(topStack(stackArr));
}

function PostfixSubEval(num1,num2,sym)
{
 var returnVal;
 if(sym=="+")
  returnVal=num1+num2;
 if(sym=="-")
  returnVal=num1-num2;
 if(sym=="*")
  returnVal=num1*num2;
 if(sym=="/")
  returnVal=num1/num2;
 if(sym=="^")
  returnVal=Math.pow(num1,num2);
 return(returnVal);
}

function PostfixEval(postfixStr)
{
 var stackArr=new Array();
 postfixStr=postfixStr.split('');
 for(var i=0; i<postfixStr.length; i++)
 {
  if(isOperand(postfixStr[i]))
  {
   push_stack(stackArr,postfixStr[i]);
  }
  else
  {
   var temp=parseFloat(topStack(stackArr));
   pop_stack(stackArr);
   var pushVal=PostfixSubEval(parseFloat(topStack(stackArr)),temp,postfixStr[i]);
   pop_stack(stackArr);
   push_stack(stackArr,pushVal);
  }
 }
 return(topStack(stackArr));
}
</script>
<!--END INFIX-POSTFIX JAVASCRIPT-->
michael306:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
PAQ with REFUND
ASKER CERTIFIED SOLUTION
Avatar of AnnieMod
AnnieMod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial