Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
What I have tried:

the program 1.evaluates postfix and prefix expressions2.reverse a string3.parathesis balancing 4.decimal to binary conversion5.infix to postfix conversion
there a some extra characters(emojis) appended in the output of dec to binary conversion and prefix evaluation. please help me with that.
this a first year college project..all suggestion are most welcome.
also please suggest demerits and how we could better this project more.

What I have tried:

#include<stdio.h>
#include<ctype.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
int stack[MAX],opp1,opp2,top=-1;

struct stack {
  char stck[20];
  int top;
}s;
void push(int x)
	{   
		top++;
		stack[top]=x;
	}
int pop()
	{   
	    char c;
	    c=stack[top];
	    top=top-1;
	    printf("%c",c);
	}
char pop1()
{
    if(top == -1)
        return -1;
    else
        return stack[top--];
}
postfixeval()
{
	char postfix[20];
	int res,i;
	gets(postfix);
	for(i=0;postfix[i]!='\0';i++)
	{
		if(isdigit(postfix[i]))
		{
		 push(postfix[i]-48);
		}
		else
		{
		opp2=pop();
		opp1=pop();
		switch(postfix[i])
		{
			case '+':push(opp1+opp2);
			         break;
			case '-':push(opp1-opp2);
			         break;
		    case '*':push(opp1*opp2);
			         break;
			case '/':push(opp1/opp2);
			         break;
			case '^':res=pow(opp1,opp2);
			         break;
		}
		
	   }
   }   
	printf("result is %d \n",pop());
}
 prefixeval()
{ 
    int len;
	char prefix[20];
	int res,i;
	gets(prefix);
	len=strlen(prefix);
	for(i=len-1;i>=0;i--)
	{
		if(isdigit(prefix[i]))
		{
		 push(prefix[i]-48);
		}
		else
		{
		opp1=pop();
		opp2=pop();
		switch(prefix[i])
		{
			case '+':push(opp1+opp2);
			         break;
			case '-':push(opp1-opp2);
			         break;
		    case '*':push(opp1*opp2);
			         break;
			case '/':push(opp1/opp2);
			         break;
			case '^':res=pow(opp1,opp2);
			         push(res);
			         break;
		}
		
	   }
   }   
	printf("result is %d \n",pop());
}

int match(char a,char b)
{
        if(a=='[' && b==']')
                return 1;
        if(a=='{' && b=='}')
                return 1;
        if(a=='(' && b==')')
                return 1;
        return 0;
}
int check(char exp[] )
{
        int i;
        char temp;
        for(i=0;i<strlen(exp);i++)
        {
                if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[')
                        push(exp[i]);
                if(exp[i]==')' || exp[i]=='}' || exp[i]==']')
                        if(top==-1) 
                        {
                                return 0;
                        }
                        else
                        {
                                temp=pop();
                                if(!match(temp, exp[i]))
                                {
                                        printf("Mismatched parentheses are : ");
                                        printf("%c and %c\n",temp,exp[i]);
                                        return 0;
                                }
                        }
        }
        if(top==-1) 
        {
                printf("Balanced Parentheses\n");
                return 1;
        }
        else
        {
                return 0;
        }
}
dectobin(int n)
{
	while(n!=0)
	{
		push(n%2);
		n=n/2;
	}
	while(top!=-1)
	{
		printf("%d",pop());
	}
	stack[top]='\0';
}
int priority(char x)
{
    if(x == '(')
        return 0;
    if(x == '+' || x == '-')
        return 1;
    if(x == '*' || x == '/')
        return 2;
    return 0;
}
void intopost()
{
    char exp[100];
    char *e, x;
    printf("Enter the expression : \n");
    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 = pop1()) != '(')
                printf("%c ", x);
        }
        else
        {
            while(priority(stack[top]) >= priority(*e))
                printf("%c ",pop1());
            push(*e);
        }
        e++;
    }
    
    while(top != -1)
    {
        printf("%c ",pop1());
    }
}



int main()
{
	int ch,i,len;
	char postfix[20],prefix[20],str[30];
	do
	{
	printf("\n----STACK APPLICATIONS----\n");
	printf("1.postfix expression evaluation\n2.prefix expression evaluation\n3.reverse a string\n4.paranthesis balancing\n5.decimal to binary\n6.infix to postfix\n7.exit\n");
	printf("enter choice");
	scanf("%d",&ch);
	switch(ch)
	{ 
	  case 1: 
	       {
	          printf("enter postfix expression\n");
	          scanf("%c",&postfix);
			  postfixeval();
	          break;
	        }
	  case 2: 
	       {
	  
	          printf("enter prefix expression\n");
	          scanf("%c",prefix);
	          prefixeval();
	          break;
	        }
	  case 3: 
	        { 
			  printf("enter string\n");
	          scanf("%s",str);
			  len=strlen(str);
			  for(i=0;i<len;i++)
			  {
			  	push(str[i]);
			  }
			  printf("reversed string is:");
			  for(i=0;i<len;i++)
			  {
			  	pop();
			  }
			  break;
		    }
	  case 4: 
	       {
	
	           char exp[20];
			   int valid;
               printf("Enter an algebraic expression : \n");
               scanf("%s",exp);
               valid=check(exp);
               if(valid==1)
                 {
				 printf("Valid expression\n");
		       	 }
               else
                 {
                 printf("Invalid expression\n");
                 } 
	           break;	
			}   
	  case 5:
	       {
	           int dec;
	           printf("enter decimal number\n");
	           scanf("%d",&dec);
	           dectobin(dec);
	           break;
	        }
	  case 6:
	       {   
		       intopost();
	           break;
	       }
	  case 7:
	  	    {
	  	    	exit(0);
			}
	  default: printf("invalid choice\n");
	         
	}
   }while(ch!=7);
}
Posted
Updated 18-Aug-22 11:11am
v4
Comments
Rick York 18-Aug-22 15:15pm    
You need to revise your question. Your code should go in the "what I've tried" section and your statement should be asked as the question.
palak rathore 18-Aug-22 16:09pm    
done
Rick York 18-Aug-22 16:42pm    
OK, the code was missing the pre tags and was corrupted when pasted. There are a lot of extraneous '=""' strings in there.
palak rathore 18-Aug-22 16:48pm    
sorry,I am new to this site
correction done
Rick York 18-Aug-22 17:12pm    
that looks a lot better.

Advice: Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes.
C++
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define MAX 20
int stack[MAX], opp1, opp2, top = -1;

struct stack
{
	char stck[20];
	int top;
}
s;
void push(int x)
{
	top++;
	stack[top] = x;
}
int pop()
{
	char c;
	c = stack[top];
	top = top - 1;
	printf("%c", c);
}
char pop1()
{
	if (top == -1)
		return -1;
	else
		return stack[top--];
}
postfixeval()
{
	char postfix[20];
	int res, i;
	gets(postfix);
	for (i = 0; postfix[i] != '\0'; i++)
	{
		if (isdigit(postfix[i]))
		{
			push(postfix[i] - 48);
		}
		else
		{
			opp2 = pop();
			opp1 = pop();
			switch (postfix[i])
			{
				case '+':
					push(opp1 + opp2);
					break;
				case '-':
					push(opp1 - opp2);
					break;
				case '*':
					push(opp1 *opp2);
					break;
				case '/':
					push(opp1 / opp2);
					break;
				case '^':
					res = pow(opp1, opp2);
					break;
			}
		}
	}
	printf("result is %d \n", pop());
}
prefixeval()
{
	int len;
	char prefix[20];
	int res, i;
	gets(prefix);
	len = strlen(prefix);
	for (i = len - 1; i >= 0; i--)
	{
		if (isdigit(prefix[i]))
		{
			push(prefix[i] - 48);
		}
		else
		{
			opp1 = pop();
			opp2 = pop();
			switch (prefix[i])
			{
				case '+':
					push(opp1 + opp2);
					break;
				case '-':
					push(opp1 - opp2);
					break;
				case '*':
					push(opp1 *opp2);
					break;
				case '/':
					push(opp1 / opp2);
					break;
				case '^':
					res = pow(opp1, opp2);
					push(res);
					break;
			}
		}
	}
	printf("result is %d \n", pop());
}

int match(char a, char b)
{
	if (a == '[' && b == ']')
		return 1;
	if (a == '{' && b == '}')
		return 1;
	if (a == '(' && b == ')')
		return 1;
	return 0;
}
int check(char exp[])
{
	int i;
	char temp;
	for (i = 0; i < strlen(exp); i++)
	{
		if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
			push(exp[i]);
		if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
			if (top == -1)
			{
				return 0;
			}
		else
		{
			temp = pop();
			if (!match(temp, exp[i]))
			{
				printf("Mismatched parentheses are : ");
				printf("%c and %c\n", temp, exp[i]);
				return 0;
			}
		}
	}
	if (top == -1)
	{
		printf("Balanced Parentheses\n");
		return 1;
	}
	else
	{
		return 0;
	}
}
dectobin(int n)
{
	while (n != 0)
	{
		push(n % 2);
		n = n / 2;
	}
	while (top != -1)
	{
		printf("%d", pop());
	}
	stack[top] = '\0';
}
int priority(char x)
{
	if (x == '(')
		return 0;
	if (x == '+' || x == '-')
		return 1;
	if (x == '*' || x == '/')
		return 2;
	return 0;
}
void intopost()
{
	char exp[100];
	char *e, x;
	printf("Enter the expression : \n");
	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 = pop1()) != '(')
				printf("%c ", x);
		}
		else
		{
			while (priority(stack[top]) >= priority(*e))
				printf("%c ", pop1());
			push(*e);
		}
		e++;
	}

	while (top != -1)
	{
		printf("%c ", pop1());
	}
}

int main()
{
	int ch, i, len;
	char postfix[20], prefix[20], str[30];
	do {
		printf("\n----STACK APPLICATIONS----\n");
		printf("1.postfix expression evaluation\n2.prefix expression evaluation\n3.reverse a string\n4.paranthesis balancing\n5.decimal to binary\n6.infix to postfix\n7.exit\n");
		printf("enter choice");
		scanf("%d", &ch);
		switch (ch)
		{
			case 1:
				{
					printf("enter postfix expression\n");
					scanf("%c", &postfix);
					postfixeval();
					break;
				}
			case 2:
				{

					printf("enter prefix expression\n");
					scanf("%c", prefix);
					prefixeval();
					break;
				}
			case 3:
				{
					printf("enter string\n");
					scanf("%s", str);
					len = strlen(str);
					for (i = 0; i < len; i++)
					{
						push(str[i]);
					}
					printf("reversed string is:");
					for (i = 0; i < len; i++)
					{
						pop();
					}
					break;
				}
			case 4:
				{

					char exp[20];
					int valid;
					printf("Enter an algebraic expression : \n");
					scanf("%s", exp);
					valid = check(exp);
					if (valid == 1)
					{
						printf("Valid expression\n");
					}
					else
					{
						printf("Invalid expression\n");
					}
					break;
				}
			case 5:
				{
					int dec;
					printf("enter decimal number\n");
					scanf("%d", &dec);
					dectobin(dec);
					break;
				}
			case 6:
				{
					intopost();
					break;
				}
			case 7:
				{
					exit(0);
				}
			default:
				printf("invalid choice\n");
		}
	} while (ch != 7);
}

Indentation style - Wikipedia[^]
Best C++ Formatter and Beautifier[^]
Online C/C++ Formatter, Indenter and Beautifier – Techie Delight[^]

Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[^]
ultraedit[^]
Enabling Open Innovation & Collaboration | The Eclipse Foundation[^]
 
Share this answer
 
Comments
palak rathore 18-Aug-22 17:05pm    
thankyou for your help! also unwanted additional characters are appended with the output of this code can you help me with that!?
is there some way can add pictures here so that i can share the picture of final output?
Patrice T 18-Aug-22 17:09pm    
Use Improve question to update your question.
So that everyone can pay attention to this information.
Start by looking at your code: a casual glance shows duplicated code which should be refactored; magic numbers; a total absence of comments; inconsistent indentation; ... basically all the hallmarks of code which wasn't planned, but evolved.

Think about what a well presented app will look like, and how it could be designed to be expanded. For example, how would you add negative numbers to it? Functions like square root, or sine?

Then think about how what you have could fit into that "shape".
 
Share this answer
 
I really don't see how this can even compile but it's so corrupted I'm sure there was a lot lost in translation. This section in particular looks off :
dectobin(int n)
{
   while(n!=0)
      push(n%2);
   n=n/2;
   while( top!=-1 )
      printf("%d",pop());
   stack[top]="\0" ;  // <-----
}
First, there is no return type but it appears to be void. Worse, variable stack at location top is assigned an empty string. That is an integer value declared as
int stack[MAX]
so you can not assign a string to it. As I wrote, I don't know how this can even compile. A statement like
stack[top] = 0;
would me more appropriate there.

One other thing - this code is in dire need of limit checking and organization. Limits need to be checked because you have an array of integers of size MAX and a global variable is used to index into it but I see only one place where the value of that index is validated - in pop1(), and it's never called. You will have unpredictable results if that index ever becomes negative or it equals or exceeds MAX.

It needs organization because there are too many global variables. There really should not be any and for something like this there does not need to be any. All functions that operate on the stack should take that variable as an argument. In fact, you could have all of those global variables be members of a data structure and a pointer to that structure could be the argument passed to all of the functions. That would be a big improvement over what you have now. Actually, I see that you have a structure set up called a stack so you are almost ready to go. Change the type of stck to int and that will be essentially what you have with the separate items. The variables opp1 and opp2 should NOT be globals because they only used locally in a couple of functions.

Here is one function converted to use the stack passed as an argument :
C++
typedef struct stack
{
   int stck[MAX];
   int top;
};

void initStack( stack * pstack )
{
   if( ! pstack )
       return;           // received null pointer
   pstack->top = -1;     // stack is empty
}

int push( stack * pstack, int x )
{
   if( ! pstack )
       return 0;         // received null pointer
   if( pstack->top >= MAX )
       return 0;         // stack is already full

   pstack->top++;
   pstack->stck[ top ] = x;
   return 1;             // success
}

// usage example

int main(void)
{
   stack s;              // declare an instance of a stack
   initStack( & s );     // initialize the stack
   push( & s, 42 );      // add an entry to the stack

   return 0;
}
 
Share this answer
 
Comments
Rick York 18-Aug-22 17:13pm    
I took so long writing all that it seems you have a corrected a problem I mentioned.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900