Postfix evaluation algorithm implementation
More...
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
|
void | push (int8_t opd) |
| Function to push on the stack.
|
|
int8_t | pop () |
| Function to pop from the stack.
|
|
int8_t | evaluate (char post[]) |
| Function to evaluate postfix expression.
|
|
static void | test () |
| Self-test implementations.
|
|
int | main () |
| Main function.
|
|
|
struct Stack | st |
| global declaration of stack st
|
|
Postfix evaluation algorithm implementation
The input postfix expression is of type string upto 49 characters (including space delimiters). Supported operations- '+', '-', '/', '*', ''
- Author
- Kumar Yash
◆ evaluate()
int8_t evaluate |
( |
char |
post[] | ) |
|
Function to evaluate postfix expression.
- Parameters
-
post | the input postfix expression |
- Returns
- evaluated answer
60 {
61 int8_t it1;
62 int8_t it2;
63 int8_t temp;
64 int8_t number;
65 int i;
66 for(i = 0; i < strlen(post); i++) {
67 if(post[i] == ' ') {
68 continue;
69 }
70 else if(isdigit(post[i])) {
71 number = 0;
72 do {
73 number = number * 10 + (post[i]-'0');
74 i++;
75 } while(i < strlen(post) && isdigit(post[i]));
77 }
78 else {
81 switch(post[i]) {
82 case '+':
83 temp = it1 + it2; break;
84 case '-':
85 temp = it1 - it2; break;
86 case '*':
87 temp = it1 * it2; break;
88 case '/':
89 temp = it1 / it2; break;
90 case '%':
91 temp = it1 % it2; break;
92 default:
93 printf("Invalid operator"); exit(1);
94 }
96 }
97 }
99}
void push(struct Stack *p, char ch)
push function
Definition infix_to_postfix.c:55
int8_t pop()
Function to pop from the stack.
Definition postfix_evaluation.c:44
◆ main()
Main function.
- Returns
- 0 on exit
initialize
run self-test implementations
124 {
127 return 0;
128}
struct Stack st
global declaration of stack st
Definition postfix_evaluation.c:24
static void test()
Self-test implementations.
Definition postfix_evaluation.c:105
int top
stores index of the top element
Definition infix_to_postfix2.c:23
◆ pop()
Function to pop from the stack.
- Returns
- popped number
< to store the popped value to be returned
44 {
45 int8_t item;
47 printf("Stack underflow...");
48 exit(1);
49 }
52 return item;
53}
char stack[10]
array stack
Definition infix_to_postfix2.c:22
◆ push()
Function to push on the stack.
- Parameters
-
opd | number to be pushed in the stack |
- Returns
- void
31 {
33 printf("Stack overflow...");
34 exit(1);
35 }
38}
◆ test()
static void test |
( |
void |
| ) |
|
|
static |
Self-test implementations.
- Returns
- void
this ensures that the algorithm works as expected
this ensures that the algorithm works as expected
105 {
106
107
108
109
110 char temp1[50] = "2 10 + 9 6 - /";
112
113
114
115 char temp2[50] = "4 2 + 3 5 1 - * +";
117 printf("All tests have successfully passed!\n");
118}
int8_t evaluate(char post[])
Function to evaluate postfix expression.
Definition postfix_evaluation.c:60