Iteration
- Repeating a set of instructions or calculations until a condition is satisfied.
- Common in programming (e.g., for loops) and mathematics (e.g., recursive definitions).
- Used to break complex tasks into repeated steps or smaller subproblems.
Definition
Section titled “Definition”Iteration is the repetition of a certain process or algorithm in computer programming and mathematics, performed by repeating a set of instructions or calculations until a specific condition is met.
Explanation
Section titled “Explanation”Iteration repeats instructions to achieve the efficient completion of complex tasks. In programming, iteration typically uses constructs like for loops with a counter variable to traverse sequences or arrays; the loop continues while a condition holds and stops when the condition is no longer true. Recursive algorithms implement iteration by calling the algorithm itself with reduced inputs until a base case is reached, at which point the recursion stops.
Examples
Section titled “Examples”For loop example
Section titled “For loop example”A for loop iterating through numbers 1 to 10:
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}In this example, the counter variable i is incremented by 1 with each iteration. The loop continues until the condition i <= 10 is no longer true.
Recursive factorial example
Section titled “Recursive factorial example”Mathematical definition: the factorial of 5 is 5!, which is equal to 5 * 4 * 3 * 2 * 1 = 120.
A recursive algorithm to compute factorial n:
int factorial(int n) {
if (n == 1) {
return 1;
}
else {
return n * factorial(n - 1);
}
}In this example, the function calls itself with a reduced value of n on each iteration until the base case n == 1 is reached.
Use cases
Section titled “Use cases”- Iterating through a sequence of numbers or elements in an array (for loops).
- Implementing recursive algorithms for problems such as search algorithms and complex data structures.
Notes or pitfalls
Section titled “Notes or pitfalls”- A loop continues until its condition becomes false; ensure the loop condition will eventually be false to avoid infinite loops.
- Recursive algorithms require a base case (for example, n == 1 in the factorial example) to terminate the recursion.
Related terms
Section titled “Related terms”- For loop
- Recursive algorithm / Recursion
- Counter variable
- Sequence
- Array
- Base case
- Factorial
- Search algorithms
- Data structures