# Answering an interview question on implementing a &quot;isEven(int)&quot; function in C should not require a for loop.

• The job i was interviewing doesn't require "programming", per-se. However, if I observe an interviewee that lists a programming language on his/her resume, I feel compelled to ask, if only to observe if they are padding their resume. In addition,the skills in coding are definitely germane to the job. I also provide them an out, asking them how familiar they were. When, he told me he had been responsible for a "large C module" and stated proficency, we were off...

I asked him to code up an "isEven(int)" function. I wrote out the code that I would use it with, and explained that it would tell me if the integer is an even number or an odd number. I reminded him that exact syntax wasn't the important part.

He started with a #include. I told him he shouldn't worry about that, he was just writing a function to be imbedded in my program. So he scratched that out and went straight to main(). At that point, I settled back for a bit of fun. It didn't seem worthwhile to immediately correct him a second time.

I will reproduce his "solution", straight from the piece of paper that I have preserved. Comments are mine, of course...

main()

{

int i;

i=0;

int even;

int odd;   // started calling them e and o, then changed when I asked him "What are the variables e and o?". I guess he didn't realize I really wasn't WTF'ing the name, just the necessity...

for (i=1; i<=100;)   // started with 0, changed to 1

{

if (i = 1)  // started with 0, changed to 1 with the for loop index.  I was wondering if he didn't know whether 0 was even or odd. I don't think he knew. See note below

{

odd = i;

i++;

}

if (i = 2)

{

i = even;  // We never explored why it was "odd = i" and "i = even".

i++;

}

// He ran out of room on the paper, and I ran out of sanity...

}

}

Note: I don't usually hold it against people if their only mistake is to not use double equal for comparison, if that was their only problem... However, in this case, the = v.s. == produced a rather interesting result given his odd for loop.

I don't think he understood I was asking for a function, but he still didn't answer it properly after I clarified that aspect the second time (the first time after he started the #include, the second time after he completed the above).

Also you should bear in mind that he states that he is working towards an MS in "Software Systems" through "distance learning". Very distant, perhaps...

•  wow. Just... I don't think you could find a more simplistic question than that. Except maybe "make a function that returns it's parameter". That might have been hilarious to see too.

Just to confirm I'm not an idiot, the "answer" could have been as simple as this(?):

```int isEven(int pcheck)
{
return pcheck%2!=0;
}```
` `

• @ericmorton said:

{

int i;

i=0;

int even;

int odd;   // started calling them e and o, then changed when I asked him "What are the variables e and o?". I guess he didn't realize I really wasn't WTF'ing the name, just the necessity...

for (i=1; i<=100;)   // started with 0, changed to 1

{

if (i = 1)  // started with 0, changed to 1 with the for loop index.  I was wondering if he didn't know whether 0 was even or odd. I don't think he knew. See note below

{

odd = i;

i++;

}

if (i = 2)

{

i = even;  // We never explored why it was "odd = i" and "i = even".

i++;

}

// He ran out of room on the paper, and I ran out of sanity...

}

}

This is dynamic programming at its finest; clearly if i is odd, the i + 1 is even.

Surely using a loop and saving the results of sub-solutions is better than the solution:

```bool isEven(int num) {
if (i == 1) return false;
else if (i > 1) return !isEven(i - 1);
else return FILE_NOT_FOUND;
}
```

... right?

• @BC_Programmer said:

```int isEven(int pcheck)
{
return pcheck%2!=0;
}```
` `

Seems it'd be cleaner as:

```int isntNotOdd(int pcheck) {
return !(pcheck % 2 != 0);
}
```

• Correct. but after that we would explore your concept of what an "int" is. How would you code that without using the modulo function, bools v.s. int returns, etc... When the interviewee expresses more confidence in C, I would ask harder questions too.

• @BC_Programmer said:

int isEven(int pcheck)

{

return pcheck%2!=0;

}

My instinct is to go for

return ! ( pcheck & 1 );

However I'd check a hex dump to see if negative numbers have the lower-order bit on or off. Bit-wise AND runs a whole lot faster than modulo.

Even and odd are only defined for mathematical integers; there's no such thing as an even boolean. Unfortunately 12.000 is mathematically defined as even, but I would hesitate to code a C function to test it.

• @BC_Programmer said:

wow. Just... I don't think you could find a more simplistic question than that. Except maybe "make a function that returns it's parameter". That might have been hilarious to see too.

Just to confirm I'm not an idiot, the "answer" could have been as simple as this(?):

```int isEven(int pcheck)
{
return pcheck%2!=0;
}```
` `

It could have been, of course I'd have named it "isOdd" in that case, but I suppose that's just me.

• @ericmorton said:

bools v.s. int returns

C89 doesn't have a bool type. C99 kinda has, but it's a #define for _Bool, and I can't find a specification for that right away. Some major compilers don't support C99 though.

• @AndyCanfield said:

However I'd check a hex dump to see if negative numbers have the lower-order bit on or off. Bit-wise AND runs a whole lot faster than modulo.

I'm not aware of any modern platform which does not use two's complement arithmetic. In particular, both x86 and ARM use it.

@AndyCanfield said:

Even and odd are only defined for mathematical integers; there's no such thing as an even boolean.

Not for true booleans, no. But computers don't deal with such abstract concepts, so their booleans are the members of ℤ/2ℤ, i.e. the ring of integers (mod 2). In this ring, multiplication becomes the boolean and operation and addition becomes the boolean xor operation. Constructing other boolean operations is left as an excercise.

@AndyCanfield said:

Unfortunately 12.000 is mathematically defined as even, but I would hesitate to code a C function to test it.

Why? It's easy to prove that you can use modular arithmetic to check for integer parity.

• @tdb said:

@AndyCanfield said:

Unfortunately 12.000 is mathematically defined as even, but I would hesitate to code a C function to test it.

Why? It's easy to prove that you can use modular arithmetic to check for integer parity.

I think the implied difficulty is that 12.000 is a floating point number.

• @Ilya Ehrenburg said:

@tdb said:

@AndyCanfield said:

Unfortunately 12.000 is mathematically defined as even, but I would hesitate to code a C function to test it.

Why? It's easy to prove that you can use modular arithmetic to check for integer parity.

I think the implied difficulty is that 12.000 is a floating point number.

I took the dot to be a thousands separator. The concept of even and odd numbers isn't defined for rational, real or any other numbers besides integers, and Andy seems knowledgeable enough of the subject to be aware of this.

• @Sutherlands said:

It could have been, of course I'd have named it "isOdd" in that case, but I suppose that's just me.

For some reason I had == originally, but then flipped it. That was fail.

Now to integrate it into production code.

• @AndyCanfield said:

My instinct is to go for

return ! ( pcheck & 1 );

However I'd check a hex dump to see if negative numbers have the lower-order bit on or off. Bit-wise AND runs a whole lot faster than modulo.

Aren't optimizing compilers supposed to do that automatically if possible?

@AndyCanfield said:

Even and odd are only defined for mathematical integers; there's no such thing as an even boolean. Unfortunately 12.000 is mathematically defined as even, but I would hesitate to code a C function to test it.

I'll give it a try anyway.

```int feven(double d) { return fmod(d, 2.0) == 0.0; }
int fodd (double d) { return fabs(fmod(d, 2.0)) == 1.0; }```

Discuss.

inb4==

• @tdb said:

I took the dot to be a thousands separator. The concept of even and odd numbers isn't defined for rational, real or any other numbers besides integers, and Andy seems knowledgeable enough of the subject to be aware of this.

Yup:

@AndyCanfield said:

Even and odd are only defined for mathematical integers; there's no
such thing as an even boolean. Unfortunately 12.000 is mathematically
defined as even, but I would hesitate to code a C function to test it.

However, he wrote "mathematical integers" and 12.000 is an integral-valued floating-point number, so I interpreted Andy's sentence as "I would hesitate to code a C function to test floating-point numbers for even integral values".

• @ericmorton said:

I was wondering if he didn't know whether 0 was even or odd. I don't think he knew.

Sometime towards the end of last century I had a college computing lecturer argue forcefully that 0 was neither even nor odd, and was in fact something called "neutral".

My only hypothesis is that he misheard the word "natural" and that one extra datum was enough to cause his neuron's buffer to overrun.

• @fatbull said:

I'll give it a try anyway.

```int feven(double d) { return fmod(d, 2.0) == 0.0; }
int fodd (double d) { return fabs(fmod(d, 2.0)) == 1.0; }```

Discuss.

```#include <stdio.h>
#include <math.h>

int feven(double d) { return fmod(d, 2.0) == 0.0; }
int fodd (double d) { return fabs(fmod(d, 2.0)) == 1.0; }

int main ()
{
double n1 = 1.0;
n1 += 0.33333333333333333333333333333333333333333333333;
n1 -= 0.11111111111111111111111111111111111111111111111;
n1 -= 0.22222222222222222222222222222222222222222222222;
printf("n1 is %f\n", n1);
printf("is n1 even: %d\n", feven(n1));
printf("is n1 odd: %d\n", fodd(n1));
}

```

Result:

```n1 is 1.000000
is n1 even: 0
is n1 odd: 0
```

I don't like testing floats for eveness/oddness either.

• @Buzer said:

```
printf("n1 is %0.16f\n", n1);
```

Result:

```n1 is 0.9999999999999999
is n1 even: 0
is n1 odd: 0
```

FTFY

• @tdb said:

@ericmorton said:

bools v.s. int returns

C89 doesn't have a bool type. C99 kinda has, but it's a #define for _Bool, and I can't find a specification for that right away. Some major compilers don't support C99 though.

C99 has <stdbool.h> which defines "bool" "true" and "false"

Also, if an "int % 2" can be rewritten as "int & 1" then your compiler will do so unless you disable all optimizations. So... DO NOT DO THAT, if you need to think twice if a piece of simple code is correct, then the code is wrong, even if it produces the correct result.

• @Daid said:

Also, if an "int % 2" can be rewritten as "int & 1" then your compiler will do so unless you disable all optimizations. So... DO NOT DO THAT, if you need to think twice if a piece of simple code is correct, then the code is wrong, even if it produces the correct result.

`int & 1` is more obvious to me than `int % 2`. NOW WHAT?!

• @Watson said:

Sometime towards the end of last century I had a college computing lecturer argue forcefully that 0 was neither even nor odd, and was in fact something called "neutral".

I had a teacher in elementary school argue that zero was neither even nor odd. I only remember this because I argued with my teachers all the time on account that they were morons. Sigh, oh how I hated school, what a waste of time...

Nevertheless, there's a whole [url=http://en.wikipedia.org/wiki/Parity_of_zero]Wikipedia article[/url] about it, and a very interesting one at that, so I guess there has been confusion over the simple and obvious.

Stupid teachers...

• @Xyro said:

@Watson said:
Sometime towards the end of last century I had a college computing lecturer argue forcefully that 0 was neither even nor odd, and was in fact something called "neutral".

I had a teacher in elementary school argue that zero was neither even nor odd. I only remember this because I argued with my teachers all the time on account that they were morons. Sigh, oh how I hated school, what a waste of time...

Nevertheless, there's a whole Wikipedia article about it, and a very interesting one at that, so I guess there has been confusion over the simple and obvious.

Stupid teachers...
Are you sure you didn't go to the same elementary school as me?  My arguing with teachers started in Kindergarten; that was when my teacher stated that clouds did not move, but that the Earth moved under them.  By the time I reached 5th grade, I didn't care anymore.  I became a discipline problem because I was bored and was more familiar with the outdated knowledge most of the older teachers had.  Interesting note - my son brought home a Kindergarten paper last year with some patently wrong science - the tongue map of the taste buds.  I can't believe they're still teaching some things that have been disproven for that many years.  Welcome to our public education system...

• @Jayman said:

my son brought home a Kindergarten paper last year with some patently wrong science - the tongue map of the taste buds.
Did the teachers get brought up to date then?

• WHO GIVES A FUCKING SHIT HOW TO SOLVE THE PROBLEM THAT IS NOT THE POINT! If you're reading this forum, let's just take it as a given that you can solve the problem and talk about more interesting things. Like... almost anything at all.

This thread reminds me of the famous FizzBuzz thread, where tons of pedantic dickweeds kept solving the fizzbuzz problem instead of commenting on the actual point of the thread. And thus completely missing the point.

Which is this: approximately 50% of people who claim they can program cannot. Probably 33% or more of these people genuinely think they can program.

• @Watson said:

@ericmorton said:

I was wondering if he didn't know whether 0 was even or odd. I don't think he knew.

Sometime towards the end of last century I had a college computing lecturer argue forcefully that 0 was neither even nor odd, and was in fact something called "neutral".

My only hypothesis is that he misheard the word "natural" and that one extra datum was enough to cause his neuron's buffer to overrun.

I was going to suggest that he was talking about primeness, and you had misremembered or misunderstood the discussion, but that was before the other anecdotes and wiki article. WTF, man.

• @ericmorton said:

// He ran out of room on the paper, and I ran out of sanity...
I've had two train-wreck interviews in the last year.  I made a checklist and committed it to memory for dealing with this situation:

1.  Close Jaw.

2.  Bite Tongue.

3.  Check the safety on the concealed 9mm.

5.  Send them on their way.

One of the candidates almost cried when he couldn't get past the second line of code in FizzBuzz.  It is for this candidate that I created the checklist.  If they pull an ego trip, simply skip step 4 and reinterpret the list in the most violent way possible.

• I had a (substitute) teacher argue that values like 6.48, when rounded to the nearest integer, should be 7, because 8 >= 5, so we round to 6.5, then 5 >= 5, so we round to 7.

• @blakeyrat said:

This thread reminds me of the famous FizzBuzz thread, where tons of pedantic dickweeds kept solving the fizzbuzz problem instead of commenting on the actual point of the thread. And thus completely missing the point.

I think you're completely missing the point: solving the problem in interesting or silly ways IS MORE FUN than discussing the point, to which we all can already painfully attest.

• @Xyro said:

@blakeyrat said:
This thread reminds me of the famous FizzBuzz thread, where tons of pedantic dickweeds kept solving the fizzbuzz problem instead of commenting on the actual point of the thread. And thus completely missing the point.

I think you're completely missing the point: solving the problem in interesting or silly ways IS MORE FUN than discussing the point, to which we all can already painfully attest.

How can it be "more fun" when it's not at all fun? In fact it sucks life out of me, like some kind of forum vampire.

• @Xyro said:

@blakeyrat said:
This thread reminds me of the famous FizzBuzz thread, where tons of pedantic dickweeds kept solving the fizzbuzz problem instead of commenting on the actual point of the thread. And thus completely missing the point.
I think you're completely missing the point: solving the problem in interesting or silly ways IS MORE FUN than discussing the point, to which we all can already painfully attest.

Or how about this: we all come here for different reasons.  Some come to discuss the WTF, others come here to "solve" these simple problems in funny and interesting ways, and blakey comes here to yell at people.

I think I have all the bases covered...

• @blakeyrat said:

This thread reminds me of the famous FizzBuzz thread, where tons of pedantic dickweeds kept solving the fizzbuzz problem instead of commenting on the actual point of the thread. And thus completely missing the point.
for (int x = 0; x<=100; x++) Console.WriteLine( x % 3 == 0 &&
x % 5 == 0 ? "FizzBuzz" : x % 3 == 0 ? "Fizz" : x % 5 == 0 ? "Buzz":
x.ToString());

• @blakeyrat said:

Probably 33% or more of these people genuinely think they can program.

Probably more than that. About half of the solutions in the fizz buzz post comments are wrong.

• @blakeyrat said:

This thread reminds me of the famous FizzBuzz thread, where tons of pedantic dickweeds kept solving the fizzbuzz problem instead of commenting on the actual point of the thread. And thus completely missing the point.

I'm pretty sure the "pedantic dickweeds" were trolling on that thread.   Wasn't one of them called "eBusiness" or some such nonesense?<FONT size=2>

</FONT>

• ew, your for loop has a [i]body[/i]? How quaint!

``````
public class FizzBuzzLol {
static public String DIV_BY_THREE = "Fizz";
static public String DIV_BY_FIVE = "Buzz";

static public void main(String[]] args) {
for (int i = 1;
( check(i % 15, DIV_BY_THREE+DIV_BY_FIVE)
||check(i %  3, DIV_BY_THREE)
||check(i %  5, DIV_BY_FIVE )
||check(0, Integer.toString(i))
) && i < 100; i++);
}

static private boolean check(int mod, String message) {
if (mod==0) {
System.out.println(message);
// TODO: replace with EnterprisePrintWriterFactory
return true;
} return false;
}
}
``````

• @Xyro said:

// TODO: replace with EnterprisePrintWriterFactory
HAHAHAHA! Hysterical bro!

Does anyone have an answer involving LINQ?

• @hoodaticus said:

Does anyone have an answer involving LINQ?

Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");

var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);

output.ToList().ForEach(x => Console.Write(x));

• @frits said:

@hoodaticus said:

Does anyone have an answer involving LINQ?

Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");

var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);

output.ToList().ForEach(x => Console.Write(x));

Awesome...

• @frits said:

@hoodaticus said:

Does anyone have an answer involving LINQ?

Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");

var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);

output.ToList().ForEach(x => Console.Write(x));

I don't like this answer.  I hate making assumptions about the order in which the key/values in a dictionary are enumerated.  Is the underlying data structure an ordered list, or a hashtable?

• around here, someone would probably code it up:

```public static boolean isEven(int arg) {
return new BigInteger(arg).isEven();
}
```
... they'd compile it and realize that BigInteger doesn't have an isEven() method. So, they'd create a wrapper class, MyBigInteger, and use it instead. But then they'd need to code up the actual isEven() method for MyBigInteger.
```public boolean isEven() {
for (BigInteger i = 0, i < BigInteger.MAX_VALUE, i+=2) {
if (this.equals(i)) {
return true;
}
}
return false;
}
```
They'd test it and it would work, then they'd hit a negative number that wasn't even and be confused. So they'd write:
```public boolean isEvenNegative() {
if (this > 0) {
return this.isEven();
}
for (BigInteger i = 0; i > BigInteger.MIN_VALUE, i-=2) {
if (this.equals(i) {
return true;
}
}
return false;
}```

Then, all the calls to isEven would need to be changed to isEvenNegative ... and there would be peace throughout the land.

• @C-Octothorpe said:

@frits said:

@hoodaticus said:

Does anyone have an answer involving LINQ?

Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");

var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);

output.ToList().ForEach(x => Console.Write(x));

Awesome...

Righteous!

• @frits said:

@blakeyrat said:

This thread reminds me of the famous FizzBuzz thread, where tons of pedantic dickweeds kept solving the fizzbuzz problem instead of commenting on the actual point of the thread. And thus completely missing the point.

I'm pretty sure the "pedantic dickweeds" were trolling on that thread.   Wasn't one of them called "eBusiness" or some such nonesense?<font size="2"></font>

Yes, let's not forget the Law of the Internet: Troll or be trolled. [EDIT: Oops, forgot that was in my signature.]

• @frits said:

@hoodaticus said:

Does anyone have an answer involving LINQ?

Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");

var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);

output.ToList().ForEach(x => Console.Write(x));

This is about the closest C# code gets to elegance.

• @zelmak said:

around here, someone would probably code it up:

```public static boolean isEven(int arg) {
return new BigInteger(arg).isEven();
}
```
... they'd compile it and realize that BigInteger doesn't have an isEven() method. So, they'd create a wrapper class, MyBigInteger, and use it instead. But then they'd need to code up the actual isEven() method for MyBigInteger.
```public boolean isEven() {
for (BigInteger i = 0, i < BigInteger.MAX_VALUE, i+=2) {
if (this.equals(i)) {
return true;
}
}
return false;
}
```
They'd test it and it would work, then they'd hit a negative number that wasn't even and be confused. So they'd write:
```public boolean isEvenNegative() {
if (this > 0) {
return this.isEven();
}
for (BigInteger i = 0; i > BigInteger.MIN_VALUE, i-=2) {
if (this.equals(i) {
return true;
}
}
return false;
}```

Then, all the calls to isEven would need to be changed to isEvenNegative ... and there would be peace throughout the land.

I'm calling you out on this: that [b]someone[/b] you speak of; it's you, isn't it? It's okay, we've all been there. It's a learning process.

• @dohpaz42 said:

I'm calling you out on this: that someone you speak of; it's you, isn't it? It's okay, we've all been there. It's a learning process.

Hah! Nice try ... no, not me. My predecessors had (have?) this insane ability to create indirection, like the above, which was completely unnecessary.

I cut my eye-teeth on 6502 and 8088 assembler, so I know and understand the bit-wise tricks. Mine would have been similar to the !(blah & 1) version, above. (I'm sure I would have made it return (blah & 1 == 0) to make it [somewhat more {I wonder how many levels deep I can nest parenthetical comments}] obvious what was going on.)

• @DemonWasp said:

I had a (substitute) teacher argue that values like 6.48, when rounded to the nearest integer, should be 7, because 8 >= 5, so we round to 6.5, then 5 >= 5, so we round to 7.

You had one of those too?

Now coding a function to "round" that way might be a good test for an interview.

• @da Doctah said:

@DemonWasp said:
I had a (substitute) teacher argue that values like 6.48, when rounded to the nearest integer, should be 7, because 8 >= 5, so we round to 6.5, then 5 >= 5, so we round to 7.

You had one of those too?

Now coding a function to "round" that way might be a good test for an interview.

Rounding by induction?

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.