Write a program to check the mathematical expressions contai

Write a program to check the mathematical expressions containing the following parentheses for validity:

                (

                [

                {

Hint: {(6 – 2) * 8} is a valid expression. [3 + (6 * 7) } is an invalid expression.

Solution

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int top = -1;
char stack[100];

// function prototypes
void push(char);
void pop();
void find_top();

void main()
{
   int i;
   char a[100];
   printf(\"enter expression\ \");
   scanf(\"%s\", &a);
   for (i = 0; a[i] != \'\\0\';i++)
   {
       if (a[i] == \'(\')
       {
           push(a[i]);
       }
       else if(a[i]==\'{\')
{

push(a[i]);
}
else if(a[i]==\'[\')
{

push(a[i]);
}
       else if (a[i] == \')\')
       {
           pop();
       }
       else if(a[i]==\'}\')
{

pop();
}
else if(a[i]=\']\')
{

pop();
}
   }
   find_top();
}

// to push elements in stack
void push(char a)
{
   stack[top] = a;
   top++;
}

// to pop elements from stack
void pop()
{
   if (top == -1)
   {
       printf(\"expression is invalid\ \");
       exit(0);
   }
   else
   {
       top--;
   }
}

// to find top element of stack
void find_top()
{
   if (top == -1)
       printf(\"\ expression is valid\ \");
   else
       printf(\"\ expression is invalid\ \");
}

------------------------------------------------------------------------------------------------------------------------

out put

enter expression
{3+(2*3))
expression is invalid

Write a program to check the mathematical expressions containing the following parentheses for validity: ( [ { Hint: {(6 – 2) * 8} is a valid expression. [3 + (
Write a program to check the mathematical expressions containing the following parentheses for validity: ( [ { Hint: {(6 – 2) * 8} is a valid expression. [3 + (

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site