Skip to content

Instantly share code, notes, and snippets.

@sid24rane
Created September 28, 2016 17:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sid24rane/7ea2fa2d13f7c3ee950a15f4c975482c to your computer and use it in GitHub Desktop.
Save sid24rane/7ea2fa2d13f7c3ee950a15f4c975482c to your computer and use it in GitHub Desktop.
Balanced Parenthesis in C using stack
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX_SIZE 100
struct Stack{
int top;
char arr[MAX_SIZE];
} st;
void init(){
st.top = -1;
}
bool isEmpty(){
if(st.top == -1){
return true;
}else{
return false;
}
}
bool isFull(){
if(st.top == MAX_SIZE-1){
return true;
}else{
return false;
}
}
void push(char item){
if(isFull()){
printf("Stack is full");
}else{
st.top++;
st.arr[st.top] = item;
}
}
void pop(){
if(isEmpty()){
printf("Stack is empty");
}else{
st.top--;
}
}
char gettop(){
return st.arr[st.top];
}
bool ArePair(char opening,char closing)
{
if(opening == '(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '[' && closing == ']') return true;
return false;
}
void main()
{
char in_expr[MAX_SIZE];
int length=0,i,j;
init();
printf("Enter an expression to check:");
gets(in_expr);
length = strlen(in_expr);
for(i=0;i<length;i++){
if(in_expr[i] == '(' || in_expr[i] == '{' || in_expr[i] == '['){
push(in_expr[i]);
}else if(in_expr[i] == ')' || in_expr[i] == '}' || in_expr[i] == ']'){
char a = gettop();
printf("%c",a);
if(isEmpty() || !ArePair(gettop(),in_expr[i])){
printf("\nResult - Invalid expression - Not a Balanced one !");
return 0;
}else{
pop();
}
}
}
if(isEmpty()){
printf("\nResult - Valid expression - Perfectly Balanced !");
}else{
printf("\nResult - Invalid expression - Not a Balanced one !");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment