how many times will an unsigned Char loop run
I'm a noob at C/C++ So excuse the simplicity of the question, but here goes
unsigned char i;
for (i=0; i<1000; ++i)
if ((i%4) == 0)
printf("hello\n");
how many times will the code print "hello". I say 63, but alas its not one of the options. Can someone provide an answer, but more importantly an explanation as to why开发者_开发知识库
Note: I am assuming 8 bit char types.
You will overflow when you perform ++i
for i
equal to 255. At that point the language standard decrees that i
becomes 0, a phenomenon commonly known as wraparound.
So, you have an infinite loop, since i<1000
for all values of i
.
I would urge you to conduct an experiment by running the code. If that doesn't clear things up, try printing out the values of i
for which the condition is true. If you then notice any anomalies in how the value of i
changes, think about possible causes of that.
Answer is Infinite time, range of unsigned character is between 0-255(1 byte) when it goes beyond 255 it will overflow and come back to 0 that mean it will never reach to 1000 ..hence infinite loop
Here the you decleared "i" as unsigned char whose range in less than 1000 and its of size 1 byte (0-255) when it reaches the 255 again it decrements then at any condition the value will not exceeds 1000 bcoz "i" ranges from 0-255 only.
so the for loop doesn't fail n executes indefinatly
I Hope u got my point......!!!!!!!!!!
I say 0 - it is not "hello", but "hellow" :-)
But now in real: i
has the values 0, 1, 2, ... 999. These are 1000 values.
When will the string be printed? If i
is 0, 4, 8, 12, ... - so once every 4 loop cycles.
--> In 1000 loop cycles, it gets printed 250 times.
This would be true without unsigned char
as data type.
Infinite time "hello" print because reason is simple, unsigned char have a limit up to 255 after that if u again increment on it ,they will become zero & again they reach to 255 then zero , so variable i never reach 1000 we call it infinite loop.
精彩评论