# Print the balanced bracket expression using given brackets in C Program

CServer Side ProgrammingProgramming

Given four variables a, b, c, d with predefined values that will print the given bracket depending upon the variable 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, if we cannot form a balanced bracket expression then print -1. In case of multiple answers we can print any of the multiple answers which can be formed using the given brackets.

## Example

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

To achieve this result we can, first check if the balanced bracket expression can be formed with the given number of brackets or not. If the expression can be made by given number of brackets then we will.

• Print the number of type 1 brackets.
• Print the number of type 3 brackets.
• Print the number of type 4 brackets.
• Print the number of type 2 brackets.

Below is the algorithm and implementation of the approach.

## 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’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'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 above program then it will generate following output

(((((()()()()())))))()()
Published on 22-Aug-2019 06:24:14