Each method body can only have one loop. |
Do not mix loops and recursion [LOOP-WITH-RECURSION: 1-4 points]
A method that contains a loop must not also use recursion. |
If code is only performed at the end of the last iteration of a loop, then it should be written after the loop. If code is only performed at the beginning of the first iteration, it should be written before the loop. [LOOP-END: 1 point]
Look at the following example.
int loopdemo(int n) { for(int i = 0; i < n; i++) { doSomething(i); if(i == n-1) { finish(i+1); } } }Notice that statement finish(i+1) is only done at the end of the last iteration of the loop. This method should be written as follows. int loopdemo(int n) { for(int i = 0; i < n; i++) { doSomething(i); } finish(n); } |
Do not change the value of a for-loop control variable in the loop body [FOR-BODY-CHANGE: 1-3 points]
A for-loop
control variable (any variable that is modified in the third
part of a for-loop heading) should only be modified in the for-loop heading,
not in the body of the loop. For example, do not write
for(i = 1; i < n; i++) { … i = n; … }If you want to break out of a loop, use break or return. |
Do not change a for-loop end value in the loop without justification [FOR-BODY-END: 1-3 points]
Do not change the end-value of a for-loop just as a way to get
out of the loop. For example,
for(i = 1; i < n; i++) { … if(condition) { n = 0; } … }is not a good way to cause the loop to end. If you want to exit a for-loop, use break or return. |
Do not simulate two nested loops or two consecutive loops using a single loop. [NESTED-LOOP-SIMULATION: 2-8 points]
It is possible to do a lot in a single loop by managing variables in
complicated ways. Imagine that you want to do two nested for-loops,
as follows.
for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { doSomething(i,j); } }But instead you write int i = 0; int j = 0; while(i < n) { doSomething(i,j); j++; if(j == m) { j = 0; i++; } }That is not an acceptable way to avoid two loops in one method. |