infix to postfix using stack error in updating top variable - c

I'm trying to implement a code for infix to postfix conversion but I'm not able to obtain the output. By analyzing the program I found that the variable top s not getting updated even though I'm returning its value back to the main. Please help me figure it out. The code is:
#include<stdio.h>
char stack[15];
int check(char op)
{
int rank=0;
switch(op)
{
case '/':
rank=1;
break;
case '*':
rank=2;
break;
case '+':
rank=3;
break;
case '-':
rank=4;
break;
}
return rank;
}
int POP(char stack[15],int top)
{
if(top==-1)
{
printf("Stack Underflow");
return top;
}
else
{
top--;
printf("%c",stack[top+1]);
return top;
}
}
int PUSH(char stack[15],int top,char op)
{
char opstack;
int rank1,rank2;
if(top>=14)
{
printf("Stack Overflow");
return top;
}
else
{
if(top==-1)
{
top++;
stack[top]=op;
return top;
}
else
{
opstack=stack[top];
rank1=check(op);
rank2=check(opstack);
if( rank1 <= rank2 )
{
top++;
stack[top]=op;
}
else
{
top=POP(stack,top);
top=PUSH(stack,top,op);
}
return top;
}
}
}
int main()
{
char string[15],ch;
int top=-1,i;
printf("Enter the infix operation: ");
gets(string);
fflush(stdin);
for(i=0;string[i]!='\0';i++)
{
ch=string[i];
if( ((ch>='a') && (ch<='z'))||((ch>='A') &&(ch<='Z')) )
{
printf("%c",string[i]);
}
else
{
ch=string[i];
top=PUSH(stack,top,ch);
}
top=POP(stack,top);
}
return 0;
}

in main function add these three lines after for loop End.and remove top=POP(stack,top);
inside for loop.
while(top!=-1)
top=POP(stack,top);
printf("\n");
modified main function:
int main()
{
char string[15],ch;
int top=-1,i;
printf("Enter the infix operation: ");
gets(string);
fflush(stdin);
for(i=0;string[i]!='\0';i++)
{
ch=string[i];
if( ((ch>='a') && (ch<='z'))||((ch>='A') &&(ch<='Z')) )
{
printf("%c",string[i]);
}
else
{
ch=string[i];
top=PUSH(stack,top,ch);
}
}
while(top!=-1)
top=POP(stack,top);
printf("\n");
return 0;
}

Related

In this trie data structure implementation the display function is not working.Why?

When i display I am getting different answer but search is working. It could be a semantic error.Please help to correct it. It could have an error somewhere. I don't know where is it.Please help me to find it.The insert does not work in the program.It could be an error somewhere.I need this trie data structure to work.
#include<stdio.h>
#include<stdlib.h>
#define maxlength 10
typedef struct node
{
int isend;
struct node *branch[27];
}trinode;
int len,count;
trinode *createnode()
{
trinode *new=(trinode *)malloc(sizeof(trinode));
int ch;
for(ch=0;ch<27;ch++)
{
new->branch[ch]=NULL;
}
new->isend=0;
return new;
}
trinode *insert_trie(trinode *root,char *newenty)
{int ind;
trinode *proot;
if(root==NULL)
root=createnode();
proot=root;
for(int i=0;i<maxlength;i++)
{
ind=newenty[i]-'a';
if(newenty[i]=='\0')
break;
else
{
if(root->branch[ind]==NULL)
root->branch[ind]=createnode();
root=root->branch[ind];
}
}
if(root->isend!=0)
printf("trying to insert duplicate");
else
root->isend=1;
return proot;
}
void print_trie(trinode *cur)
{
int count;
char word[40];
for(int i=0;i<26;i++)
{
if(cur->branch[i]!=NULL)
{
word[count++]=(i+'a');
if((cur->branch[i]->isend)==1)
{
printf("\n");
for(int j=0;j<count;j++)
{
printf("%c",word[j]);
}
}
print_trie(cur->branch[i]);
}
}
count--;
}
int search_trie(trinode *root,char *target)
{
int ind;
for(int i=0;i<maxlength &&root;i++)
{
ind=target[i]-'a';
if(target[i]=='\0')
break;
else
root=root->branch[ind];
}
if(root && root->isend==1)
return 1;
else
return 0;
}
int main()
{
int ch;
trinode *root=NULL;
char *newenty;
char *target;
int check;
newenty = (char *)malloc(maxlength);
target= (char *)malloc(maxlength);
while(1)
{
printf("\n enter option 1.insert_trie 2.display 3.search 4.exit");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("enter word");
scanf("%s",newenty);
root=insert_trie(root,newenty);
break;
case 2:
count =0;
print_trie(root);
break;
case 3:
printf("enter elem you want to search");
scanf("%s",target);
check=search_trie(root,target);
if(check==0)
printf("word not found");
else
printf("found");
break;
case 4:
exit(0);
break;
}
}
}

I need help to convert from infix to postfix in C

I was practising some data structures problems that I did previously but this time I don't know what is going wrong in my code. I looked over a long time but I did not found the mistake. When I'm printing I'm just getting the first character and it looks like e is not being updated. But I've written e++.
#include<stdio.h>
#include "ctype.h"
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int priorityof(char x)
{
if(x=='(')
return 3;
else if(x=='+'|| x=='-')
return 1;
else if(x=='*'|| x=='/')
return 2;
}
int main()
{
char exp[20];
char *e;
e=exp;char x;
scanf("%c",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 (priorityof(stack[top]) >= priorityof(*e)) {
printf("%c", pop());
push(*e);
}
}
e++;
}
while(top!=-1)
{
printf("%c",pop());
}
}
%c is for single character and reading your question it seems like you are giving more than one character so its a string, use %s.
#include<stdio.h>
#include "ctype.h"
int stack[20]; int top = -1;
void push(int x) {
stack[++top] = x;
}
int pop() { return stack[top--]; }
int priorityof(char x) {
if(x=='(') return 3;
else if(x=='+'|| x=='-') return 1;
else if(x=='*'|| x=='/') return 2;
}
int main() {
char exp[20];
char *e;
e=exp;char x;
scanf("%s",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 (priorityof(stack[top]) >= priorityof(*e)) { printf("%c", pop()); push(*e); } } e++; } while(top!=-1) { printf("%c",pop()); } }

Evaluate postfix notation

I was doing my exercise but i stucked at the last step.
I have to evaluate postfix notation using stacks in C.
Code:
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct
{
int info;
}tipElement;
typedef struct
{
tipElement magacin [MAX];
int vrv;
}tipMagacin;
tipMagacin postfixStack;
void Inicijalizacija(tipMagacin *Mag)
{
(*Mag).vrv = -1; //warehouse is empty
}
int Prazen(tipMagacin Mag)
{
return(Mag.vrv == -1); //returns true if the warehouse is empty
}
int Poln(tipMagacin Mag)
{
return(Mag.vrv == MAX-1); //returns true if the warehouse is full
}
void Push(tipMagacin *Mag, tipElement Element)
{
if (Poln(*Mag)) printf("Warehouse is full\n"); //if it is full report an error
else
{
(*Mag).vrv++; //next position in the warehouse
(*Mag).magacin[(*Mag).vrv].info = Element.info; //put an element
}
}
void Pop(tipMagacin *Mag, tipElement *Element)
{
if (Prazen(*Mag)) printf("Warehouse is empty\n"); //if it is empty report an error
else
{
(*Element).info = (*Mag).magacin[(*Mag).vrv].info; //read the last element
(*Mag).vrv--; // delete it
}
}
int evaluate(int op1, int op2, char operate) {
switch (operate) {
case '*': return op2 * op1;
case '/': return op2 / op1;
case '+': return op2 + op1;
case '-': return op2 - op1;
default : return 0;
}
}
int evaluatePostfix (char *izraz, int n)
{
tipMagacin *Mag;
tipElement element;
tipElement go,z;
int i=0;
int op2;
char ch;
int value;
while (i < n) {
element.info = izraz[i];
if(isdigit(element.info))
{
Push(&postfixStack, element);
}
else
{
z=Pop(&postfixStack, &go);
op2=1;
value = evaluate(z,op2,ch);
Push(Mag,value);
}
i++;
}
return value;
}
my code works fine until here:
else
{
op1=Pop(&postfixStack, &go);
op2=Pop(&postfixStack, &go);
value = evaluate(op1,op2,element.info);
Push(&postfixStack, value);
}
i++;
}
return value;
}
the problem is: error: void value not ignored as it ought to be
my Push and Pop functions are void and i need to put the value that I remove from my stack to some int variable then i calculate them. put it doesnt put it for some reason i dont know.
Anyone help ?

Static stack operations in C

i'm trying to perform all operations(push, pop, peep, update, show) on stack using array in C.It's working fine when i am calling the show() at last after calling all of the functions that i need. But whenever i call show() before any of the operations than it is not giving me the appropiate result.
I'm using following code:
int main()
{
push(1);
push(2);
push(3);
push(4);
push(6);
pop();
push(5);
show();//line 8
//push(7);//line 9
//pop();
//peep();
//update();
//show();//line 13
return;
}
void push(int num){//insert an item
if(top==MAXSIZE-1)
{
printf("Overflow condition");
return;
}
top++;
stack[top]=num;
//return;
}
void pop()//delete a item from top
{
int num;
if(top==-1)
{
printf("Underflow condition");
return;
}
num=stack[top];
top--;
//return;
}
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
while(top!=-1){
printf("%d\n",stack[top--]);
}
//return;
}
void peep()//extract information
{
int loc,num;
printf("enter location:\n");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
num=stack[top-loc+1];
printf("\nItem at location %d is %d",loc,num);
}
}
void update(){//update information
int loc,item;
printf("enter new item:");
scanf("%d",&item);
printf("enter location:");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
stack[top-loc+1]=item;
printf("\nItem inserted");
}
}
Here after calling show(),top will point to -1(empty) at line 8,so after that following consequences will be:
push() will insert at position 1 instead of at top.
pop() will show underflow condition.
peep() and update will go in if condition.
So how can i set top to the top element in the stack after once calling the show()?
Thanks.
Your show() method modifies the top pointer and this is wrong:
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
while(top!=-1){
printf("%d\n",stack[top--]); // <--- here 'top--' will modify the top pointer
}
//return;
}
You can change the show() method like this:
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
int i = top; // introducing a new variable to iterate through the stack
while(i!=-1){
printf("%d\n",stack[i--]); // now 'i' is modified
}
//return;
}
One problem with your show function is that, it is also trying to pop out all the data. You should not be doing the top-- in your show function.
//WAP to perform Stack Operation usin C--
1. Push, 2.pop, 3.peep, 4.change, 5.top-of-stack, 6.is-empty, 7.is-full, 8.display
#include<stdlib.h>
#include<stdio.h>
#define max_size 5
int stack[max_size],top=-1,i,x;
/*------ Function Prototype------------*/
void push();
void pop();
void peep();
void display();
void top_stack();
void change();
void is_empty();
/*-------------------------------------*/
int main()
{
int choice;
do{
printf("\n\n--------STACK OPERATIONS-----------\n");
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Peep\n");
printf("4.Display\n");
printf("5.Change\n");
printf("6.TOP\n");
printf("7.exit\n");
printf("-----------------------");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: peep();
break;
case 4: display();
break;
case 5: change();
break;
case 6: top_stack();
break;
case 7: exit(0);
break;
default: printf("\nInvalid choice:\n");
break;
}
}while(choice!=7);
return 0;
}
void push() //Inserting element in to the stack
{
int item;
if(top==(max_size-1))
{
printf("\nStack Overflow:");
}
else
{
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop() //deleting an element from the stack
{
int item;
if(top==-1)
{
printf("Stack Underflow:");
}
else
{
item=stack[top];
top=top-1;
printf("\nThe poped element: %d\t",item);
}
}
void peep()
{
printf("enter the i th element");
scanf("%d",&i);
if(top-i+1<0)
{
printf("\nStack is empty:");
}
else
{
printf("The topmost element of the stack is %d",stack[top-i+1]);
}
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is Empty:");
}
else
{
printf("\nThe stack elements are:\n" );
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}
}
void change()
{
printf("enter the i th element");
scanf("%d",&i);
if(top-i+1<0)
{
printf("\nStack is empty:");
}
else
{
printf("enter the element to be changed\n");
scanf("%d",&x);
stack[top-i+1]=x ;
printf("The topmost element of the stack is %d",stack[top-i+1]);
}
}
void top_stack()
{
int t;
t=stack[top];
printf("The Topmost element of stack is =%d",t);
}

Stack of strings

Hi i have program here that accept int as value. i wanted to translate it to accept strings in array then. i have read about using struct but i couldnt get into it. i hope someone can help me getting into that without using struct i dont know where to start i want to keep this lines of code.
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
int top = 0;
int *stack = NULL;
int size = 0;
main()
{
int opt, num;
char cont[] = { 'y' };
clrscr();
/* <start Declaring Stack Size { */
printf("Stacking Program");
printf("\n\nData Size: ");
scanf("%d", &size);
printf("\n");
/* } end> */
/* <start Allocates size of stack { */
if(size > 0)
{
stack = malloc(size * sizeof(int));
if(stack == NULL)
{
printf("ERROR: malloc() failed\n");
exit(2);
}
}
else
{
printf("ERROR: size should be positive integer\n");
exit(1);
}
/* } end> */
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
/* <start Main Menu { */
printf("Stacking Program");
printf("\n\nData Size: %d\n\n", size);
printf("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
scanf("%d", &opt);
printf("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top==size)
{
printf("You can't push more data");
}
else
{
printf("Enter data for Stack[%d]: ", top+1);
scanf("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
printf("Your choice is not on the list.");
break;
}
/* } end> */
printf("\n\nDo you want continue\(Y\/N\)?");
scanf("%s", &cont[0]);
}
free(stack);
}
pop()
{
int a;
loading();
if(top <= 0)
{
printf("Stack empty.");
return 0;
}
else
{
top--;
a=stack[top];
printf("\(Stack[%d] = %d\) removed.", top+1, a);
}
}
push(int a)
{
stack[top]=a;
top++;
loading();
}
pick()
{
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
printf("\(Stack[%d] = %d\) is the last data.", top, stack[top-1]);
}
}
view()
{
int i;
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
for(i=0;i<top;i++)
{
printf("Stack[%d] = %d\n", i+1, stack[i]);
}
}
}
loading()
{
float i, x;
float load;
int loadarea[] = { 5000, 10000, 15000, 20000, 25000, 30000 };
int percentLoad;
x=0;
load=0;
percentLoad = loadarea[random(5)];
gotoxy(26,11);
printf("[");
for(i=0;i<25;i++)
{
x = i+27;
gotoxy(x, 11);
printf("=");
delay(percentLoad);
gotoxy(51,11);
printf("]");
gotoxy(53,11);
load=(i/25)*104.5;
if(load>100)
load = 100.00;
printf("%.2f\%",load);
}
delay(60000);
for(i=0;i<60;i++) {
printf("\b \b");
}
printf("\n");
}
Easiest way is to convert your stack to store char* instead of int.
char **stack;
stack = malloc( size * sizeof(char*) );
Now, your push operation will accept a char* from some buffer that is storing the string that was just input, duplicate it with strdup, and store that new pointer in the stack.
typedef enum {
STACK_MEM_ERROR = -1,
STACK_FULL = 0,
STACK_OK = 1
} StackStatus;
StackStatus push(const char *str)
{
char *newstr;
if( top >= size ) return STACK_FULL;
newstr = strdup(str);
if( newstr == NULL ) return STACK_MEM_ERROR;
stack[top++] = newstr;
return STACK_OK;
}
When you pop a string, you just get a pointer.
char *pop()
{
if( top == 0 ) return NULL;
return stack[--top];
}
You are responsible for freeing that memory when you are finished with the pointer (by calling free).
char * val;
while( NULL != (val = pop()) )
{
printf( "I popped: %s\n", val );
free(val);
}

Resources