Bailey0314
Bailey0314

Reputation: 21

Boolean Truth Table C++

(p -> q) <-> [( r ^ t ) v (not) s]

This equation was given by my teacher for us to code a truth table for. I already ran the checks for this by the teacher, but I'm having issues trying to populate the arrays:

bool p[32] = { false };
bool q[32] = { false }; 
bool r[32] = { false };
bool s[32] = { false };
bool t[32] = { false };

I know that I'm trying to allocate memory that wasn't set aside(getting "stack around variable 'p' was corrupted") by doing:

for (int i = 0; i < counter; i++)           
    {
        toTrue[i] = true;
        for (int j = (counter * 2); j < (counter * 3); j++)     
        {
            toTrue[j] = true;
            for (int k = (counter * 4); k < (counter * 5); k++)     
            {
                toTrue[k] = true;
                for (int l = (counter * 6); l < (counter * 7); l++)     
                {
                    toTrue[l] = true;
                    for (int m = (counter * 8); m < (counter * 9); m++)     
                    {
                        toTrue[m];
                    }
                }
            }
        }
    }

This is just based off the basic truth tables where a basic, 2 variable OR truth table would result:

a b    c
1 1    1
1 0    1
0 1    1
0 0    0

I'm not sure how to fix this issue without using vectors, which I have a very limited knowledge about, so not 100% confident going that route. Another idea I had was to try and create multiple methods for populate p, then q, then r, etc. But my teacher already told me previously that I was expanding the code more than I need to, and I feel like doing multiple methods like that would lead to him saying the same thing. Any advice?

Upvotes: 1

Views: 12200

Answers (1)

kelalaka
kelalaka

Reputation: 5636

A different and simple method.

#include<iostream>

using namespace std;

bool getBit(unsigned int uint, int position) { // !!! no range check  !!! 
     return (uint >> position) & 0x1;
}

int main( int argc, char* argv[]) {

    bool p,q,r,s,t;
    
    cout << "p  q  r  s  t  (p -> q) <-> [( r ^ t ) v (not) s] \n";
    for ( unsigned int i = 0 ; i < 32 ; i++ ) {
             
        cout << getBit(i,0) << "  ";
        cout << getBit(i,1) << "  ";
        cout << getBit(i,2) << "  ";
        cout << getBit(i,3) << "  ";
        cout << getBit(i,4) << "  ";
        
        cout  << ((!p || q)  == (( r ^ t ) ||  !s));
        
        cout << endl;
    }
    return 0;
}

Upvotes: 2

Related Questions