Write a program that will take a string as input.
The program will then determine whether each
left parenthesis '(' has a matching right
parenthesis). If so, the program will print 0
else the program will print 1.
For example,
For the input provided as follows:
HELLO AND (WELCOME (TO THE) TCEA
(CONTEST)TODAY) IS (SATURDAYO)
The output of the program will be:
0
Another example,
For the input provided as follows:
(9x(7-2)* (15)
The output of the program will be:
1
Answers
Answered by
0
Answer:
#include <iostream>
using namespace std;
int main() {
string str;
cout<<"Enter the string: ";
getline(cin, str);
cout<<str;
if((getline(str,'('))&&(getline(str,')')))
{
cout<<"0";
}
else
{
cout<<"1";
}
return 0;
}
Explanation:
- We first declare the variables that will be used in the program. Since the program has to take a string as input, we declare the variable str of the string data type.
- Next statement of the program displays a message on the screen asking the user to enter a string.
- The string is read and stored using the getline function. The getline function reads and stores every character of the string including spaces.
- The next step is to check every character for the presence of parentheses. To do this, we use the if-else loop.
- The expression first checks whether '(' is present in the entire string. If it is present, then the expression gives a logic high result.
- Similarly, the expression then checks whether ')' is present in the entire string. If it is present, then the expression gives a logic high result.
- The results of both the expressions are logically ANDed.
- If both the results are high, it implies that a pair of parenthesis is present and the if statement block is executed which prints the output as zero.
- If either one of the results is low, it implies that a pair of parenthesis is not present and the else statement block is executed which prints the output as one.
- After printing the output, the program is terminated.
#SPJ3
Similar questions