forked from keshavsingh4522/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
By Shourya Gupta A simple program using user defined function to Evaluate an expression given by the user in infix to prefix using C languague
- Loading branch information
1 parent
5f95745
commit 6853725
Showing
1 changed file
with
117 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
/* infix to prefix conversion*/ | ||
|
||
#include<stdio.h> | ||
#include<string.h> | ||
#define MAX 20 | ||
char stack[MAX]; | ||
int top=-1; | ||
void push(char item) | ||
{ | ||
top++; | ||
stack[top]=item; | ||
} | ||
char pop() | ||
{ | ||
char a; | ||
a=stack[top]; | ||
top--; | ||
return a; | ||
} | ||
int prcd(char symbol) | ||
{ | ||
switch(symbol) | ||
{ | ||
case '+': | ||
case '-': return 2; | ||
case '*': | ||
case '/': return 4; | ||
case '^': | ||
case '$': return 6; | ||
case '(': | ||
case ')': | ||
case '#': return 1; | ||
} | ||
return 0; | ||
} | ||
int isoperator(char symbol) | ||
{ | ||
switch(symbol) | ||
{ | ||
case '+': | ||
case '-': | ||
case '*': | ||
case '/': | ||
case '^': | ||
case '$': | ||
case '(': | ||
case ')': return 1; | ||
default: return 0; | ||
} | ||
} | ||
void infix_to_prefix(char infix[], char prefix[]) | ||
{ | ||
int i,symbol,j=0; | ||
char test[MAX]; | ||
infix=strrev(infix); | ||
stack[++top]='#'; | ||
for(i=0;i<strlen(infix);i++) | ||
{ | ||
symbol=infix[i]; | ||
if(isoperator(symbol)==0) | ||
{ | ||
prefix[j]=symbol; | ||
j++; | ||
} | ||
else | ||
{ | ||
if(symbol==')') | ||
{ | ||
push(symbol); | ||
} | ||
else if(symbol=='(') | ||
{ | ||
while(stack[top]!=')') | ||
{ | ||
prefix[j]=pop(); | ||
j++; | ||
} | ||
pop(); | ||
} | ||
else | ||
{ | ||
if(prcd(symbol>=prcd(stack[top]))) | ||
{ | ||
push(symbol); | ||
} | ||
else | ||
{ | ||
while(prcd(symbol)<prcd(stack[top])) | ||
{ | ||
prefix[j]=pop(); | ||
j++; | ||
} | ||
push(symbol); | ||
} | ||
} | ||
} | ||
} | ||
while(stack[top]!='#') | ||
{ | ||
prefix[j]=pop(); | ||
j++; | ||
} | ||
prefix[j]='\0'; | ||
prefix=strrev(prefix); | ||
} | ||
|
||
/*The driver code*/ | ||
int main(void) | ||
{ | ||
char infix[20],prefix[20]; | ||
printf("\nenter infix expression:"); | ||
scanf("%s",infix); | ||
infix_to_prefix(infix,prefix); | ||
printf("\nequivalent prefix expression:"); | ||
puts(prefix); | ||
return 0; | ||
} |