How to resolve the algorithm Truth table step by step in the C++ programming language

Published on 7 June 2024 03:52 AM

How to resolve the algorithm Truth table step by step in the C++ programming language

Table of Contents

Problem Statement

A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Truth table step by step in the C++ programming language

This snippet defines a program to evaluate Boolean expressions. Boolean expressions are defined as either 'T' (True), 'F' (False), a single-letter variable (except 'T' and 'F'), or an operator followed by one or more variables or 'T', 'F'.

The operators supported are:

  • & (and)
  • | (or)
  • ! (not)
  • ^ (xor)

The process_expr function removes any whitespace and converts the expression to uppercase. The is_operator function checks if a character is an operator.

The eval_expr function evaluates the expression. It takes a string expression as an argument and returns a Boolean value. The function uses a stack to evaluate the expression. The pop function is used to pop the top element from the stack.

The set_vars function is used to set the values of the variables. It takes two arguments: the position of the variable to set and the expression to evaluate. The function uses recursion to set the values of the variables. If the position is greater than the number of variables, the function throws an exception. If the position is equal to the number of variables, the function evaluates the expression and prints the result. If the position is less than the number of variables, the function sets the variable value to false, calls set_vars with the next position and the expression.

The main function takes an expression from the user and evaluates it. If the user enters an empty string, the program exits. The main function calls process_expr to remove any whitespace and convert the expression to uppercase. The main function then calls eval_expr to evaluate the expression and prints the result.

Source code in the cpp programming language

#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <vector>

struct var {
    char name;
    bool value;
};
std::vector<var> vars;

template<typename T>
T pop(std::stack<T> &s) {
    auto v = s.top();
    s.pop();
    return v;
}

bool is_operator(char c) {
    return c == '&' || c == '|' || c == '!' || c == '^';
}

bool eval_expr(const std::string &expr) {
    std::stack<bool> sob;
    for (auto e : expr) {
        if (e == 'T') {
            sob.push(true);
        } else if (e == 'F') {
            sob.push(false);
        } else {
           auto it = std::find_if(vars.cbegin(), vars.cend(), [e](const var &v) { return v.name == e; });
           if (it != vars.cend()) {
               sob.push(it->value);
           } else {
               int before = sob.size();
               switch (e) {
               case '&':
                   sob.push(pop(sob) & pop(sob));
                   break;
               case '|':
                   sob.push(pop(sob) | pop(sob));
                   break;
               case '!':
                   sob.push(!pop(sob));
                   break;
               case '^':
                   sob.push(pop(sob) ^ pop(sob));
                   break;
               default:
                   throw std::exception("Non-conformant character in expression.");
               }
           }
        }
    }
    if (sob.size() != 1) {
        throw std::exception("Stack should contain exactly one element.");
    }
    return sob.top();
}

void set_vars(int pos, const std::string &expr) {
    if (pos > vars.size()) {
        throw std::exception("Argument to set_vars can't be greater than the number of variables.");
    }
    if (pos == vars.size()) {
        for (auto &v : vars) {
            std::cout << (v.value ? "T  " : "F  ");
        }
        std::cout << (eval_expr(expr) ? 'T' : 'F') << '\n'; //todo implement evaluation
    } else {
        vars[pos].value = false;
        set_vars(pos + 1, expr);
        vars[pos].value = true;
        set_vars(pos + 1, expr);
    }
}

/* removes whitespace and converts to upper case */
std::string process_expr(const std::string &src) {
    std::stringstream expr;

    for (auto c : src) {
        if (!isspace(c)) {
            expr << (char)toupper(c);
        }
    }

    return expr.str();
}

int main() {
    std::cout << "Accepts single-character variables (except for 'T' and 'F',\n";
    std::cout << "which specify explicit true or false values), postfix, with\n";
    std::cout << "&|!^ for and, or, not, xor, respectively; optionally\n";
    std::cout << "seperated by whitespace. Just enter nothing to quit.\n";

    while (true) {
        std::cout << "\nBoolean expression: ";

        std::string input;
        std::getline(std::cin, input);

        auto expr = process_expr(input);
        if (expr.length() == 0) {
            break;
        }

        vars.clear();
        for (auto e : expr) {
            if (!is_operator(e) && e != 'T' && e != 'F') {
                vars.push_back({ e, false });
            }
        }
        std::cout << '\n';
        if (vars.size() == 0) {
            std::cout << "No variables were entered.\n";
        } else {
            for (auto &v : vars) {
                std::cout << v.name << "  ";
            }
            std::cout << expr << '\n';

            auto h = vars.size() * 3 + expr.length();
            for (size_t i = 0; i < h; i++) {
                std::cout << '=';
            }
            std::cout << '\n';

            set_vars(0, expr);
        }
    }

    return 0;
}


  

You may also check:How to resolve the algorithm Arrays step by step in the BML programming language
You may also check:How to resolve the algorithm Factorial step by step in the Peylang programming language
You may also check:How to resolve the algorithm Flow-control structures step by step in the Scala programming language
You may also check:How to resolve the algorithm Enumerations step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Call a function step by step in the Little programming language