fork download
  1. // Valentin Rieuf
  2. // This program checks for basic syntax of a source file, namely open
  3. // braces, brackets, parenthesis
  4. #include <stdio.h>
  5. #define ON 1
  6. #define OFF 0
  7. #define ENCAPLEVELS 15
  8.  
  9. /* 1-24 K&R syntax checker */
  10.  
  11. void pop(int index, int array[]); /* unused */
  12. void push(int index, int symbol, int array[]);
  13.  
  14. int main(void){
  15.  
  16. int c, stackTop, fail;
  17. int stack[ENCAPLEVELS];
  18.  
  19. stackTop = -1;
  20. fail = OFF;
  21.  
  22. while (((c = getchar()) != EOF) && (fail == OFF)){
  23.  
  24. if ((c == '}') || (c == ')') || (c == ']')){
  25. if (stackTop == -1){
  26. fail = ON;
  27. break;
  28. } else if (c == ')'){
  29. if (c == (stack[stackTop] + 1)){
  30. stackTop--;
  31. } else {
  32. fail = ON;
  33. break;
  34. }
  35. } else {
  36. if (c == (stack[stackTop] + 2)){
  37. stackTop--;
  38. } else {
  39. fail = ON;
  40. break;
  41. }
  42. }
  43. } else if ((c == '{') || (c == '(') || (c == '[')){
  44. stackTop++;
  45. push(stackTop, c, stack);
  46. }
  47. }
  48.  
  49. printf("\nvalue of stackTop is %d \n", stackTop);
  50. if (stackTop > -1){
  51. fail = ON;
  52. }
  53.  
  54. if (fail == ON){
  55. printf("The syntax of this program is NOT balanced.\n");
  56. } else {
  57. printf("The program IS balanced.\n");
  58. }
  59.  
  60. return 0;
  61. }
  62.  
  63. void pop(int index, int array[]){
  64. /* unused */
  65. }
  66. void push(int index, int symbol, int array[]){
  67. array[index] = symbol;
  68. }
Success #stdin #stdout 0s 2116KB
stdin
		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;
}
stdout
value of stackTop is -1 
The syntax of this program is NOT balanced.