0

Forgive me for the confusing syntax, I am new to coding. My question is simple. In my last statement, >> "else if (digits[15] == 5 (&&) digits[14] == 1 || digits[14] == 2 || digits[14] == 3 || digits[14] == 4 || digits[14] == 5;)"

I am trying to say "if the first digit in the credit card number is 5 and the second number is 1 or 2 or 3 or 4 or 5 then print out Mastercard". I do not understand the syntax and I am almost done with this problem, could somebody please run this code and help me understand where I am wrong with this statement. Thank you.

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    ...    
    [EDIT: unreated code removed for Honor Code compliance.]

    else if (digits[15] == 5 (&&) digits[14] == 1 || digits[14] == 2 || digits[14] == 3 || digits[14] == 4 || digits[14] == 5;)
    {
        printf("Mastercard\n");
        return 0;
    }
}

}

0
else if (digits[15] == 5 (&&) digits[14] == 1 || digits[14] == 2 || 
          digits[14] == 3 || digits[14] == 4 || digits[14] == 5;)

Aside from syntax issues like the semicolon inside the parentheses and the parentheses around &&, you need to remember that, except for overriding parentheses, the tests are evaluated first for precedence and then left to right. In this case, it translates to this: Are the first two digits 51 OR is the second digit either 2, 3, 4 or 5?

Parentheses, when used properly, will accomplish what you want.

IF( a && ( b || c || d || e || f)  ) 
{
    //more code
}

This example requires the first condition, a, to be true, and at least one of the remaining 5 conditions must be true too.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |
  • 1
    Problem here is not left-to-right, but operator precedence. && has a higher precedence than ||, so if you want to apply || first, you need parentheses. It's the same as with multiply and addition. Multiply operator * has higher precedence than addition operator +. – Blauelf Nov 17 '17 at 10:15
  • If you want to compare the precedence, I use the list on en.cppreference.com/w/c/language/operator_precedence – Blauelf Nov 17 '17 at 10:22
  • Yeah, ok, I had the precedence vs left to right wrong, but I had the result right. I fixed the answer accordingly. In any case, the key to fixing this one is parentheses. In any case, it's good to have people around to fact check everything. ;-) – Cliff B Nov 17 '17 at 11:01
  • Thanks for correcting your answer. I did not want to open a new answer because you were mostly right, just got the reason wrong. BTW, some operators are evaluated right to left, e.g. a = b = 7 – Blauelf Nov 17 '17 at 13:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .