Assignment 6 CS 392 : TCPTUTOR

7
119

PROBLEM STATEMENT

Write a C program for evaluating a Postfix Expression (single digit).

ALGORITHM

Step 1: Add an ‘)’ at end of expression.

Step 2: Scan P from left to right and repeat steps 3 & 4 until end of expression is reached.

Step 3: If an operand is encountered, push it to stack.

Step 4: If an operator is encountered:

a) Remove the top two elements from stack where A is element at stack top and B is next to stack top.

b) Evaluate B operator A.

c) Push the result back to stack.

[end of if]

[end of loop]

Step 5: Set value = element in stack.

Step 6: Exit..

SOURCE CODE

#include<stdio.h>
#include<conio.h>
#include<ctype.h>

#define MAXSTACK 100
int stack[MAXSTACK];
int top = -1 ;

void push(int item)
{

if(top >= MAXSTACK -1)
{
printf(“stack over flow”);
return;
}
else
{
top = top + 1 ;
stack[top]= item;
}
}

int pop()
{
int item;
if(top <0)
{
printf(“stack under flow”);
}
else
{
item = stack[top];
top = top – 1;
return item;
}
}

void EvalPostfix(char postfix[])
{

int i ;
char ch;
int val;
int A, B ;
for (i = 0 ; postfix[i] != ‘\0’; i++)
{
ch = postfix[i];
if (isdigit(ch))
{
push(ch – ‘0’);
}
else if (ch == ‘+’ || ch == ‘-‘ || ch == ‘*’ || ch == ‘/’ || ch == ‘^’)
{
A = pop();
B = pop();

switch (ch)
{
case ‘*’:
val = B * A;
break;

case ‘/’:
val = B / A;
break;

case ‘+’:
val = B + A;
break;

case ‘-‘:
val = B – A;
break;

case ‘^’:
val = pow(B,A);
break;

}
push(val);
}
}
printf( ” \n Result of expression evaluation : %d \n”, pop()) ;
}

int main()
{
char postfix[MAXSTACK];
printf( “\nEnter postfix expression: “);

gets(postfix);

EvalPostfix(postfix);
return 0;
}

OUTPUT

Enter postfix expression : 12345*+*+

Result of expression evaluation : 47

*******************

7 COMMENTS

  1. 防曬粉 BB粉底霜 亮麗柔滑打底乳液 亮麗柔滑控油打底乳液 有機幹細胞修護CC霜 潤澤防曬底霜 礦物質潤澤慕斯 礦物質奇幻粉餅 礦物質蜜粉 完美礦物粉底 控油定妝蜜粉 高清控油粉餅 控油蜜 保濕滋潤噴霧 有機抗氧爽膚噴霧 有機抗敏保濕

  2. 破產前 (即頒布破產前) 案件分析 : 向您講解各項會受破產影響的問題 (新借貸款、物業、保險單、銀行戶口、退休金、工作、家庭等)。並分析您現在所有債項詳情及現時被追收欠債情況,並提供適當對策。 入紙申請 : 可即日宣誓申請文件並入紙法院排期破產耹訊。 追債問題 : 即時通知債權人破產呈請,停止追數滋擾。 戶口凍結 : 申請解凍銀行戶口,取回被凍結的薪金。 初步訊問表 : 當中部份問題,難以回答,而胡亂作答,會引至被檢控。我們會協助回答訊問表內各方面的問題。 收支申報 : 懂得申報支出就可保留全部或大部份收入來生活。我們會協助你爭取最多生活支出,滿足你的需要

LEAVE A REPLY

Please enter your comment!
Please enter your name here