Home >Backend Development >C++ >Print balanced bracket expression in C program using given brackets

Print balanced bracket expression in C program using given brackets

王林
王林forward
2023-09-09 23:13:021202browse

Print balanced bracket expression in C program using given brackets

Given four variables a, b, c, d, which have predefined values, print the given brackets according to the variables used.

Where variable,

a for ((
b for ()
c for )(
d for ))

The task is to use all the given brackets and print the balanced bracket expression, or print -1 if the balanced bracket expression cannot be formed. If there are multiple answers, we can print any of the multiple answers formed using the given brackets.

Example

Input: a = 3, b = 2, c = 4, d = 3
Output : (((((()()()()())))))()()

To achieve this result, we can first check whether a balanced bracket expression can be formed with a given number of brackets. If the expression can be constructed from a given number of parentheses, then we can.

  • Print type 1 The number of brackets.
  • The number of print types is 3 brackets.
  • Print type 4 The number of brackets.
  • Print type 2 The number of brackets.

The following is the algorithm and implementation of the method.

Algorithm

START
Step 1 -> Declare Function void print(int a, int b, int c, int d) Declare int i
   IF ((a == d && a) || (a == 0 && c == 0 && d == 0))
      Loop For i=1 and i<=a and i++
         Print ((
      End
      Loop For i=1 and i<=c and i++
         Print )(
      End
      Loop For i=1 and i<=d and i++
         Print ))
      End
      Loop For i=1 and i<=b and i++
         Print ()
      End
   Else
      Print can&rsquo;t be formed
Step 2 -> main()
   Declare int a = 3, b = 2, c = 4, d = 3
   Call print(a,b,c,d)
STOP

Example

#include<stdio.h>
void print(int a, int b, int c, int d){
   int i;
   if ((a == d && a) || (a == 0 && c == 0 && d == 0)){
      for (i = 1; i <= a; i++)
         printf("((");
      for (i = 1; i <= c; i++)
         printf(")(");
      for (i = 1; i <= d; i++)
         printf("))");
      for (i = 1; i <= b; i++)
         printf("()");
   }
   else
      printf("can&#39;t be formed");
}
int main(){
   int a = 3, b = 2, c = 4, d = 3;
   print(a, b, c, d);
   return 0;
}

Output

If we run the above program then it will generate the following output

(((((()()()()())))))()()

The above is the detailed content of Print balanced bracket expression in C program using given brackets. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete