Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

4. [20 points] Every C++ compiler (or any compiler, for that matter) often begin

ID: 3738535 • Letter: 4

Question

4. [20 points] Every C++ compiler (or any compiler, for that matter) often begins by checking if you closed every parentheses you opened in a program text. For example, a fragment such as if (a-b) tb b c; is faulty because a closing parentheses (') is missing after the if statement. Using stacks, write a function that checks if every open parentheses is indeed closed in a program text. The function should return 1' on success, and 1' on failure. Lets call this int checkParantheses Assume your program has access to a function called char readChar) that returns the next character in a program text. Read all characters until you hit the end of file, or EOF. By the time you hit EOF, the # of open parantheses should match the # of closing parantheses. To get you started, the following statements should read all characters in the text and keep storing them in a variable called nextChar for your perusal: char nextChar - readChar while (nextChar -EOF) nextChar readChar() ;

Explanation / Answer

Hello There,

PFB method for requested functionality with comments specifying the functionality.

-----------------------------------------------------

int checkParantheses(){

stack<int> openParantheses;

char nextChar = readChar();

while(nextChar != EOF){

if(nextChar == '{'){

openParantheses.push(nextChar); // push opening parantheses into the stack

}else if(nextChar == '}'){

if(!openParantheses.empty()){

openParantheses.pop(); // pop an opening parantheses for every closing parantheses encountered

}else{

return -1; // no opening parantheses matching closing parantheses

}

}

nextChar = readChar();

}

if(openParantheses.empty()){

return 1; // when all open parantheses has a matching closing parantheses

}else{

return -1; // when there are extra opening parantheses

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote