# Structure of Bracket Validation Problem

shebom640
c_cpp
a year ago
2.2 kB
8
Indexable
Never
```// Question 1
// Structure of Bracket Validation Problem

#include<stdio.h>
#include<stdlib.h>
char stack[10];
int top =-1;
void push(char);
void pop();
int eval(char[]);
int main()
{
char expr[30];
int result;
printf("\n Enter the expression");
scanf("%[^\n]s",expr);
printf("\n The input string is: %s",expr);
result = eval(expr);
if(result)
printf("\n It is a valid expression");
else
printf("\n It is an invalid expression.");
}
int eval(char expr[])
{
int i = 0,valid;
char ch;
while(expr[i]!='\0')
{
//If opening Bracket push it in the stack
//If closing Bracket pop from the bracket
i++;
}
if(top==-1)
valid = 1;
else
valid = 0;
return valid;
}
void push(char num)
{
//Push Algorithm
}
void pop()
{
//Pop algorithm
}

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 30

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

void push(char);
void pop();
int eval(char[]);
int main()
{
char expr[MAX_SIZE];
int result;

printf("\n Enter the expression: ");
scanf("%[^\n]s", expr);

printf("\n The input string is: %s", expr);
result = eval(expr);

if (result)
printf("\n It is a valid expression.");
else
printf("\n It is an invalid expression.");

return 0;
}

int eval(char expr[])
{
int i = 0, valid;
char ch;

while (expr[i] != '\0')
{
ch = expr[i];

if (ch == '(' || ch == '[' || ch == '{')
{
push(ch);
}
else if (ch == ')' || ch == ']' || ch == '}')
{
if (top == -1)
{
return 0;
}

char topBracket = stack[top];

if ((ch == ')' && topBracket == '(') ||
(ch == ']' && topBracket == '[') ||
(ch == '}' && topBracket == '{'))
{
pop();
}
else
{
return 0;
}
}

i++;
}

if (top == -1)
valid = 1;
else
valid = 0;

return valid;
}

void push(char ch)
{
if (top < MAX_SIZE - 1)
{
top++;
stack[top] = ch;
}

}

void pop()
{
if (top >= 0)
{
top--;
}

}
```