Practical No: 5: Rajdeep Shivarkar BE19F06F060
Practical No: 5: Rajdeep Shivarkar BE19F06F060
Practical No: 5: Rajdeep Shivarkar BE19F06F060
PRACTICAL NO : 5
OUTPUT :
#include<stdio.h>
#include<ctype.h> char
stack[100]; int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{ if(top == -1) return -
1; else return
stack[top--];
}
int priority(char x)
{ if(x == '(') return 0;
if(x == '+' || x == '-')
return 1; if(x == '*' || x ==
'/') return 2; return 0;
}
Rajdeep Shivarkar BE19F06F060
int main()
{
char exp[100]; char *e, x;
printf("Enter the expression : ");
scanf("%s",exp); printf("\n"); e =
exp; while(*e != '\0')
{ if(isalnum(*e))
printf("%c ",*e); else if(*e == '(')
push(*e); else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
} else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
} e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
Rajdeep Shivarkar BE19F06F060
OUTPUT :
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> struct
Stack { int top; int
maxSize; int* array;
};
struct Stack* create(int max)
Rajdeep Shivarkar BE19F06F060
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct
Stack)); stack->maxSize = max; stack->top = -1;
stack->array = (int*)malloc(stack->maxSize * sizeof(int));
return stack;
}
int isFull(struct Stack* stack)
{
if(stack->top == stack->maxSize - 1){
printf("Will not be able to push maxSize reached\n");
}
// Since array starts from 0, and maxSize starts from 1
return stack->top == stack->maxSize - 1;
}
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}
int checkIfOperand(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
if (checkIfOperand(expression[i]))
expression[++j] = expression[i]; else if
(expression[i] == '(') push(stack,
expression[i]);
else if (expression[i] == ')')
{
while (!isEmpty(stack) && peek(stack) !=
'(') expression[++j] = pop(stack);
if (!isEmpty(stack) && peek(stack) != '(')
return -1; // invalid expression else
pop(stack);
}
else // if an opertor
{
while (!isEmpty(stack) && precedence(expression[i]) <= precedence(peek(stack)))
expression[++j] = pop(stack);
push(stack, expression[i]);
}
}
while (!isEmpty(stack))
expression[++j] = pop(stack);
expression[++j] = '\0';
temp[j--]='\0';
while(exp[i]!='\0')
Rajdeep Shivarkar BE19F06F060
{
temp[j] = exp[i];
j--; i++;
}
strcpy(exp,temp);
}
void brackets(char* exp){
int i = 0; while(exp[i]!='\0')
{
if(exp[i]=='(')
exp[i]=')'; else
if(exp[i]==')')
exp[i]='('; i++;
}
}
void InfixtoPrefix(char *exp)
{ int size = strlen(exp);
reverse(exp); brackets(exp);
getPostfix(exp); reverse(exp);
}
int main()
{
printf("The infix is: "); char expression[]
= "((a/b)+c)-(d+(e*f))"; printf("%s\
n",expression); InfixtoPrefix(expression);
printf("The prefix is: "); printf("%s\
n",expression);
return 0;
}
OUTPUT :
Rajdeep Shivarkar BE19F06F060