Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print the balanced bracket expression using given brackets in C Program
Given four variables a, b, c, d with predefined values that represent different types of bracket pairs. The task is to use all the given brackets and print a balanced bracket expression using these bracket types.
Where variables represent −
a for (( b for () c for )( d for ))
If we cannot form a balanced bracket expression then print "can't be formed". In case of multiple valid answers, we can print any of them.
Syntax
void print(int a, int b, int c, int d);
Algorithm
To form a balanced expression, we need to ensure that the number of opening brackets equals the number of closing brackets. The condition for a valid balanced expression is −
- Either a equals d and both are non-zero (equal opening and closing double brackets)
- Or a, c, and d are all zero (only complete bracket pairs)
The printing order is: (( brackets first, then )( brackets, then )) brackets, and finally () brackets.
Example
#include <stdio.h>
void print(int a, int b, int c, int d) {
int i;
/* Check if balanced expression can be formed */
if ((a == d && a) || (a == 0 && c == 0 && d == 0)) {
/* Print (( brackets */
for (i = 1; i <= a; i++)
printf("((");
/* Print )( brackets */
for (i = 1; i <= c; i++)
printf(")(");
/* Print )) brackets */
for (i = 1; i <= d; i++)
printf("))");
/* Print () brackets */
for (i = 1; i <= b; i++)
printf("()");
printf("<br>");
}
else {
printf("can't be formed<br>");
}
}
int main() {
int a = 3, b = 2, c = 4, d = 3;
printf("Input: a = %d, b = %d, c = %d, d = %d<br>", a, b, c, d);
printf("Output: ");
print(a, b, c, d);
return 0;
}
Input: a = 3, b = 2, c = 4, d = 3 Output: (((((()()()()())))))()()
How It Works
The algorithm works by −
-
Validation: Check if a balanced expression is possible using the condition
(a == d && a) || (a == 0 && c == 0 && d == 0) - Pattern Formation: Print brackets in the sequence that ensures balance: opening doubles, middle pairs, closing doubles, complete pairs
-
Balance Maintenance: The
)(brackets maintain internal balance while((and))provide outer structure
Conclusion
This solution efficiently generates balanced bracket expressions by validating input constraints and following a specific printing order. The key insight is that balanced expressions require equal opening and closing brackets with proper nesting structure.
