1. Use a for loop to repeat calculations for a specific range of values:
b is defined locally, it is not known outside the program.
2. Use the program to evaluate the sum when a=5
The program performs the same operation as the summation operator:
3. Use a while loop to repeat calculations until a condition is violated. The program below finds the square root of a positive real number, terminating when the estimate of the root squared is less than a threshold amount different from target value.
4. Use the continue operator in a program that adds only odd integers between 0 and n by skipping the even ones using continue. The continue operator stops execution of the current iteration and restarts it at the top of the nearest enclosing loop for the next iteration.
By comparison, the summation operator includes all the non-negative integers:
5. Use the break operator to break out of a while or for loop prematurely. The program below refines the estimate of the square root until it is better than ε, or until it has reached its maximum number of iterations.
6. Use loops in recursive programs. The program below calculates the factorial of a number:
7. Compare this result with the built-in factorial operator: