Advertisement
annie_02

zad_brackets

Jan 12th, 2023
717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. //TRY THIS OUT
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. int top = -1;
  8. char s[100];
  9.  
  10. void balanced_parentheses(){
  11. int i,l;
  12. char exp[100],x,y;
  13. printf("Enter the exp: \n");
  14. scanf("%s",exp);
  15. l = strlen(exp);
  16. for(i = 0;i<l;i++){
  17. if(exp[i]=='(' || exp[i]=='{' || exp[i]=='['){
  18. x = exp[i];
  19. push(exp[i]);
  20. }
  21. else if(exp[i]==')' || exp[i]=='}' || exp[i]==']'){
  22. y = exp[i];
  23. pop(y);
  24. }
  25. }
  26. }
  27.  
  28. void push(char x){
  29. top++;
  30. s[top] = x;
  31. }
  32.  
  33. void pop(char y){
  34. if(y==')'){
  35. if(s[top]=='('){
  36. top=top-1;
  37. }
  38. }
  39. else if(y=='}'){
  40. if(s[top]=='{'){
  41. top = top-1;
  42. }
  43. }
  44. else if(y==']'){
  45. if(s[top]=='['){
  46. top = top-1;
  47. }
  48. }
  49. else{
  50. return "\0";
  51. }
  52. }
  53.  
  54. void Print(){
  55. int i;
  56. if(top==-1){
  57. printf("\nThey are balanced parentheses");
  58. }
  59. else{
  60. printf("\nFALSE! not balanced ones..because\n");
  61.  
  62.     for(i=0;i<=top;i++){
  63.         if(s[top]=='('){
  64.                 printf("You should end with: ')' ");
  65.            }
  66.         else if(s[top]=='{'){
  67.             printf("You should end with: '}' ");
  68.         }
  69.         else if(s[top]=='['){
  70.             printf("You should end with: ']'");
  71.         }
  72.         else{
  73.             printf("INVALID expression here!");
  74.         }
  75.         return;
  76.     }
  77.  
  78. }
  79. }
  80.  
  81. int main(){
  82. balanced_parentheses();
  83. Print();
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement