# 6.10.4. Loops

Only one loop per function [Multiple loops: 2-8 points]

 Each function definition can only have one loop.

It must be possible to do a loop's body more than once [Loop is not loop: 1-3 points]

 Do not use while to mean if. If you write a loop, there should exist some circumstances where the loop body can be done more than once.

Do not mix loops and recursion [Loop with recursion: 1-4 points]

 A function 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-2 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 function 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 changes control variable: 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 changes 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.

Initialize for a for-loop in the heading where sensible [For loop initialization: 1-2 points]

 The first component of a for-loop heading is for initializing the control variable. Use it unless you have a good reason for not using it.

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 that uses two loops, so you simulate it with one loop, as follows. ``` int i = 0; int j = 0; while(i < n) { doSomething(i,j); j++; if(j == m) { j = 0; i++; } } ``` You can recognize this by the reset of j to 0 when j = m. That is not an acceptable way to avoid two loops in one function. Just write a function to handle the inner loop. ``` void doAll(int i) { for(int j = 0; j < m; j++) { doSomething(i,j); } } ``` Now your loop becomes ``` for(int i = 0; i < n; i++) { doAll(i); } ```