• 0

Very easy C Question - Regarding IF statements


Question

Hello,

My small program needs to calculate car depreciation and look out for classic cars. I have in an array car 7 which is a Ford.

Can I have multiple Or statements when the user selected Ford?

Is it possible to do this

if (brand == 7 && caryear == 1965 || caryear == 1931 || caryear == 1957 )

{

printf("\n\t\t\tThis car is a CLASSIC!!!");

printf("\n\n");

}

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

Yes. The way || works is if the first part doesn't equal true, it skips to the next part and sees if it's true, but if the first part does equal true, it doesn't go any further.

You may want to write it like this so its easier to tell what it's doing:

if (brand == 7 && (caryear == 1965 || caryear == 1931 || caryear == 1957 ))

{

printf("\n\t\t\tThis car is a CLASSIC!!!");

printf("\n\n");

}

Well, actually what you had would be true if the year was a '31 or a '57, even if the brand wasn't a 7.

Since yours could be written like:

if ((brand == 7 && caryear == 1965) || caryear == 1931 || caryear == 1957)

Since the and fails, it goes onto the or's.

Edited by kjordan2001
Link to comment
Share on other sites

  • 0
if (brand == 7 && caryear == 1965 || caryear == 1931 || caryear == 1957 )

{

printf("\n\t\t\tThis car is a CLASSIC!!!");

printf("\n\n");

}

if (brand == 7 && caryear <= 1965)

{

}

/// Whats wrong with this then ??

Link to comment
Share on other sites

  • 0

breaking the statement down

if (brand == 7 &amp;&amp; caryear &lt;= 1965)

//is not the same as 
if (brand == 7 &amp;&amp; caryear == 1965)

// they only want if ((brand 7, 1965) or (1931) or (1957))
// &lt;= will pick up years that the person does not want

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.