C++ or C program to implement postfix expression evaluation using stack

File name:-postfeva.cpp
#include<iostream.h>
#include<conio.h>
#include<string.h>
#define N 100
int stack[N];
char post[N];
int top=-1;
void main(){
void pushstack(int temp);
void calculator(char c);
int i;
clrscr();
cout<<"Insert a postfix notation :: ";
gets(post);
for(i=0;i<strlen(post);i++)
 {
 if(post[i]>='0' && post[i]<='9')
  {
   pushstack(i);
  }
  if(post[i]=='+' || post[i]=='-' || post[i]=='*' ||
  post[i]=='/' || post[i]=='^')
  {
   calculator(post[i]);
  }
 }
 cout<<endl<<"Result :: "<<stack[top];
 getch();
}
void pushstack(int temp)
{
 top++;
 stack[top]=(int)(post[temp]-48);
}
void calculator(char c)
{
 int a,b,ans;
 a=stack[top];
 stack[top]='\0';
 top--;
 b=stack[top];
 stack[top]='\0';
 top--;
 switch(c)
 {
  case '+':
  ans=b+a;
  break;
  case '-':
  ans=b-a;
  break;
  case '*':
  ans=b*a;
  break;
  case '/':
  ans=b/a;
  break;
  case '^':
  ans=b^a;
  break;
  default:
  ans=0;
 }
 top++;
 stack[top]=ans;
}


File name:-postfeva.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define N 100
int stack[N];
char post[N];
int top=-1;
void main()
{
void pushstack(int temp);
void calculator(char c);
 int i;
 clrscr();
 printf("Insert a postfix notation :: ");
 gets(post);
 for(i=0;i<strlen(post);i++)
 {
  if(post[i]>='0' && post[i]<='9')
  {
   pushstack(i);
  }
  if(post[i]=='+' || post[i]=='-' || post[i]=='*' ||
  post[i]=='/' || post[i]=='^')
  {
   calculator(post[i]);
  }
 }
 printf("\n\nResult :: %d",stack[top]);
 getch();
}
void pushstack(int temp)
{
 top++;
 stack[top]=(int)(post[temp]-48);
}
void calculator(char c)
{
 int a,b,ans;
 a=stack[top];
 stack[top]='\0';
 top--;
 b=stack[top];
 stack[top]='\0';
 top--;
 switch(c)
 {
  case '+':
  ans=b+a;
  break;
  case '-':
  ans=b-a;
  break;
  case '*':
  ans=b*a;
  break;
  case '/':
  ans=b/a;
  break;
  case '^':
  ans=b^a;
  break;
  default:
  ans=0;
 }
 top++;
 stack[top]=ans;
}

No comments:

Post a Comment

Stack Data Structure, Push, Pop and Peek Operations , Applications of Stack

Stack is a linear data structure. It is collection of ordered data elements. It is also known as LIFO system (last in first out). It means i...