I am writing a few computer programs that require recursion for an assignment, a
ID: 3756890 • Letter: I
Question
I am writing a few computer programs that require recursion for an assignment, and I have so far been able to complete some of the assignments, but I am seriously lost on how to do the next one.... It is a C++ program that will take in a line of braces, brackets, and parenthesis with different values mixed in here is an example of the input... {{((a-d)*x+z)qiq}ddfeg} The program needs to use recursion in an array, it should first read the number of characters entered, and set the array to that size. Second it should check to see if there is an equal number of parenthesis, brackets, and braces, and ignore any of the other characters in between. If all the brackets, braces, and parenthesis have a match, then the program should report that it is balanced, and if not it should report that it is not balanced. For the example input above, the output should be... {{((a-d)*x+z)qiq}ddfeg} The sequence {{((a-d)*x+z)qiq}ddfeg} is balanced If the input was changed to {{((a-d)*x+z)qiqddfeg} where not all braces, brackets, and parens have a match... The sequence {{((a-d)*x+z)qiqdddfeg} is not balanced
Explanation / Answer
#include <iostream>
#include <string>
#include <cstring>
char * match (char *str) {
if( *str == '' || *str == ')' || *str == '}')
return str;
if( *str == '(' ) {
char *closer = match(++str);
if( *closer == ')' )
return match(++closer);
return str - 1;
}
if( *str == '{' ) {
char *closer = match(++str);
if( *closer == '}' )
return match(++closer);
return str - 1;
}
return match(++str);
}
int main() {
std::string s;
std::cin >> s;
char str[s.size() + 1];
strcpy(str, s.c_str());
const char * result = match(str);
if(*result == '')
std::cout << "The sequence " << s << " is balanced ";
else
std::cout << "The sequence " << s << " is not balanced ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.