help: evaluating prefix notation

Discussion in 'C' started by Mst8kenId, Aug 28, 2010.

  1. Mst8kenId

    Mst8kenId New Member

    Joined:
    Aug 28, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    only a beginner, please bear with me..
    there are no errors, but wrong output
    assumptions:
    input is correctly formed
    array size is 20
    single digits only
    4 basic operations

    #include
    #include
    #include
    #include

    int stk[20];

    void push(int a, int b)
    {
    stk[a]=b;
    }

    int pop(int a)
    {
    int b=stk[a];
    stk[a]=NULL;
    return b;
    }

    main()
    {
    char yorn, str[20], *tmp;
    int chr, sctr, a, x, y, ans;

    do{
    clrscr();
    printf("input an equation in prefix notation: ");
    scanf("%s", &str[20]);
    sctr=0;
    for(a=20; a>0; a--)
    {
    if(isdigit(str[a-1])!=0)
    {
    *tmp=str[a-1];
    chr=atoi(tmp);
    push(sctr, chr);
    sctr++;
    }
    if(isdigit(str[a-1])==0)
    {
    if(str[a-1]=='+')
    {
    x=pop(sctr-1);
    y=pop(sctr-2);
    sctr-2;
    ans=x+y;
    push(sctr, ans);
    }
    if(str[a-1]=='-')
    {
    x=pop(sctr-1);
    y=pop(sctr-2);
    sctr-2;
    ans=x-y;
    push(sctr, ans);
    }
    if(str[a-1]=='/')
    {
    x=pop(sctr-1);
    y=pop(sctr-2);
    sctr-2;
    ans=x/y;
    push(sctr, ans);
    }
    if(str[a-1]=='*')
    {
    x=pop(sctr-1);
    y=pop(sctr-2);
    sctr-2;
    ans=x*y;
    push(sctr, ans);
    }
    }
    }
    ans=pop(sctr);
    printf("the answer is %d", ans);
    printf("\ntry again?[y/n]: ");
    scanf("%s", &yorn);
    getch();
    }while((yorn=='y')||(yorn=='Y'));

    getch();
    return 0;
    }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice