Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For the sake of discussion...</p> <p>You only need to look at the last digit in any given number to see if it is even or odd. Signed, unsigned, positive, negative - they are all the same with regards to this. So this should work all round: -</p> <pre><code>void tellMeIfItIsAnOddNumberPlease(int iToTest){ int iLastDigit; iLastDigit = iToTest - (iToTest / 10 * 10); if (iLastDigit % 2 == 0){ printf("The number %d is even!\n", iToTest); } else { printf("The number %d is odd!\n", iToTest); } } </code></pre> <p>The key here is in the third line of code, the division operator performs an integer division, so that result are missing the fraction part of the result. So for example 222 / 10 will give 22 as a result. Then multiply it again with 10 and you have 220. Subtract that from the original 222 and you end up with 2, which by magic is the same number as the last digit in the original number. ;-) The parenthesis are there to remind us of the order the calculation is done in. First do the division and the multiplication, then subtract the result from the original number. We could leave them out, since the priority is higher for division and multiplication than of subtraction, but this gives us "more readable" code.</p> <p>We could make it all completely unreadable if we wanted to. It would make no difference whatsoever for a modern compiler: -</p> <pre><code>printf("%d%s\n",iToTest,0==(iToTest-iToTest/10*10)%2?" is even":" is odd"); </code></pre> <p>But it would make the code way harder to maintain in the future. Just imagine that you would like to change the text for odd numbers to "is not even". Then someone else later on want to find out what changes you made and perform a svn diff or similar...</p> <p>If you are not worried about portability but more about speed, you could have a look at the least significant bit. If that bit is set to 1 it is an odd number, if it is 0 it's an even number. On a little endian system, like Intel's x86 architecture it would be something like this: -</p> <pre><code>if (iToTest &amp; 1) { // Even } else { // Odd } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload