+ 2

No body in the "for loop"

Hello everyone 👋 I recently faced a situation when it was necessary to use the "for loop" without it's body. I mean the curved brackets like these {}. Everything works perfectly but I think I don't quite understand what's going on and how does the loop differs from the normal loop. Does it iterate the code lines until the condition is met unlike the normal loop that iterates the whole body?

2nd Aug 2019, 6:14 AM
Paul Smith
Paul Smith - avatar
2 Answers
+ 14
Without the curly braces, only the first statement after the loop statement is executed repeatedly. for (...) { stmt1; stmt2; } In the above, both stmt1 and stmt2 will execute as part of the for loop. for (...) stmt1; stmt2; In spite of how this looks due to the indentation, only stmt1 is part of the part loop body. The second statement, stmt2 is not part of the loop.
2nd Aug 2019, 6:20 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
You can also have a for loop like this where everything is done in the header. https://code.sololearn.com/cGO63bKEmyoB/?ref=app
2nd Aug 2019, 10:00 AM
Sonic
Sonic - avatar