1 year ago

#69625

test-img

pratik jain

Why is am getting wrong output while converting infix expression (without parentheses) to prefix expression?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct stack {
    int tos;
    char arr[21];
} stack;

void push(stack*, char);
char pop(stack*);
void convert(char[], char[]);
int isoperand(char);
int precd(char, char);
int isempty(stack);

int main()
{
    char infix[21];
    char prefix[21];
    printf("Enter the character in infix expression:\n");
    scanf("%s", infix);
    convert(infix, prefix);
    printf("%s", prefix);
}

int isempty(stack s)
{
    return s.tos == -1;
}

void push(stack *p, char ch)
{
    if (p->tos == 19)
    {
        printf("Stack overflow");
    }
    p->arr[++(p->tos)] = ch;
}

char pop(stack *p)
{
    if (p->tos == -1)
    {
        printf("Stack underflow");
        return '\0';
    }
    return p->arr[(p->tos)--];
}

int isoperand(char ch)
{
    return ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'));
}

int precd(char op1, char op2) /*I think in this function something is wrong but I am unable to trace it.*/
{
    if (op1 == op2)
        return 1;
    else if (op2 == '$')
        return 0;
    else if (op1 == '$')
        return 1;
    else if ((op2 == '*' || op2 == '%' || op2 == '/') &&(op1 != '*' || op1 != '%' || op1 != '/'))
        return 0;
    else if ((op1 == '*' || op1 == '%' || op1 == '/') &&(op2 != '*' || op2 != '%' || op2 != '/'))
        return 1;
    else if ((op2 == '-' || op2 == '+') && (op1 != '-' || op1 != '+'))
        return 0;
    else
        return 1;
}

void convert(char infix[], char prefix[])
{
    int i, j = 0;
    stack s;
    s.tos = -1;
    int r;
    for (i = (strlen(infix) - 1); i >= 0; i--)
    {
        if (isoperand(infix[i]) == 1)
        {
            prefix[j] = infix[i];
            j++;
        }
        else
        {
            while (isempty(s) == 0)
            {
                r = precd(infix[i], s.arr[s.tos]);
                if (r == 0)
                {
                    prefix[j] = pop(&s);
                    j++;
                }
                else
                    break;
             }
             push(&s, infix[i]);
         }
     }
     while (isempty(s) == 0)
     {
        prefix[j] = pop(&s);
        j++;
     }
     prefix[j] = '\0';
     strrev(prefix);
}

I think I have written something wrong in the precd(char, char) function if else if else condition which checks the precedence but I am unable to trace it. Also I think the problem is in the comparison of '-' operator with '+' operator you can also see other functions if they have any bug I have also added comment in the function to highlight it. I am stuck here, please help.

arrays

c

if-statement

stack

prefix

0 Answers

Your Answer

Accepted video resources