Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write multiple if conditions

Tags:

c++

I have two variables A and B and I want to write a code where if one of the two variables is equal to

151 or 156 or 720

and the other is not equal to one of these numbers then a third variable C = 0 is equal to one.

So for example

1) if A = 151 and B = 700 then C = 1 
2) if A = 151 and B = 720 then C = 0
3) if A = 140 and B = 700 then C = 0

This is the code

int A = 0
cin >> A;
int B = 0
cin >> B;
int C=0;
int DECKlist[3] = {151,156,720}
for(int d=0; d<3;d++){
      if(A== DECKlist[d]){
           for(int w=0; w<3;w++){
                if(B==DECKlist[w]) C=0;
                 else C=1;
            }
       }
       if(B== DECKlist[d]){
           for(int w=0; w<3;w++){
                if(A==DECKlist[w]) C=0;
                 else C=1;
            }
       }
}

Is this OK? There are other better ways of doing it?

like image 506
user3036416 Avatar asked Feb 12 '23 15:02

user3036416


2 Answers

This is an exclusive OR, XOR. There is no logical XOR in C++, but you can use the bit-wise XOR for your case and exploit the fact that the result of a logical operator is a bool which will map to 0 or 1:

#include <iostream>

int main()
{
    int A, B, C;

    std::cin >> A;
    std::cin >> B;

    A = (A == 151 || A == 156 || A == 720);
    B = (B == 151 || B == 156 || B == 720);

    C = A ^ B;

    std::cout << C << std::endl;
}

I've used a simple expression here to check whether a number is one of three supplied numbers. For larger sets of numbers to check against, you could use a, well, std::set.

like image 120
M Oehm Avatar answered Feb 15 '23 13:02

M Oehm


You can use standard algorithms. For example you could use standard algoritnm std::binary_search along with bitwise XOR operator because array DECKlist is sorted

#include <algorithm>
#include <iterator>

//...

int DECKlist[] = { 151, 156, 720 };

//...

if ( std::binary_search( std::begin( DECKlist ), std::end( DECKlist ), A ) ^
     std::binary_search( std::begin( DECKlist ), std::end( DECKlist ), B ) )
{
   C = 1;
}

In this case you may add new values in the array and the approach will work as usual correctly. It does not depend on "magic numbers" and their quntity.:)

like image 21
Vlad from Moscow Avatar answered Feb 15 '23 11:02

Vlad from Moscow