Home >Backend Development >C++ >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.
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.
The following is the algorithm and implementation of the method.
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’t be formed Step 2 -> main() Declare int a = 3, b = 2, c = 4, d = 3 Call print(a,b,c,d) STOP
#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't be formed"); } int main(){ int a = 3, b = 2, c = 4, d = 3; print(a, b, c, d); return 0; }
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!