Q 1.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 3
int stack [MAX_SIZE];
int top = -1;
void push(int value)
{
if(top==MAX_SIZE-1) {
printf("Stack Overflow (Full): Cannot Push Element (%d) onto the stack.\n", value);
}
else {
top++;
stack[top] = value;
printf("Element (%d) Pushed Onto The Stack.\n", value);
}
}
void pop()
{
if(top == -1) {
printf("Stack Underflow (Empty): Cannot Pop Element From The Stack.\n");
}
else {
printf("\nElement (%d) Popped From The Stack.\n", stack[top]);
top--;
}
}
void display()
{
if(top == -1) {
printf("Stack is Empty.\n");
}
else {
printf("Stack Elements are: ");
for(int i=top; i>=0; i--) {
printf("%d, ",stack[i]);
}
printf("\n");
}
}
int main() {
push(10);
push(20);
display();
push(50);
push(100);
display();
pop();
display();
pop();
pop();
display();
return 0;
}
//OUTPUT:
Element (10) Pushed Onto The Stack.
Element (20) Pushed Onto The Stack.
Stack Elements are: 20, 10,
Element (50) Pushed Onto The Stack.
Stack Overflow (Full): Cannot Push Element (100) onto the stack.
Stack Elements are: 50, 20, 10,
Element (50) Popped From The Stack.
Stack Elements are: 20, 10,
Element (20) Popped From The Stack.
Element (10) Popped From The Stack.
Stack is Empty.
Q3.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
char stack[MAX_SIZE];
int top = -1;
void push(char data) {
if (top == MAX_SIZE - 1) {
printf("Overflow stack!\n");
return;
}
top++;
stack[top] = data;
}
char pop() {
if (top == -1) {
printf("Empty stack!\n");
return ' ';
}
char data = stack[top];
top--;
return data;
}
int is_matching_pair(char char1, char char2) {
if (char1 == '(' && char2 == ')') {
return 1;
} else if (char1 == '[' && char2 == ']') {
return 1;
} else if (char1 == '{' && char2 == '}') {
return 1;
} else {
return 0;
}
}
int isBalanced(char* text) {
int i;
for (i = 0; i < strlen(text); i++) {
if (text[i] == '(' || text[i] == '[' || text[i] == '{') {
push(text[i]);
} else if (text[i] == ')' || text[i] == ']' || text[i] == '}') {
if (top == -1) {
return 0;
} else if (!is_matching_pair(pop(), text[i])) {
return 0;
}
}
}
if (top == -1) {
return 1;
} else {
return 0;
}
}
int main() {
char text[MAX_SIZE];
printf("Input an expression in parentheses: ");
scanf("%s", text);
if (isBalanced(text)) {
printf("The expression is balanced.\n");
} else {
printf("The expression is not balanced.\n");
}
return 0;
}
//OUTPUT:
Input an expression in parentheses: {[({[]})]}
The expression is balanced.
Input an expression in parentheses: [{[}]]
The expression is not balanced.