SlideShare a Scribd company logo
1 of 14
Download to read offline
Given an expression string exp, write a java class ExpressionCheccker whose main method gets
exp in the input line of terminal and examines whether the pairs and the orders of ”(“,”)”,”[“,”]”
are correct in exp. For example, the program should print true for exp =“[()][()()]()” and false for
exp = “[(])”. ( Use stack)
Ans:
Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the
popped character is the matching starting bracket then fine else parenthesis are not balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”
Program:
#include
#include
#define bool int
/* structure of a stack node */
struct sNode
{
char data;
struct sNode *next;
};
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
int i = 0;
/* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
/* If exp[i] is a ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
return 0;
/* Pop the top element from stack, if it is not a pair
parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf(" Balanced ");
else
printf(" Not Balanced ");
return 0;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
/*If stack is empty then error */
if (*top_ref == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
#include
#include
#define bool int
/* structure of a stack node */
struct sNode
{
char data;
struct sNode *next;
};
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
int i = 0;
/* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
/* If exp[i] is a ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
return 0;
/* Pop the top element from stack, if it is not a pair
parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf(" Balanced ");
else
printf(" Not Balanced ");
return 0;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
/*If stack is empty then error */
if (*top_ref == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
Solution
Given an expression string exp, write a java class ExpressionCheccker whose main method gets
exp in the input line of terminal and examines whether the pairs and the orders of ”(“,”)”,”[“,”]”
are correct in exp. For example, the program should print true for exp =“[()][()()]()” and false for
exp = “[(])”. ( Use stack)
Ans:
Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the
popped character is the matching starting bracket then fine else parenthesis are not balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”
Program:
#include
#include
#define bool int
/* structure of a stack node */
struct sNode
{
char data;
struct sNode *next;
};
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
int i = 0;
/* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
/* If exp[i] is a ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
return 0;
/* Pop the top element from stack, if it is not a pair
parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf(" Balanced ");
else
printf(" Not Balanced ");
return 0;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
/*If stack is empty then error */
if (*top_ref == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
#include
#include
#define bool int
/* structure of a stack node */
struct sNode
{
char data;
struct sNode *next;
};
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
int i = 0;
/* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
/* If exp[i] is a ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
return 0;
/* Pop the top element from stack, if it is not a pair
parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf(" Balanced ");
else
printf(" Not Balanced ");
return 0;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
/*If stack is empty then error */
if (*top_ref == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}

More Related Content

Similar to Given an expression string exp, write a java class ExpressionCheccke.pdf

Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfmohdjakirfb
 
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxMETA-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxandreecapon
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxshericehewat
 
Data Structure Lecture 2
Data Structure Lecture 2Data Structure Lecture 2
Data Structure Lecture 2Teksify
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab ManualAkhilaaReddy
 
Implement the ADT stack by using an array stack to contain its entri.pdf
Implement the ADT stack by using an array stack to contain its entri.pdfImplement the ADT stack by using an array stack to contain its entri.pdf
Implement the ADT stack by using an array stack to contain its entri.pdfSIGMATAX1
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
 

Similar to Given an expression string exp, write a java class ExpressionCheccke.pdf (20)

week-15x
week-15xweek-15x
week-15x
 
7 stacksqueues
7 stacksqueues7 stacksqueues
7 stacksqueues
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
 
Stack
StackStack
Stack
 
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxMETA-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Data Structure Lecture 2
Data Structure Lecture 2Data Structure Lecture 2
Data Structure Lecture 2
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
 
Implement the ADT stack by using an array stack to contain its entri.pdf
Implement the ADT stack by using an array stack to contain its entri.pdfImplement the ADT stack by using an array stack to contain its entri.pdf
Implement the ADT stack by using an array stack to contain its entri.pdf
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 

More from info382133

1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf
1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf
1.) Main characteristics of Haloarchaea are as followsHalophiles .pdfinfo382133
 
1. The three bacteria that may be implicated in the given case are S.pdf
1. The three bacteria that may be implicated in the given case are S.pdf1. The three bacteria that may be implicated in the given case are S.pdf
1. The three bacteria that may be implicated in the given case are S.pdfinfo382133
 
1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf
1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf
1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdfinfo382133
 
1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf
1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf
1. Activation of Vit. D involves Kidney and Liver and liver is part .pdfinfo382133
 
Rf = (distance the spot traveled)L there are fou.pdf
                     Rf = (distance the spot traveled)L there are fou.pdf                     Rf = (distance the spot traveled)L there are fou.pdf
Rf = (distance the spot traveled)L there are fou.pdfinfo382133
 
No. Since sodium chloride is an ionic compound, i.pdf
                     No. Since sodium chloride is an ionic compound, i.pdf                     No. Since sodium chloride is an ionic compound, i.pdf
No. Since sodium chloride is an ionic compound, i.pdfinfo382133
 
Nacl is highly ionic in nature. where as CaO is s.pdf
                     Nacl is highly ionic in nature. where as CaO is s.pdf                     Nacl is highly ionic in nature. where as CaO is s.pdf
Nacl is highly ionic in nature. where as CaO is s.pdfinfo382133
 
it is reduced as it accepts e- and goes from 0 to.pdf
                     it is reduced as it accepts e- and goes from 0 to.pdf                     it is reduced as it accepts e- and goes from 0 to.pdf
it is reduced as it accepts e- and goes from 0 to.pdfinfo382133
 
Iodine test is used to see if a compound has star.pdf
                     Iodine test is used to see if a compound has star.pdf                     Iodine test is used to see if a compound has star.pdf
Iodine test is used to see if a compound has star.pdfinfo382133
 
I have no clue! .pdf
                     I have no clue!                                  .pdf                     I have no clue!                                  .pdf
I have no clue! .pdfinfo382133
 
C only III is major product .pdf
                     C only III is major product                      .pdf                     C only III is major product                      .pdf
C only III is major product .pdfinfo382133
 
Borane-THF is flammable and highly reactive with .pdf
                     Borane-THF is flammable and highly reactive with .pdf                     Borane-THF is flammable and highly reactive with .pdf
Borane-THF is flammable and highly reactive with .pdfinfo382133
 
Ubiquity Internet is available everywhere namely at home, at work v.pdf
Ubiquity Internet is available everywhere namely at home, at work v.pdfUbiquity Internet is available everywhere namely at home, at work v.pdf
Ubiquity Internet is available everywhere namely at home, at work v.pdfinfo382133
 
Water is the most used resource in our day to day life . When the wa.pdf
Water is the most used resource in our day to day life . When the wa.pdfWater is the most used resource in our day to day life . When the wa.pdf
Water is the most used resource in our day to day life . When the wa.pdfinfo382133
 
The initiation of the sporulation of the bacteria is a complex cellu.pdf
The initiation of the sporulation of the bacteria is a complex cellu.pdfThe initiation of the sporulation of the bacteria is a complex cellu.pdf
The initiation of the sporulation of the bacteria is a complex cellu.pdfinfo382133
 
The emissivity of a given surface is the measure of its ability to e.pdf
The emissivity of a given surface is the measure of its ability to e.pdfThe emissivity of a given surface is the measure of its ability to e.pdf
The emissivity of a given surface is the measure of its ability to e.pdfinfo382133
 
Power set={SolutionPower set={.pdf
Power set={SolutionPower set={.pdfPower set={SolutionPower set={.pdf
Power set={SolutionPower set={.pdfinfo382133
 
bro Solutionbro .pdf
bro Solutionbro .pdfbro Solutionbro .pdf
bro Solutionbro .pdfinfo382133
 
ANSWER Accounting concepts and conventions In dr.pdf
                     ANSWER Accounting concepts and conventions  In dr.pdf                     ANSWER Accounting concepts and conventions  In dr.pdf
ANSWER Accounting concepts and conventions In dr.pdfinfo382133
 
As ions are charged species a strong interactions.pdf
                     As ions are charged species a strong interactions.pdf                     As ions are charged species a strong interactions.pdf
As ions are charged species a strong interactions.pdfinfo382133
 

More from info382133 (20)

1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf
1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf
1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf
 
1. The three bacteria that may be implicated in the given case are S.pdf
1. The three bacteria that may be implicated in the given case are S.pdf1. The three bacteria that may be implicated in the given case are S.pdf
1. The three bacteria that may be implicated in the given case are S.pdf
 
1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf
1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf
1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf
 
1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf
1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf
1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf
 
Rf = (distance the spot traveled)L there are fou.pdf
                     Rf = (distance the spot traveled)L there are fou.pdf                     Rf = (distance the spot traveled)L there are fou.pdf
Rf = (distance the spot traveled)L there are fou.pdf
 
No. Since sodium chloride is an ionic compound, i.pdf
                     No. Since sodium chloride is an ionic compound, i.pdf                     No. Since sodium chloride is an ionic compound, i.pdf
No. Since sodium chloride is an ionic compound, i.pdf
 
Nacl is highly ionic in nature. where as CaO is s.pdf
                     Nacl is highly ionic in nature. where as CaO is s.pdf                     Nacl is highly ionic in nature. where as CaO is s.pdf
Nacl is highly ionic in nature. where as CaO is s.pdf
 
it is reduced as it accepts e- and goes from 0 to.pdf
                     it is reduced as it accepts e- and goes from 0 to.pdf                     it is reduced as it accepts e- and goes from 0 to.pdf
it is reduced as it accepts e- and goes from 0 to.pdf
 
Iodine test is used to see if a compound has star.pdf
                     Iodine test is used to see if a compound has star.pdf                     Iodine test is used to see if a compound has star.pdf
Iodine test is used to see if a compound has star.pdf
 
I have no clue! .pdf
                     I have no clue!                                  .pdf                     I have no clue!                                  .pdf
I have no clue! .pdf
 
C only III is major product .pdf
                     C only III is major product                      .pdf                     C only III is major product                      .pdf
C only III is major product .pdf
 
Borane-THF is flammable and highly reactive with .pdf
                     Borane-THF is flammable and highly reactive with .pdf                     Borane-THF is flammable and highly reactive with .pdf
Borane-THF is flammable and highly reactive with .pdf
 
Ubiquity Internet is available everywhere namely at home, at work v.pdf
Ubiquity Internet is available everywhere namely at home, at work v.pdfUbiquity Internet is available everywhere namely at home, at work v.pdf
Ubiquity Internet is available everywhere namely at home, at work v.pdf
 
Water is the most used resource in our day to day life . When the wa.pdf
Water is the most used resource in our day to day life . When the wa.pdfWater is the most used resource in our day to day life . When the wa.pdf
Water is the most used resource in our day to day life . When the wa.pdf
 
The initiation of the sporulation of the bacteria is a complex cellu.pdf
The initiation of the sporulation of the bacteria is a complex cellu.pdfThe initiation of the sporulation of the bacteria is a complex cellu.pdf
The initiation of the sporulation of the bacteria is a complex cellu.pdf
 
The emissivity of a given surface is the measure of its ability to e.pdf
The emissivity of a given surface is the measure of its ability to e.pdfThe emissivity of a given surface is the measure of its ability to e.pdf
The emissivity of a given surface is the measure of its ability to e.pdf
 
Power set={SolutionPower set={.pdf
Power set={SolutionPower set={.pdfPower set={SolutionPower set={.pdf
Power set={SolutionPower set={.pdf
 
bro Solutionbro .pdf
bro Solutionbro .pdfbro Solutionbro .pdf
bro Solutionbro .pdf
 
ANSWER Accounting concepts and conventions In dr.pdf
                     ANSWER Accounting concepts and conventions  In dr.pdf                     ANSWER Accounting concepts and conventions  In dr.pdf
ANSWER Accounting concepts and conventions In dr.pdf
 
As ions are charged species a strong interactions.pdf
                     As ions are charged species a strong interactions.pdf                     As ions are charged species a strong interactions.pdf
As ions are charged species a strong interactions.pdf
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Given an expression string exp, write a java class ExpressionCheccke.pdf

  • 1. Given an expression string exp, write a java class ExpressionCheccker whose main method gets exp in the input line of terminal and examines whether the pairs and the orders of ”(“,”)”,”[“,”]” are correct in exp. For example, the program should print true for exp =“[()][()()]()” and false for exp = “[(])”. ( Use stack) Ans: Algorithm: 1) Declare a character stack S. 2) Now traverse the expression string exp. a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack. b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced. 3) After complete traversal, if there is some starting bracket left in stack then “not balanced” Program: #include #include #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct sNode** top_ref); /* Returns 1 if character1 and character2 are matching left and right Parenthesis */ bool isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']')
  • 2. return 1; else return 0; } /*Return 1 if expression has balanced Parenthesis */ bool areParenthesisBalanced(char exp[]) { int i = 0; /* Declare an empty character stack */ struct sNode *stack = NULL; /* Traverse the given expression to check matching parenthesis */ while (exp[i]) { /*If the exp[i] is a starting parenthesis then push it*/ if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); /* If exp[i] is a ending parenthesis then pop from stack and check if the popped parenthesis is a matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { /*If we see an ending parenthesis without a pair then return false*/ if (stack == NULL) return 0; /* Pop the top element from stack, if it is not a pair parenthesis of character then there is a mismatch. This happens for expressions like {(}) */ else if ( !isMatchingPair(pop(&stack), exp[i]) ) return 0; } i++; } /* If there is something left in expression then there is a starting parenthesis without a closing parenthesis */ if (stack == NULL)
  • 3. return 1; /*balanced*/ else return 0; /*not balanced*/ } /* UTILITY FUNCTIONS */ /*driver program to test above functions*/ int main() { char exp[100] = "{()}[]"; if (areParenthesisBalanced(exp)) printf(" Balanced "); else printf(" Not Balanced "); return 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow "); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref)
  • 4. { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL) { printf("Stack overflow "); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } } #include #include #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct sNode** top_ref); /* Returns 1 if character1 and character2 are matching left and right Parenthesis */ bool isMatchingPair(char character1, char character2) {
  • 5. if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']') return 1; else return 0; } /*Return 1 if expression has balanced Parenthesis */ bool areParenthesisBalanced(char exp[]) { int i = 0; /* Declare an empty character stack */ struct sNode *stack = NULL; /* Traverse the given expression to check matching parenthesis */ while (exp[i]) { /*If the exp[i] is a starting parenthesis then push it*/ if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); /* If exp[i] is a ending parenthesis then pop from stack and check if the popped parenthesis is a matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { /*If we see an ending parenthesis without a pair then return false*/ if (stack == NULL) return 0; /* Pop the top element from stack, if it is not a pair parenthesis of character then there is a mismatch. This happens for expressions like {(}) */ else if ( !isMatchingPair(pop(&stack), exp[i]) ) return 0; } i++;
  • 6. } /* If there is something left in expression then there is a starting parenthesis without a closing parenthesis */ if (stack == NULL) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* UTILITY FUNCTIONS */ /*driver program to test above functions*/ int main() { char exp[100] = "{()}[]"; if (areParenthesisBalanced(exp)) printf(" Balanced "); else printf(" Not Balanced "); return 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow "); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref);
  • 7. /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref) { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL) { printf("Stack overflow "); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } } Solution Given an expression string exp, write a java class ExpressionCheccker whose main method gets exp in the input line of terminal and examines whether the pairs and the orders of ”(“,”)”,”[“,”]” are correct in exp. For example, the program should print true for exp =“[()][()()]()” and false for exp = “[(])”. ( Use stack) Ans: Algorithm: 1) Declare a character stack S. 2) Now traverse the expression string exp. a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
  • 8. b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced. 3) After complete traversal, if there is some starting bracket left in stack then “not balanced” Program: #include #include #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct sNode** top_ref); /* Returns 1 if character1 and character2 are matching left and right Parenthesis */ bool isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']') return 1; else return 0; } /*Return 1 if expression has balanced Parenthesis */ bool areParenthesisBalanced(char exp[]) { int i = 0; /* Declare an empty character stack */ struct sNode *stack = NULL;
  • 9. /* Traverse the given expression to check matching parenthesis */ while (exp[i]) { /*If the exp[i] is a starting parenthesis then push it*/ if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); /* If exp[i] is a ending parenthesis then pop from stack and check if the popped parenthesis is a matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { /*If we see an ending parenthesis without a pair then return false*/ if (stack == NULL) return 0; /* Pop the top element from stack, if it is not a pair parenthesis of character then there is a mismatch. This happens for expressions like {(}) */ else if ( !isMatchingPair(pop(&stack), exp[i]) ) return 0; } i++; } /* If there is something left in expression then there is a starting parenthesis without a closing parenthesis */ if (stack == NULL) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* UTILITY FUNCTIONS */ /*driver program to test above functions*/ int main() { char exp[100] = "{()}[]"; if (areParenthesisBalanced(exp))
  • 10. printf(" Balanced "); else printf(" Not Balanced "); return 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow "); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref) { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL) { printf("Stack overflow "); getchar(); exit(0); }
  • 11. else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } } #include #include #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct sNode** top_ref); /* Returns 1 if character1 and character2 are matching left and right Parenthesis */ bool isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']') return 1; else return 0; } /*Return 1 if expression has balanced Parenthesis */
  • 12. bool areParenthesisBalanced(char exp[]) { int i = 0; /* Declare an empty character stack */ struct sNode *stack = NULL; /* Traverse the given expression to check matching parenthesis */ while (exp[i]) { /*If the exp[i] is a starting parenthesis then push it*/ if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); /* If exp[i] is a ending parenthesis then pop from stack and check if the popped parenthesis is a matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { /*If we see an ending parenthesis without a pair then return false*/ if (stack == NULL) return 0; /* Pop the top element from stack, if it is not a pair parenthesis of character then there is a mismatch. This happens for expressions like {(}) */ else if ( !isMatchingPair(pop(&stack), exp[i]) ) return 0; } i++; } /* If there is something left in expression then there is a starting parenthesis without a closing parenthesis */ if (stack == NULL) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* UTILITY FUNCTIONS */
  • 13. /*driver program to test above functions*/ int main() { char exp[100] = "{()}[]"; if (areParenthesisBalanced(exp)) printf(" Balanced "); else printf(" Not Balanced "); return 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow "); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref) { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL)
  • 14. { printf("Stack overflow "); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } }