Amazon Interview Question
Software Engineer / DevelopersI have tried other options too :
->if 0 is replaced by any other no.(i.e. true) then, it prints guess infinite number of times,
->if 0 is replaced by FALSE(defined as 0), then it also prints guess just once
CONSIDERING THESE CASES IT SEEMS THAT :- "for loop without any initialization and incre/decre, it works as do-while loop"
!!!BUT again contrary to this when 0 is replaced by any wrong condition it behaves like while loop(i.e. don't print guess, as expected)
PLEASE SOMEONE HELP WITH SOME EXPLANATION
Its because..a for loop will always do the initialisation first and executes the loop's body...ONLY after executing the loops body once,it will check for the condition..
So..in this case ...it executes loop's body once..then it finds 0(ie .false) ,hence it quits but instead of 0,any other number is considered true,hence executes infinite number of times...
if for loop follows do-while loop, then it should execute the loop body at least once as for the earlier case even if, 0 is replaced by some wrong condition(like int i=0;
for(;i<0;) printf("\nGUESS");
BUT ITS CONTRADICTORY TO THE ASSUMED CONCLUSION AND DOES NOT PRINT ANYTHING
@sha
you are wrong ,during 1 st iteration it is initialized and condition is checked before executing the body
try this code
for(x=1;x>2;x++)
printf("%d",x);
so according to you it should have printed 1 ,but it won't print because condition is also checked before entering body
Tried compiling with Dev c++ (Which internally uses gcc for c files)
- snk_anindya February 04, 2011- Nothing is printed when for(;0;)
- Infinite loop when for(;1;)