Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

.

Name: Ameya Kalgurkar


Nikhil Kadam Class: D6ADA. 27
Roll No.: -
26

Title: Experiment 3 Parenthesis Matching

Aim: Application of Stacks – Parenthesis Matching

Theory:
Stacks are commonly used in programming for tasks like parenthesis matching. When
processing expressions, such as mathematical or programming code, stacks can help ensure
that parentheses are balanced and nested correctly. For example, you can use a stack to check
if every opening parenthesis has a corresponding closing parenthesis in the correct order. This
ensures the expression is syntactically valid. If you encounter an opening parenthesis, you push
it onto the stack, and when you encounter a closing parenthesis, you pop an opening
parenthesis from the stack. If the stack is empty at the end, all parentheses are matched
properly. If not, there’s a mismatch.

Stacks are used for parenthesis matching:


1. Introduction:
Parenthesis matching is a common problem in computer science where you need to determine
if a given expression containing parentheses is properly balanced. A balanced expression has
all opening and closing parentheses matched in the correct order.

2. Stack Approach:
The stack data structure is well-suited for solving this problem due to its Last-In-First-Out (LIFO)
behavior. Here’s how the stack approach works:

o Initialize an empty stack to keep track of opening parentheses.


o Iterate through each character in the expression.
o If the character is an opening parenthesis (‘(‘, ‘{‘, ‘[‘), push it onto the stack.
o If the character is a closing parenthesis (‘)’, ‘}’, ‘]’), pop the top element from the
stack and compare it with the current closing parenthesis. If they match,
continue; otherwise, the expression is not balanced.
o After processing all characters, if the stack is empty, the expression is balanced.
If the stack is not empty, there are unmatched opening parentheses.

3. Implementation in Java:
In Java, you can implement the above approach using the `Stack` class from the `java.util`
package. The `Stack` class provides methods like `push`, `pop`, `isEmpty`, and `peek` that are
useful for managing the stack.

4. Complexity:
The time complexity of this algorithm is O(n), where n is the length of the expression. Each
character is processed once, and push and pop operations on the stack are constant time
operations.
5. Error Handling:
The stack-based approach allows you to detect errors, such as unmatched parentheses or
incorrect nesting, and pinpoint the location of the error in the expression.

6. Applications:
Beyond parenthesis matching, the stack approach is applicable to other problems involving
proper nesting, such as checking the syntax of programming language constructs, evaluating
expressions, and parsing markup languages.

7. Benefits:
Using stacks for parenthesis matching provides an organized and efficient solution. It’s a classic
example of how data structures like stacks are pivotal for maintaining order and structure in
programming and computational tasks.

Using stacks for parenthesis matching is just one application of stacks in computer science.
Stacks are versatile data structures that are used in various scenarios where elements need to
be added and removed in a Last-In-First-Out (LIFO) manner.
Code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#define MAX_SIZE 100

Struct Stack {
Int top;
Char items[MAX_SIZE];
};

Void initialize(struct Stack *s) {


s->top = -1;
}

Bool isEmpty(struct Stack *s) {


Return s->top == -1;
}

Bool isFull(struct Stack *s) {


Return s->top == MAX_SIZE – 1;
}

Void push(struct Stack *s, char c) {


If (!isFull(s)) {
s->items[++(s->top)] = c;
} else {
Printf(“Stack is full\n”);
}
}

Char pop(struct Stack *s) {


If (!isEmpty(s)) {
Return s->items[(s->top)--];
} else {
Printf(“Stack is empty\n”);
Return ‘\0’;
}
}

Bool isBalanced(const char *expression) {


Struct Stack stack;
Initialize(&stack);

For (int I = 0; expression[i] != ‘\0’; i++) {


If (expression[i] == ‘(‘ || expression[i] == ‘[‘ || expression[i] == ‘{‘) {
Push(&stack, expression[i]);
} else if (expression[i] == ‘)’ || expression[i] == ‘]’ || expression[i] == ‘}’) {
If (isEmpty(&stack)) {
Return false;
}
Char top = pop(&stack);
If ((expression[i] == ‘)’ && top != ‘(‘) ||
(expression[i] == ‘]’ && top != ‘[‘) ||
(expression[i] == ‘}’ && top != ‘{‘)) {
Return false;
}
}
}

Return isEmpty(&stack);
}

Int main() {
Char expression[MAX_SIZE];
Printf(“Enter an expression: “);
Scanf(“%s”, expression);

If (isBalanced(expression)) {
Printf(“Parentheses are balanced.\n”);
} else {
Printf(“Parentheses are not balanced.\n”);
}

Return 0;
}
Output:

Conclusion: Using stacks for parenthesis matching in Java is like using a special tool to make
sure that parentheses in a math problem or a code are properly balanced. Imagine you’re
building a tower with different types of blocks: opening blocks like “{“, “(“, “[“ and closing blocks
like “}”, “)”, “]”. You want to make sure that for every opening block you use, there’s a matching
closing block, and they’re in the right order.

You might also like