I have a few loops that I need in my program. I can write out the pseudo code, but I\'m not entirely sure how to write them logically.
I need -
if (num is
You might be overthinking this.
if (x % 10)
{
.. code for 1..9 ..
} else
{
.. code for 0, 10, 20 etc.
}
The first line if (x % 10)
works because (a) a value that is a multiple of 10 calculates as '0', other numbers result in their remainer, (b) a value of 0 in an if
is considered false
, any other value is true
.
Edit:
To toggle back-and-forth in twenties, use the same trick. This time, the pivotal number is 10
:
if (((x-1)/10) & 1)
{
.. code for 10, 30, ..
} else
{
.. code for 20, 40, etc.
}
x/10
returns any number from 0 to 9 as 0
, 10 to 19 as 1
and so on. Testing on even or odd -- the & 1
-- tells you if it's even or odd. Since your ranges are actually "11 to 20", subtract 1 before testing.