In programming ( and ) are called parenthesis and are commonly used in mathematical expressions like 3 + (6 / 2)

If total number of opening ( is equal to total number of closing ) then the expression is said to have balanced parenthesis.

- no. of ( is equal to no. of )
- Extra no. of (
- Extra no. of )

Case 1 gives a balanced expression.

While case 2 and case 3 gives an unbalanced expression.

We will use variable **bf** to measure balance factor. bf will tell whether the expression is balanced or not.

```
Initially set bf = 0
Scan the expression from left to right.
For each ( increment bf by 1
For each ) decrement bf by 1
Continue scanning as long as bf >= 0
After scanning is complete
If bf == 0 then we have a balanced expression
Else an unbalanced expression
```

```
/*
* balanced parenthesis
*/
#include <stdio.h>
int main(){
//variables
char expr[100];
int bf = 0; //balance factor
int i;
//input
printf("Enter expression: ");
scanf("%s", &expr);
//scan
i = 0;
while(expr[i] != '\0'){
if(expr[i] == '(')
bf++;
else if(expr[i] == ')'){
bf--;
if(bf < 0)
break; //terminate search
}
i++;
}
//output
if(bf == 0)
printf("Balanced parenthesis.\n");
else
printf("Unbalanced.\n");
return 0;
}
```

Recently Added

- How to create thumbnail by resizing image in PHP using dyreimage-php DYReImage-PHP
- Getting Started DYReImage-PHP
- PHPUnit - Hello World Test PHPUnit
- PHPUnit - Getting Started PHPUnit
- DSLR - How to read camera lens DSLR
- jQuery - Traversal Methods jQuery
- jQuery - Selectors jQuery
- jQuery - Getting Started jQuery
- jQuery - Introduction jQuery
- Dijkstra Algorithm - Finding Shortest Path Graph