tampurus

2.3 Infix to Postfix

Nov 25th, 2021 (edited)
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. /*
  2. Input:
  3.     Enter the infix expression
  4.     K+L-M*N+(O^P)*W/U/V*T+Q
  5.  
  6. Output:
  7.     The postfix expression is : KL+MN*-OP^W*U/V/T*+Q+
  8.  */
  9. #include<stdio.h>
  10. #include<conio.h>
  11. #define Stack_Size 50
  12. char stack[Stack_Size];
  13. int top=-1;
  14. int Is_empty(){
  15.     if(top==-1)return 1;
  16.     else return 0;
  17. }
  18. void Push(int element){
  19.     stack[++top]=element;
  20. }
  21. void Pop(){
  22.     stack[top--]=0;
  23. }
  24. int Is_operand(char c){
  25.     return ((c>='a' && c<='z') || (c>='A' && c<='Z'));
  26. }
  27. int prec(char c){
  28.     if(c=='+' || c== '-') return 1;
  29.     else if(c=='*' || c== '/') return 2;
  30.     else if (c == '^') return 3;
  31.     else return -1;
  32. }
  33. void Infix_to_Postfix(char inf[]){
  34.     for(int i=0 ; inf[i] != '\0' ; i++){
  35.         if(inf[i] == '(')Push(inf[i]);
  36.         else if(Is_operand(inf[i]))
  37.             printf("%c",inf[i]);
  38.         else if (inf[i]==')'){
  39.             while(stack[top]!='(' || top == -1){
  40.                 printf("%c",stack[top]);
  41.                 Pop();
  42.             }
  43.             Pop();
  44.         }
  45.         else{    // + , - , * , / , ^
  46.             while(  prec(stack[top])>=prec(inf[i]) ){
  47.                     printf("%c",stack[top]);
  48.                     Pop();
  49.             }
  50.             Push(inf[i]);
  51.         }
  52.     }
  53.     while(!Is_empty()){
  54.         printf("%c",stack[top]);
  55.         Pop();
  56.     }
  57. }
  58. int main()
  59. {
  60.     char infix[50];
  61.     printf("Enter the infix expression\n");
  62.     scanf("%s",infix);
  63.     printf("The postfix expression is : ");
  64.     Infix_to_Postfix(infix);
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment