There are 3 options that depend a little on what you want. Note that your code never enters the if
for the condition within the for
does not allow negative values. Your for
run for the last time when the i
is 1 and making i--
gives it one last value of 0
and its if
searching for <0
. Having said that the options are:
break;
The break stop the loop and goes to the first line of code afterward loop. If you don’t need to traverse all iterations of a loop
but need to run code after loop, use this option.
continue;
continue jumps to the next loop iteration. If you don’t need to run all the code for a specific iteration, but you need all the iterations, use this option.
Return;
Return stops the function it is in and returns the value after the word "Return". Be inside a loop, switch or other function stops immediately and does not run the next line to Return.
Regarding the processing economy depends on what you need. The most economical is Return because it is the most powerful and ensures that no more code is run. The suggestion is to always use the most defective and not limit the code you want to run.
It is useful to use these methods to save processing? Yes, without a doubt.
It depends. If you"and just want to interrupt the loop,
break
is the best option. If you want to interrupt the loop And already abort any function logic, returning a valuereturn
is better because it works on both ends.– Bruno Augusto
But... that code will never enter
if
!– bfavaretto
The boom can reach less than 10.
– ptkato
In that case the body of
for
does not perform any time.– bfavaretto