+ 3
Why does this exist? for(int i=0;i<5;i++);
``` for(int i=0;i<5;i++); Sys...("#"); ``` It will print # only once since the loop is followed by semi-colan(;) . My question is what's the point of this , why is this even a thing , the loop is pointless , shouldn't it cause an error .
11 Réponses
+ 11
It serves the pure purpose to fool colleagues or make them lol. Imo you shouldn't do something like that, readability first (clean code!).
+ 9
If you've encountered this in a quiz, it's merely there to test your awareness and debugging skills. As for loops with no body, they can still be useful as certain statements can be executed by embedding them in the loop statement itself.
for (int i = 0; i < 5; Sys...(i++));
For brainless derps like me who would actually do that, we'd prefer for it not to cause errors. :>
+ 9
As for those programmers who do everything within the "header" (parentheses) of the loop without using a body {}, either 1.the operation to be iterated is trivial, 2. it's the most efficient way to do the operation, or 3. the programmer is trying to show off or comes from a generation when clever tricks were favoured over readability and maintainability. In the case of exam/quiz questions, the writer is probably testing your attention to detail.
+ 5
This kind of loop can be use to create a delay / pause in you program...( Although there are other ways of doing it in Java)
e.g.
for( long i=1;I<=10000000;i++);
+ 4
Utkαrsh It was an official ICSE exam question? Interesting.
+ 3
Print statement inside for loops increment part :-|
And it works , wtf
So no real purpose , just to prevent students from getting 100%
+ 3
Btw , the original question
Find the output -
int m=2, n=15;
for(int i=1; i<5 ; i++);
m++ ; --n;
Sys...(m + " " + n);
[ICSE Class -10 , 2010]
I thought the ";" was a missprint xD
+ 3
It is normal; since you use a ";" you inform the compiler it is the end of the current instruction. That is why your loop has no body.
+ 2
Hmm to me this some how seem like a erro or a do nothing for loop because of the position of the semicolon (;) since it was a test it possible for it to be a printer error
+ 2
What a terribly designed question. Must be made by the same people who design highschool maths curricula.
0
its to loop things many times