NVIDIA Interview Question
Software Engineer / DevelopersHmm. I like Nvidia's questions. They gave out hardware/software tests at the CS career fair too. You should've seen the # of people taking tests!
Anyhow, i will not be < 0 because it's unsigned. Should be >=0. %d should work fine since it will interpret i as signed, except that may be a bug if that wasn't your original intent. Again, this may depend on the compiler's implementation as well.
As i is unsigned, it will never be negative, so the condition of i<=0 is a mistake, given an unsigned i, which, conceptually, cannot have a negative value. Thats the logic error in the code.
What actually happens when you compile it and run?
Depends on the system/compiler.
If an unsigned int is set to 100, that may well be positive, which means the continuation condition of the loop (i<=0) is false, meaning the loop is never entered... BUT... how is (i<=0) evaluated if i is unsigned? What is a < comparison going to do with an unsigned number? I dont' know
basically there are two bugs in this code :
unsigned int i;
for (i = 100; i >= 0; --i)
printf("%d\n",i);
1) As i is defined as insigned int so it value lies between 0 to 2^16-1 or 2^32-1 depending upon m/c.
so it will be an INFINITE LOOP.
2) The second bug is printing an unsinged value with as signed so it will be PRINTED POSITIVE AND NEGATIVE BOTH but CONDITION IS ALWAYS TRUE and hence INFINITE LOOP.
so, output will be INFINITE LOOP with printing value of i oscillate between 0,POSITIVE and NEGATIVE during the execution of the loop.
It is an infinite loop.
Here is why....
from 100 upto 1 it will work normally ...
after it prints 1 it will check is i>=0 yes! so it will do (--i)
then it will print 0 will check is i>=0 yes! so it will do --i, but since
i is unsigned i-1 will make i as 0xFFFFFFFF . So for next time in loop it will print 0xFFFFFFFF (or equivalent in decimal) and continue since (i>=0).
Solution is make i>0
there is only one correction required to be done in this code to run the code properly. and that is you have to write the code in following way :
unsigned int i;
for (i = 100; i > 0; --i)
printf("%d\n",i);
this will solve all the problem.But be careful in not to use "%d" if you want ti print the unsigned int values."%u" in place of "%d" will make your life easier.
Opps.. I mean
- Khoa February 04, 2006for (i = 100; i >= 0; --i)