[text] 3address

Viewer

copydownloadembedprintName: 3address
  1. #include<stdio.h>
  2. #include<ctype.h>
  3. #include<string.h>
  4. char stack[100];
  5. int top = -1;
  6. void push(char x)
  7.   {
  8.    stack[++top] = x;
  9.   }
  10. char pop()
  11.   {
  12.     if(top == -1)
  13.      return -1;
  14.       else
  15.     return stack[top--];
  16.     }
  17. int priority(char x)
  18.   {
  19.    if(x=='=')
  20.     return 1;
  21.    if(x == '(')
  22.     return 0;
  23.    if(x == '+' || x == '-')
  24.      return 2;
  25.    if(x == '*' || x == '/')
  26.     return 3;
  27.  return 0;
  28. }
  29. int main()
  30. {
  31.   char exp[100];
  32.   char *e, x;
  33.   
  34.     printf("Enter the expression : ");
  35.     scanf("%s",exp);
  36.     printf("\n");
  37.      e = exp;
  38.      
  39. char post[100];
  40. int ppointer=0;
  41. while(*e != '\0')
  42.   if(isalnum(*e))
  43.   post[ppointer++] = *e;
  44.   else if(*e == '(')
  45.   push(*e);
  46.   else if(*e == ')')
  47. {
  48.   while((x = pop()) != '(')
  49.   post[ppointer++] = x;
  50. }
  51. else
  52. {
  53.   while(priority(stack[top]) >= priority(*e))
  54.   post[ppointer++] = pop();
  55.   push(*e);
  56. }
  57. e++;
  58. }
  59. while(top != -1)
  60. {
  61. post[ppointer++] = pop();
  62. }
  63. post[ppointer] = '\0';
  64. printf("postfix expression is: %s\n",post);
  65. printf("REGISTER OP1 OP2 OPERATOR\n");
  66. for(int i = 0; i<ppointer ; i++ )
  67. {
  68. if(isalpha(post[i]))
  69. {
  70. printf(" %d %c MOV \n",i,post[i]);
  71. push(48+i);
  72. }
  73. else
  74. {
  75. char x2 = pop();
  76. char x1 = pop();
  77. if(post[i]=='+')
  78. printf(" %c %c %c ADD \n",x1,x1,x2);
  79.  else if(post[i]=='-')
  80. printf(" %c %c %c SUB \n",x1,x1,x2);
  81. else if(post[i]=='*')
  82. printf(" %c %c %c MUL \n",x1,x1,x2);
  83. else if(post[i]=='/')
  84. printf(" %c %c %c DIV \n",x1,x1,x2);
  85. else
  86. printf(" %c %c %c LOAD \n",x1,x1,x2);
  87. push(x1);
  88.    }
  89. }
  90. return 0;
  91. }

Editor

You can edit this paste and save as new:


File Description
  • 3address
  • Paste Code
  • 11 Dec-2023
  • 1.52 Kb
You can Share it: