user2009020
user2009020

Reputation: 287

If/Else Logical Flow

If I have something like:

if (n % 10 == 8 && (n/10) % 10 == 8) count = count + 2;
else if (n % 10 == 8) count++;

Basically, if condition a and b holds, then do something. If only condition a holds, do something else. What is the best logical flow for this?

Upvotes: 1

Views: 54

Answers (2)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

For the shortest possible code (albeit at the cost of readability) you can use the ternary op as

count += (n % 10) == 8 ? ((n/10) % 10 == 8 ? 2 : 1) : 0;

Upvotes: 1

VMAtm
VMAtm

Reputation: 28345

// check the condition a
if (n % 10 == 8)
{
    // check the condition b
    if ((n/10) % 10 == 8))
    {
        count = count + 2;
    }
    // only condition a took place
    else
    {
        count++;
    }
}

Upvotes: 1

Related Questions