Slip 22 - A) Write a ‘C’ program which accept an Expression and check whether the expression is Parenthesized or not using stack. (Use Static/Dynamic implementation of Stack)

Solution:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int top = -1;
char stack[100];
// 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\n");
            exit(0);
      }
      else
      {
            top--;
      }
}
int main()
{
      int i,cho;
      char a[100];
      printf("\nEnter expression : ");
      scanf("%s",a);
      for (i = 0; a[i] != '\0';i++)
      {
            if (a[i] == '(')
            {
                  push(a[i]);
            }
            else if (a[i] == ')')
            {
                  pop();
            }
      }
      if (top == -1)
      {
            printf("Expression is Parenthesized\n\n");
      }
      else
      {
            printf("Expression is not Parenthesized\n\n");
      }
      return 0;
}

Post a Comment

0 Comments