-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfix.c
More file actions
75 lines (65 loc) · 1.33 KB
/
infix.c
File metadata and controls
75 lines (65 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*returns the index of first occurence of character ch*/
int breakacc(char ch, char *str){
int i, j, len;
len = strlen(str);
for(i = 0; i < len; i++){
if(str[i] == ch){
return i;
}
}
return 0;
}
/* checked and verified*/
void copyintome(char *dest, char *source, int bound){
int i;
for(i = 0; i < bound; i++){
dest[i] = source[i];
}
return;
}
/*as the name sounds infix expression evaluation*/
int evalforinfix(char *str){
int i, num1, num2;
char *str2 = (char *)malloc(strlen(str) * sizeof(char));
i = breakacc('+', str);
if(i){
copyintome(str2, str, i);
num1 = evalforinfix(str2);
num2 = evalforinfix(str + i + 1);
return num1 + num2;
}
i = breakacc('-', str);
if(i){
copyintome(str2, str, i);
num1 = evalforinfix(str2);
num2 = evalforinfix(str + i + 1);
return num1 - num2;
}
i = breakacc('*', str);
if(i){
copyintome(str2, str, i);
num1 = evalforinfix(str2);
num2 = evalforinfix(str + i + 1);
return num1 * num2;
}
i = breakacc('/', str);
if(i){
copyintome(str2, str, i);
num1 = evalforinfix(str2);
num2 = evalforinfix(str + i + 1);
return num1 / num2;
}
return atoi(str);
}
int main(){
char str[20];
char *a, *b;
int i;
printf("Enter a string\n");
scanf("%s", str);
printf("%d\n", evalforinfix(str));
return 0;
}