+ 3
Infinity output
Can anyone explain and give infinite loop with condition ??
13 Respuestas
+ 2
while(true);
+ 1
Infinite loop refers to the situation where a block of statement is run for infinite times. As far as I'm concerned there is no actual implementation of infinite loop in codes I have seen, as running infinite loop will only result in runtime error or system crash.
Hence, my opinion is that programmers learn infinite loop to prevent and alert themselves from creating it unintentionally and lead to undesirable outcome.
+ 1
S.K.LURK had provided common examples of infinite while and for loop and I don't see a problem in these samples. May I know why did you say that example is wrong?
Anyway, it seems that you can use for(;;) to create an infinite for loop (source: https://stackoverflow.com/questions/15989618/java-infinite-loop-convention)
+ 1
While am attended one interview they ask this question and i also approached like this only but it’s wrong. And the interviewer says that refer about signed and unsigned operator and then will get result. But still now have a confusion on it.
+ 1
That is why the interviewer mentioned the unsigned data type. An unsigned variable cannot store negative value, hence if we give i an unsigned int data type, i>=0 will always be true, and the loop becomes an infinite loop.
Unfortunately, it seems that java doesn't has unsigned int data type, so we could use another alternative - by using bitwise AND operator (&) to "chop off" the negative range of int data type (see https://javamex.com/java_equivalents/unsigned.shtml ).
Hence, I think the correct answer should be:
for(int i=0; i>=0; i=(i+1)&0xff){
//
}
I'm not sure if above opinions are totally correct, you should check the answer with experienced java programmer.
+ 1
for (int i=0; i>=0; i++){
i=1;
}
for (int i=0; i != 0.5; i++){
//
}
0
Using for loop with condition
0
for (i=0; i>=0; i++){
//
}
0
I’m also think like this only but this one is wrong
0
If we declare i as int variable then it 4bytes upto 4bytes of memory only it can run and then it stops. That’s why am saying that is wrong
0
@Venkatesh R B thanks for the hints. With the help of Google I think I have found that
for (int i=0; i>=0; i++){
//
}
is not an infinite loop.
Initially, I thought that runtime error would cause the programme to end when running this loop. However, if the compiler is good, it will run until value i has the max value an int data type could store.
When value i has the max value (i=2,147,483,647) and encounters i++, overflow occurs (see https://www.quora.com/What-is-overflow-in-Java ). This causes value i to have the min value of int data type (i=-2,147,483,648). Hence, i>=0 becomes false and the loop ends.
0
Then what is the correct answer for this @Low kai han