Write a program called balanced that does the following: Prompts the user for a
ID: 3566587 • Letter: W
Question
Write a program called balanced that does the following:
Prompts the user for a string (see the get_string function from simpleio).
Determines if the given string is a balanced combination of the following six symbols:
( )
{ }
[ ]
Examples of balanced strings:
()
(())
()()
{()()}
[]
[()[]{}]()
Examples of unbalanced strings:
(
{}}
()[}
[()}
)
Program Behavior:
The program takes no command-line arguments. When run it prompts the user for a
string and then reports if it is legal or not. It then terminates.
Examples:
$ ./balanced
enter a string: {{}}()(){}
this string is balanced. Goodbye.
$ ./balanced
enter a string: {{)}()(){}
this string is not balanced. Goodbye.
Compilation:
We should be able to build the program by simply typing make balanced
This means that your submission must include all necessary files (makefile,
stack.h, stack.h, simpleio.h, simpleio.c).
Explanation / Answer
#include <stdio.h>
#include <string.h>
main()
{
char c[10];
printf("enter a string...");
scanf("%s",&c);
printf("%s",c);
int c1=0;
int c2=0;
int c3=0;
int c4=0;
int c5=0;
int c6=0;
int i=0;
for(i=0;i<10;i++)
{
if(c[i]=='{')c1++;
if(c[i]=='}')c2++;
if(c[i]=='[')c3++;
if(c[i]==']')c4++;
if(c[i]=='(')c5++;
if(c[i]==')')c6++;
}
if(c1==c2 && c3==c4 && c5==c6)
printf(" balanced string...");
else
printf(" Not a balanced string...");
}
o/p:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.