Programs > Example: Looping and Control
  
Example: Looping and Control
1. Use a for loop to repeat calculations for a specific range of values:
Click to copy this expression
* 
b is defined locally, it is not known outside the program.
2. Use the program to evaluate the sum when a=5
Click to copy this expression
Click to copy this expression
* 
The program performs the same operation as the summation operator:
Click to copy this expression
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.
Click to copy this expression
Click to copy this expression
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.
Click to copy this expression
Click to copy this expression
By comparison, the summation operator includes all the non-negative integers:
Click to copy this expression
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.
Click to copy this expression
Click to copy this expression
6. Use loops in recursive programs. The program below calculates the factorial of a number:
Click to copy this expression
Click to copy this expression
7. Compare this result with the built-in factorial operator:
Click to copy this expression