Question

Complete the following C program to solve the parenthesis matching problem using a stack. We studied...

Complete the following C program to solve the parenthesis matching problem using a stack. We studied the problem and the algorithm in class. Given a sequence of chars (symbols), check if each “(”, “{”, or “[” is paired with a matching “)”, “}”, or “[”. For example,

  1. correct: ( )(( )){([( )])}    
  2. correct: (( )(( ))){([( )])}  
  3. incorrect: )(( )){([( )])}    
  4. incorrect: ({[ ])}    
  5. incorrect: (  

#include <stdio.h>

#include <stdlib.h>

#define size 100

void push(char *s, int* top, char element);

char pop(char *s, int *top);

int full(int *top, const int size);

int empty(int *top);

void init(int *top);

void init(int *top)

{*top = 0;

}

void push(char *s, int* top, char element)

{s[(*top)++] = element;

}

char pop(char *s, int *top)

{return s[--(*top)];

}

int full(int *top, const int size)

{return *top == size ? 1 : 0;

}

int empty(int *top)

{return *top == 0 ? 1 : 0;

}

void main(){

int top;

char element;

char stack[size];

init(&top);

//You are required to complete the following:

//read a sequence of chars

//check if each parenthesis matches with the correct one; print error message if not.

//you can define variables and arrays that you need.

}

Homework Answers

Answer #1

CODE SNAPSHOTS:

OUTPUT SNAPSHOTS:

CODE:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 100

bool check(char *par, char *s, int *top);
void push(char *s, int *top, char element);
char pop(char *s, int *top);
int full(int *top, const int size);
int empty(int *top);
void init(int *top)
{
    *top = 0;
}
void push(char *s, int *top, char element)
{
    s[(*top)++] = element;
}
char pop(char *s, int *top)
{
    return s[--(*top)];
}
int full(int *top, const int size)
{
    return *top == size ? 1 : 0;
}
int empty(int *top)
{
    return *top == 0 ? 1 : 0;
}
bool check(char *par, char *s, int *top)
{
    for (int i = 0; par[i] != '\0'; i++)
    {
        if (par[i] == '(' || par[i] == '{' || par[i] == '[')
            push(s, top, par[i]);
        else
        {
            if (empty(top))
                return false;
            char ele = pop(s, top);
            bool flag = false;
            switch (par[i])
            {
            case ')':
                if (ele == '(')
                    flag = true;
                break;
            case '}':
                if (ele == '{')
                    flag = true;
                break;
            case ']':
                if (ele == '[')
                    flag = true;
                break;
            default:
                flag = false;
                break;
            }
            if (!flag)
                return false;
        }
    }
    if (empty(top))
        return true;
    return false;
}
int main()
{
    int top;
    char stack[SIZE];
    init(&top);
    char paranthesis[SIZE];
    printf("Enter the sequence:   ");
    scanf("%s", paranthesis);

    if (check(paranthesis, stack, &top))
    {
        printf("\nCorrect Sequence");
    }
    else
    {
        printf("\nIncorrect Sequence");
    }
    return 0;
}

Please comment in case of doubts or queries.
It would be really hepful if you could give an upvote :)

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h"...
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h" template StackLinked::StackLinked (int maxNumber) { } template StackLinked::StackLinked(const StackLinked& other) { } template StackLinked& StackLinked::operator=(const StackLinked& other) { } template StackLinked::~StackLinked() {    clear(); } template void StackLinked::push(const DataType& newDataItem) throw (logic_error) {    } template DataType StackLinked::pop() throw (logic_error) { } template void StackLinked::clear() {    StackNode* t;    while ( top != NULL)    {        t = top;       ...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity  ...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity   Code   Description   Project   File   Line   Suppression State Warning   C6385   Reading invalid data from 'DynamicStack': the readable size is '(unsigned int)*28+4' bytes, but '56' bytes may be read.   Here is the C++ code were I'm having the warning. // Sstack.cpp #include "SStack.h" // Constructor SStack::SStack(int cap) : Capacity(cap), used(0) {    DynamicStack = new string[Capacity]; } // Copy Constructor SStack::SStack(const SStack& s) : Capacity(s.Capacity), used(s.used)...
Using the C programming language implement Heapsort in the manner described in class. Here is some...
Using the C programming language implement Heapsort in the manner described in class. Here is some example code to use as a guideline. Remember, you need only implement the sort algorithm, both the comparison and main functions have been provided. /* * * after splitting this file into the five source files: * * srt.h, main.c, srtbubb.c, srtinsr.c, srtmerg.c * * compile using the command: * * gcc -std=c99 -DRAND -DPRNT -DTYPE=(float | double) -D(BUBB | HEAP | INSR |...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template <class ItemType> class QueueADT { public:        // Action responsibilities        virtual void resetQueue() = 0;           // Reset the queue to an empty queue.           // Post: Queue is empty.        virtual void add(const ItemType& newItem) = 0;           // Function to add newItem to the queue.           // Pre: The queue exists and is not full.          ...
Please answer the following C question: Read the following files called array-utils5A.c and array-utils5A.h. Build an...
Please answer the following C question: Read the following files called array-utils5A.c and array-utils5A.h. Build an executable with gcc -Wall -DUNIT_TESTS=1 array-utils5A.c The definitions for is_reverse_sorted and all_different are both defective. Rewrite the definitions so that they are correct. The definition for is_alternating is missing. Write a correct definition for that function, and add unit tests for it, using the unit tests for is_reverse_sorted and all_different as models. Please explain the logic errors present in in the definition of is_reverse_sorted...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input operator>> a bigint in the following manner: Read in any number of digits [0-9] until a semi colon ";" is encountered. The number may span over multiple lines. You can assume the input is valid. Overload the operator+ so that it adds two bigint together. Overload the subscript operator[]. It should return the i-th digit, where i is the 10^i position. So the first...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>    #include <cstdlib> #include "QueueADT.h" using namespace std; // Definition of the node template <class ItemType> struct NodeType {        ItemType info;        NodeType<ItemType> *next; }; template <class ItemType> class LinkedQueueType: public QueueADT<ItemType> { public:        // Constructor        LinkedQueueType();           // Default constructor.           // Post: An empty queue has been created. queueFront = NULL;           //       queueBack = NULL;...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) What int setup_game needs to do setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
I've posted this question like 3 times now and I can't seem to find someone that...
I've posted this question like 3 times now and I can't seem to find someone that is able to answer it. Please can someone help me code this? Thank you!! Programming Project #4 – Programmer Jones and the Temple of Gloom Part 1 The stack data structure plays a pivotal role in the design of computer games. Any algorithm that requires the user to retrace their steps is a perfect candidate for using a stack. In this simple game you...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT