(HackerRank) Write a Modular C Programming code to solve POSTFIX EXPRESSION EVALUATION, Help Swaraj in developing the modular c program.
Swaraj wants to now learn how to use stacks data structures to evaluate the postfix expressions. He gets the algorithm from his class teacher.
The class teacher provides the following algorithm for him to study and convert it to a working modular c program.
Help Swaraj in developing the modular c program.
Input Format
A valid postfix expression.
Constraints
Postfix expression will not have any kind of parentheses.
Output Format
Evaluated postfix expression.
Sample Input 0
59+
Sample Output 0
Given postfix Expression: 59+
Result after Evaluation: 14
Sample Input 1
12+3-4/
Sample Output 1
Given postfix Expression: 12+3-4/
Result after Evaluation: 0
Sample Input 2
55+75-31/*+
Sample Output 2
Given postfix Expression: 55+75-31/*+
Result after Evaluation: 16
CODE:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define SIZE 100 struct stack { int data[SIZE]; int top; }; void push(struct stack *sptr, int num); int pop(struct stack *sptr); int evaluate(struct stack *sptr,char postfix[SIZE]); int main() { struct stack * sptr; struct stack s; char postfix[SIZE]; sptr=&s; sptr->top=-1; scanf("%s",postfix); printf("Given postfix Expression: %s\n",postfix); int res=evaluate(sptr,postfix); printf("Result after Evaluation: %d\n",res); return 0; } void push(struct stack *sptr, int num) { if(sptr->top==SIZE-1) { printf("Stack Overflow\n"); } else { sptr->top++; sptr->data[sptr->top]=num; } } int pop(struct stack *sptr) { int num; num=sptr->data[sptr->top]; sptr->top--; return num; } int evaluate(struct stack *sptr,char postfix[SIZE]) { int op1,op2,i=0; char ch; while(postfix[i]!='\0') { ch=postfix[i]; if(isdigit(ch)!=0) { push(sptr,(ch-'0')); } else { op2=pop(sptr); op1=pop(sptr); switch(ch) { case '+':push(sptr,op1+op2); break; case '-':push(sptr,op1-op2); break; case '*':push(sptr,op1*op2); break; case '/':push(sptr,op1/op2); break; } } i++; } return pop(sptr); }
OUTPUT
Congratulations, you passed the sample test case. Click the Submit Code button to run your code against all the test cases. Input (stdin) 59+ Your Output (stdout) Given postfix Expression: 59+ Result after Evaluation: 14 Expected Output Given postfix Expression: 59+ Result after Evaluation: 14
Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, Stacks, Queues, Binary Trees, MISC, Solved model question papers & Hacker Rank all solutions on the below page:
Top 100+ C Programming codes – KLE Technological University