balancing paranthesis

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Basic:

/*

* C Program to Check if Expression is correctly Parenthesized

*/

#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\n");

scanf("%s", &a);
for (i = 0; a[i] != '\0';i++)

if (a[i] == '(')

push(a[i]);

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\n");

exit(0);

else

top--;

// to find top element of stack

void find_top()

if (top == -1)

printf("\nexpression is valid\n");

else

printf("\nexpression is invalid\n");

}
Advanced:
#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#define MAX 20

struct stack

char stk[MAX];

int top;

}s;

void push(char item)

if (s.top == (MAX - 1))

printf ("Stack is Full\n");

else

s.top = s.top + 1; // Push the char and increment top

s.stk[s.top] = item;

}}

void pop()

if (s.top == - 1)

{
printf ("Stack is Empty\n");

else

s.top = s.top - 1; // Pop the char and decrement top

}}

int main()

char exp[MAX];

int i = 0;

s.top = -1;

printf("\nINPUT THE EXPRESSION : ");

scanf("%s", exp);

for(i = 0;i < strlen(exp);i++)

if(exp[i] == '(' || exp[i] == '[' || exp[i] == '{')

push(exp[i]); // Push the open bracket

continue;

else if(exp[i] == ')' || exp[i] == ']' || exp[i] == '}')

// If a closed bracket is encountered

if(exp[i] == ')')
{

if(s.stk[s.top] == '(')

pop(); // Pop the stack until closed bracket is found

else

printf("\nUNBALANCED EXPRESSION\n");

break;

}}

if(exp[i] == ']')

if(s.stk[s.top] == '[')

pop(); // Pop the stack until closed bracket is found

else

printf("\nUNBALANCED EXPRESSION\n");

break;

}}

if(exp[i] == '}')

if(s.stk[s.top] == '{')

{
pop(); // Pop the stack until closed bracket is found

else

printf("\nUNBALANCED EXPRESSION\n");

break;

}}}}

if(s.top == -1)

printf("\nBALANCED EXPRESSION\n"); // Finally if the stack is empty, display that the expression is
balanced

}}

You might also like