// Valentin Rieuf
// This program checks for basic syntax of a source file, namely open
// braces, brackets, parenthesis
#include <stdio.h>
#define ON 1
#define OFF 0
#define ENCAPLEVELS 15
/* 1-24 K&R syntax checker */
void pop(int index, int array[]); /* unused */
void push(int index, int symbol, int array[]);
int main(void){
int c, stackTop, fail;
int stack[ENCAPLEVELS];
stackTop = -1;
fail = OFF;
while (((c
= getchar()) != EOF
) && (fail
== OFF
)){
if ((c == '}') || (c == ')') || (c == ']')){
if (stackTop == -1){
fail = ON;
break;
} else if (c == ')'){
if (c == (stack[stackTop] + 1)){
stackTop--;
} else {
fail = ON;
break;
}
} else {
if (c == (stack[stackTop] + 2)){
stackTop--;
} else {
fail = ON;
break;
}
}
} else if ((c == '{') || (c == '(') || (c == '[')){
stackTop++;
push(stackTop, c, stack);
}
}
printf("\nvalue of stackTop is %d \n", stackTop
); if (stackTop > -1){
fail = ON;
}
if (fail == ON){
printf("The syntax of this program is NOT balanced.\n"); } else {
printf("The program IS balanced.\n"); }
return 0;
}
void pop(int index, int array[]){
/* unused */
}
void push(int index, int symbol, int array[]){
array[index] = symbol;
}
Ly8gVmFsZW50aW4gUmlldWYKLy8gVGhpcyBwcm9ncmFtIGNoZWNrcyBmb3IgYmFzaWMgc3ludGF4IG9mIGEgc291cmNlIGZpbGUsIG5hbWVseSBvcGVuCi8vIGJyYWNlcywgYnJhY2tldHMsIHBhcmVudGhlc2lzCiNpbmNsdWRlIDxzdGRpby5oPgojZGVmaW5lIE9OIDEKI2RlZmluZSBPRkYgMAojZGVmaW5lIEVOQ0FQTEVWRUxTIDE1CgovKiAxLTI0IEsmUiBzeW50YXggY2hlY2tlciAqLwoKdm9pZCBwb3AoaW50IGluZGV4LCBpbnQgYXJyYXlbXSk7IC8qIHVudXNlZCAqLwp2b2lkIHB1c2goaW50IGluZGV4LCBpbnQgc3ltYm9sLCBpbnQgYXJyYXlbXSk7CgppbnQgbWFpbih2b2lkKXsKCglpbnQgYywgc3RhY2tUb3AsIGZhaWw7Cglpbn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ZXgsIGludCBhcnJheVtdKXsKCS8qIHVudXNlZCAqLwp9CnZvaWQgcHVzaChpbnQgaW5kZXgsIGludCBzeW1ib2wsIGludCBhcnJheVtdKXsKCWFycmF5W2luZGV4XSA9IHN5bWJvbDsKfQ==
CQlwcmludGYoJnF1b3Q7VGhlIHByb2dyYW0gSVMgYmFsYW5jZWQuXG4mcXVvdDspOwoJfQoKCXJldHVybiAwOwp9Cgp2b2lkIHBvcChpbnQgaW5kZXgsIGludCBhcnJheVtdKXsKCS8qIHVudXNlZCAqLwp9CnZvaWQgcHVzaChpbnQgaW5kZXgsIGludCBzeW1ib2wsIGludCBhcnJheVtdKXsKCWFycmF5W2luZGV4XSA9IHN5bWJvbDsKfQ==
printf("The program IS balanced.\n");
}
return 0;
}
void pop(int index, int array[]){
/* unused */
}
void push(int index, int symbol, int array[]){
array[index] = symbol;
}