Skip to content

Instantly share code, notes, and snippets.

@suhailgme
Created February 11, 2017 02:02
Show Gist options
  • Save suhailgme/126adde9004f8cfe43f7ed8faa222db9 to your computer and use it in GitHub Desktop.
Save suhailgme/126adde9004f8cfe43f7ed8faa222db9 to your computer and use it in GitHub Desktop.
#include "stack.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int i;
char input[256], closing;
fprintf(stderr, "Enter parantheses and/or braces: ");
// takes all of the input entered by the user and stores it in the character
// array called input.
fgets(input, 256, stdin);
// Iterate through each character of the string stored in input.
for (i = 0; i < strlen(input) - 1; i++) {
// if an opening parantheses or brace is encountered, push it to the stack.
if (input[i] == '(' || input[i] == '{') {
push(input[i]);
// if a closing parantheses is encountered, pop the last item from the
// stack.
} else if (input[i] == ')') {
closing = pop();
// if popped item is a matching opening parantheses, continue iterating,
// otherwise break from the loop.
if (closing == '(') {
continue;
} else {
// this is for the case where the last parantheses or braces popped
// results in an empty stack and a mismatched pair. An empty stack
// indicates proper nesting and this is not the case, therefore, push
// the popped item back onto the stack and break from the loop.
push(closing);
break;
}
} else if (input[i] == '}') {
closing = pop();
if (closing == '{') {
continue;
} else {
push(closing);
break;
}
}
}
//
if (is_empty()) {
printf("Parentheses are nested properly\n");
} else {
printf("Parentheses are not nested properly\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment