APPLICATION OF STACK PROGRAM

 If Screen is half, please rotate the Mobile then it is full program available

APPLICATION OF STACK: EVALUATION OF SUFFIX EXPRESSION.

5. Design, Develop and Implement a Program in C for the following Stack

Applications

a. Evaluation of Suffix expression with single digit operands and operators:

+, -, *, /, %, ^


/* Preprocessor directives */

#include <stdio.h>

#include <stdlib.h>

#include <math.h>


/*--Global variables--*/

int stack[50];

int top = 0;

char postfix[20];


typedef enum {plus, minus, times, divide, mod, power, eos, operand} PRECEDENCE;


/*-- Function definition--*/

void getPostfix ( void )

{

printf ( "\nEnter the valid POSTFIX expression: ?\b" );

gets ( postfix );

}


void push ( int symbol )

{

/* add an item to the global stack */

stack[++ top] = symbol;

}


int pop ( void )

{

/* delete and return the top element from the stack */

return stack[top --];

}


PRECEDENCE getToken ( char *symbol, int *n )

{

*symbol = postfix[(*n)++];

switch ( *symbol )

{

case '(' : return lparen;

case ')' : return rparen;

case '+' : return plus;

case '-' : return minus;

case '/' : return divide;

case '*' : return times;

case '%' : return mod;

case '^' : return power;

case '\0': return eos;

case ' ' : return eos;

default : return operand; /* no error checking, default is operand */

}

}


int eval ( void )

{

PRECEDENCE token;

char symbol;

int op1, op2;

int n = 0;

token = getToken ( &symbol, &n );

while ( token != eos )

{

if ( token == operand )

{

push ( symbol - '0' );

}

else

{

op2 = pop ( );

op1 = pop ( );

switch ( token )

{

case plus  : push ( op1 + op2 ); break;

case minus : push ( op1 - op2 );  break;

case times : push ( op1 * op2 );  break;

case divide : push ( op1 / op2 );  break;

case mod : push ( op1 % op2 ); break;

case power :   push ( (int)pow( (double)op1, (double)op2 ) );

}


}

token = getToken ( &symbol, &n );

}

return pop ( );

}


void printResult ( void )

{

printf ( "\n\nEvaluated POSTFIX expression: %d\n\n", eval ( ) );

}


int main ( void )

{

system ( "cls" );

getPostfix ( );

printResult ( );


fflush ( stdin );

getchar ( );

return 0;

}



/*


OUTPUT:-



Enter the valid POSTFIX expression: 6 2 / 3 - 4 2 * +



Evaluated POSTFIX expression: 8


*/


Post a Comment

Previous Post Next Post

Contact Form