-1

I was just wondering how I could state if x + y + z % 2 == 0 BUT only do this statement IF the three values aren't set to 0. I require the values to be 0.

Example of my code & posStatus may hold variables of the value 0. The problem is when all three of them are 0 an issue occurs. The user and program over time fill in these values.

else if (posStatus[0] + posStatus[4] + posStatus[8] % 2 == 0)
{
    if (posStatus[0] == 0)
    {
        posStatus[0] = 2;
        return;
    }
    else if (posStatus[4] == 0)
    {
        posStatus[4] = 2;
        return;
    }
    else if (posStatus[8] == 0)
    {
        posStatus[8] = 2;
        return;
    } 
}
ekad
  • 14,436
  • 26
  • 44
  • 46
Zain
  • 1,246
  • 4
  • 15
  • 26
  • A quick bet... you are misusing [Precedence and Order of Evaluation](http://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx). Try to add parenthesis. – Steve B Feb 12 '14 at 16:07
  • That doesn't seem to be an issue.. The issue is that if the array in this example 0, 4 and 8 aren't always getting initialised. If one of them is it's no big deal but if none of them happen then this issue occurs. I want it not to do this code if all 3 are not = to 0 – Zain Feb 12 '14 at 16:11
  • I'm sorry, but I don't understand what you're saying. What dou you mean by 'array in this example 0, 4 and 8 aren't always getting initialised'? – Tarec Feb 12 '14 at 16:12
  • The answer got provided but I'll explain it regardless encase anyone else has a similar issue. My issue was that i had variables that by default are set to 0 and they NEED to be left at 0 but if all three were at 0 then the three values added up then % 2 = 0 which was causing me an issue. – Zain Feb 12 '14 at 16:16

3 Answers3

2
if((x!=0 && y!=0 && z!=0) && x + y + z % 2 == 0)
    //do your stuff

Logical operators in C# are converted to series of if-else constructions during compilation, so if first condition is not true, other ones won't be checked.

Tarec
  • 3,268
  • 4
  • 30
  • 47
1
if(posStatus[0] != 0 &&
   posStatus[4] != 0 &&
   posStatus[8] != 0 &&
   (posStatus[0] + posStatus[4] + posStatus[8]) % 2 == 0)
{
    // Do something
}
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
0
if((posStatus[0]!=0 && posStatus[4]!=0 && posStatus[8]!=0) && 
   (posStatus[0] + posStatus[4] + posStatus[8]) % 2 == 0)
{

}
Christos
  • 53,228
  • 8
  • 76
  • 108