i need a program that inputs at least 10 characters only parenthesis and dermine the input if balance?
gray01
2009-01-16 00:32:10 UTC
i want to add my program that can determine when i input parenthesis and outputs if its balance or not. ex. ((())) balance, ))((()() not balance. or if entered another character will output like this message. "error" like a letter or numbers.
Three answers:
codrguy
2009-01-16 00:40:17 UTC
here it is in C:
#include
#include
main() {
char in[100];
printf("Enter your input : ");
scanf("%s",in);
int balanced=0;
if ( strlen(in) % 2 != 0 )
{
printf("not balance");
return 0;
}
for ( int i=0; i < strlen(in)/2; i++)
{
if ( in[i] != '(' && in[i] != ')' )
{
printf("ERROR : invalid input detected. the only valid input characters are ( or ).\n");
}
if ( in[i] =='(' && in[strlen(in) - i - 1] != ')' )
{
printf("not balance");
return 0;
}
if ( in[i] =='}' && in[strlen(in) - i - 1] != '(' )
{
printf("not balance");
return 0;
}
}
printf("BALANCE");
return 0;
}
videobobkart
2009-01-16 16:46:04 UTC
Navid's solution will not work on something like this: '()(())' which probably should be considered as balanced (every open parenthesis is matched by a close parenthesis). Another detail is whether you want to consider something like this: ')(' as balanced. In my solution below, a single line controls this aspect of the check for balanced (as mentioned in the comment before the line).
#include
static int balanced(char *s)
{
int d=0;
while (*s != '\0')
{ if (*s == '(') ++d;
else if (*s == ')') --d;
else printf("error\n");
//comment the line below out if you want to allow things like ')(':
if (d<0) return 0;
++s;
}
return d==0;
}
int main ( )
{
char in[100];
printf("Enter input: ");
fflush(stdout);
scanf("%s",in); // no check for buffer overflow
if (balanced(in))
printf("balanced\n");
else
printf("unbalanced\n");
return 0;
}
Nivedita
2009-01-16 00:43:45 UTC
I can tell you in brief.
If the character is ( push it on to a stack( array). When you find ), remove an element from the stack. If the stack is empty, then the input is balanced.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.