program to generate assembly code from prefix code

–1 vote
asked Sep 27, 2019 by Nitish Kumar (110 points)

1 Answer

0 votes
answered Sep 28, 2019 by Khushi Jagad (140 points)
#include <iostream>

#include <string.h>

using namespace std;

#define MAX 100

int st[MAX];

char postfix[MAX],infix[MAX],temp[MAX];

int top=-1;

void push(int a);

int pop();

void infixtopostfix(char temp[],char postfix[]);

void reverse(char str[]);

int getpriority(char);

int main()

{

cout<<"\n\tEnter a infix expression :";

cin>>infix;

infixtopostfix(infix,postfix);

cout<<"\n\tThe postfix expression is : ";

cout<<postfix;

reverse(infix);

infixtopostfix(temp,postfix);

    reverse(postfix);

cout<<"\n\tThe prefix expression is : ";

cout<<(temp);

return 0;

}

void reverse(char str[])

{

int i=0,j=0;

int len;

len=strlen(str);

j=len-1;

while(j>=0)

{

if(str[j]=='(')

temp[i]=')';

else if(str[j]==')')

temp[i]='(';

else

temp[i]=str[j];

j--;

i++;

}

temp[i]='\0';

}

void infixtopostfix(char temp[],char postfix[])

{

int i=0,j=0;

char tempo;

while(temp[i]!='\0')

{

if(temp[i]=='(')

{

push(temp[i]);

}

else if(infix[i]==')')

{

while(top!=-1 && st[top]!='(')

{

postfix[j]=pop();

j++;

}

if(top==-1)

{

cout<<"\n\tInvalid Expression";

}

tempo=pop();

i++;

}

else if(isdigit(temp[i]) || isalpha(temp[i]))

{

postfix[j]=temp[i];

j++;

i++;

}

else if(temp[i]=='*' || temp[i]=='/' || temp[i]=='%' || temp[i]=='+' || temp[i]=='-' )

{

while(top!=-1 && st[top]!='(' && getpriority(st[top])>getpriority(temp[i]))

{

postfix[j]=pop();

j++;

}

push(temp[i]);

i++;

}

else

{

cout<<"\n\tInvalid expression";

}

}

while(top!=-1 && st[top]!='(')

{

postfix[j]=pop();

j++;

}

postfix[j]='\0';

}

int getpriority(char op)

{

if(op=='+' || op=='-')

return 0;

else

return 1;

}

void push(int a)

{

if(top==MAX-1)

cout<<"\n\tStack Overflow";

else

{

top++;

st[top]=a;

}

}

int pop()

{

int val;

if(top==-1)

cout<<"\n\tStack Underflow";

else

{

val=st[top];

top--;

}

return val;

}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...