What is Iteration? Give an example.


Q.) What is Iteration? Give an example.

Subject: Data Structures

Iteration

Iteration is the process of repeating a set of instructions until a specified condition is met. It is a fundamental concept in computer science and is used in various programming constructs, such as loops, recursion, and generators. The ability to iterate allows programs to handle repetitive tasks efficiently and concisely.

Example:

Consider the following Python code that calculates the factorial of a non-negative integer n:

def factorial(n):
  if n == 0:
    return 1
  else:
    return n * factorial(n-1)

The factorial function uses recursion to calculate the factorial of n. It first checks if n is equal to 0. If it is, the function returns 1 because the factorial of 0 is defined as 1. If n is greater than 0, the function recursively calls itself with n-1 and multiplies the result by n to obtain the factorial of n.

This recursive approach involves iterating through each value of n from the given input value down to 0. Each recursive call represents one iteration in the process. The recursion continues until the base case is reached (n == 0), at which point the function starts returning values back up the call stack, accumulating the final result.

In this example, iteration is achieved through recursion. However, iteration can be implemented using loops, such as for loops and while loops, which provide a more explicit way to control the number of iterations.

Iteration is a powerful tool that enables programs to efficiently execute repetitive tasks and handle various types of data structures. It is a fundamental concept that forms the basis of many computational algorithms and programming techniques.