Sometimes we repeat a code statement to solve a problem until a specific condition is satisfied. This is known as iteration, which allows us to "write code once" and "execute many times." In programming, iteration is often referred as ‘looping’ because instead of repeatedly writing the same code, we execute the same code finite number of times. Iteration provides code reusability and simplifies problem-solving.
In data structure and algorithms, several problem-solving approaches are based on iteration. So a good grasp of iteration fundamentals is essential for mastering these approaches. Here are some excellent examples of iterative problem-solving approaches:
- Building partial solution using a single loop
- Problem-solving using nested loop
- Two pointers approach
- Sliding window approach
- Problem-solving using a hashing
- Problem-solving using stack, queue and priority queue
- BFS traversal in a tree and graph
- Bottom-up approach of dynamic programming
Types of loops in programming
Iteration is implemented using the loop. We primarily use two types of loops: "for" loop and "while" loop.
for loop
We use the for loop when we know how many times the loop will execute. In other words, the for loop helps us to run some particular code statement defined number of steps.
Inside the for loop, we use a loop variable to control the loop execution, where the initial value of variable decides the starting point. So, we start by initialising the loop variable to some value and checking whether the loop condition is true or not. If the loop condition is true, code inside the loop body will execute. After this, execution will move to the next iteration by incrementing or decrementing the loop variable. This step will be repeated till the loop condition becomes false.
for (loop initialisation; loop condition; loop update)
{
loop body
}while loop
The while loop is used to execute the loop body until a specific condition is false. We mainly apply this idea when we don’t know how many times the loop will execute.
The while loop consists of a loop condition, a block of code as a loop body and a loop update expression if required. First, the loop condition is evaluated, and if it is true, code within the loop body will be executed. This process repeats until the loop condition becomes false. For better intuition, while loop can be thought of as a repeating if statement.
loop initialisation
while (loop condition)
{
loop body
loop update
}Special Notes
- There is a third type of loop: do-while loop. It is similar to while loop, where loop execution is terminated based on some condition. But the do-while loop condition is tested at the end of loop body.
- The do-while loop is exit controlled, whereas the for and while loops are entry-controlled loops.
- In the do-while loop, loop body will execute at least once irrespective of the test condition.
- It's an exercise for you to explore the various examples of the do-while loop.
Core elements of a loop
Loop initialisation: We initialize loop variables before starting the first iteration of the loop.
Loop condition: This is a boolean expression calculated at the beginning of each iteration to determine whether the loop body will execute or stop.
Loop body: The core part of a loop where we perform required operations to manipulate data at each iteration. There can be more than one code statement here.
Loop update: We perform increment/decrement on loop variables to control repetitions of the loop.
Here is the basic flow of a loop execution: Loop conditions will be evaluated first. If loop condition is true, then loop body will run and loop variable gets updated (increment/decrement operation). The loop body will run as long as the loop condition will be true. When loop condition becomes false, we exit the loop and continue with the further code instructions.
How to design a correct iterative algorithm?
We should consider these critical steps to design and check the correctness of an iterative code:
- Precondition: A condition that must be true before the loop begins.
- Postcondition: A condition that must be true after the loop terminates.
- Loop variant: A value that changes with each iteration and moves toward a stopping point, helping prove that the loop will terminate.
- Loop invariant: A condition that is true before and after every iteration. Variables may change, but the condition remains true.
Let's understand the above idea via some examples.
Example 1: finding the sum of all integers from 1 to n
Precondition: Initialise sum to 0 and i to 1. The loop will add the integers from 1 through n.
Postcondition: When the loop terminates, sum must be equal to 1 + 2 + … + n.
Loop variant: The loop continues while i <= n. Each iteration increases i by 1, so i eventually exceeds n, and the loop terminates.
Loop invariant: At the start of ith iteration, sum equals the sum of all integers from 1 through i - 1.
- During the ith iteration, add i to sum, then increase i by 1.
- After the ith iteration, sum is equal to the sum of all integers from 1 through the new i.
- When the loop ends, i = n + 1. So sum contains the sum from 1 through n.
Solution Pseudocode
findSum(n)
i = 1
sum = 0
while i <= n
sum = sum + i
i = i + 1
return sumExample 2: Find the max element in an array
Precondition: We initialise max to X[0] and start the loop at i = 1. At this point, max is the largest value so far.
Postcondition: When the loop terminates, max must contain the largest value in X[0..n - 1].
Loop variant: The loop runs while i < n. Each iteration increments i, so i eventually reaches n, and the loop terminates.
Loop invariant: At the start of ith iteration, max is the largest value in X[0..i - 1].
- We compare X[i] with max. If X[i] is larger, we update max to X[i]. Otherwise, we keep max unchanged. After this step, max is the largest value in X[0..i].
- Increment i. The invariant then holds at the start of the next iteration: max is the largest value in X[0..i].
- When the loop ends, i = n, so max is the largest value in the entire array.
Solution Pseudocode
findMax(X, n)
max = X[0]
for i = 1 to n - 1
if X[i] > max
max = X[i]
return maxSome common errors in writing loops
Infinite loops
An infinite loop occurs when a loop condition is true at every iteration or the loop fails to make progress toward termination. This often happens because of an incorrect update to a loop variable or an error in the loop condition. Usually, this is an error, but it's common for infinite loops to occur accidentally.
For example, we want to display the sum of all numbers from 5 to 10 via following code and end up with an infinite loop because we did not increment the loop variable. Here, the loop variable remains the same through each iteration, and progress is not made towards termination.
int i = 5
int sum = 0
while (i <= 10)
sum = sum + iHere is the correct version:
i = 5
sum = 0
while i <= 10
sum = sum + i
i = i + 1
print sumOther examples of Infinite loop
Example 1: For i < 0, this goes into an infinite loop!
infiniteLoop(i)
while i != 0
i = i - 1Example 2: Here loop condition is "1" which is always true!
i = 0
while true
i = i + 1
print(i)In some situations, an infinite loop can be used on purpose. For example, we use an infinite loop for applications that continuously accept user input and constantly generate the output until user comes out of the application manually.
Example 1: An operating system is the best example of it. It runs in an infinite loop and performs tasks continuously. It only comes out of an infinite loop when user manually shuts down the system.
Example 2: Suppose we read a sequence of data from input and stop reading as soon as a particular condition becomes true. The general structure of such input loop:
read the first element
while (element is valid)
{
process the element
read the next element
}Example 3: Some online games execute in an infinite loop. The game will keep accepting user requests until user exits from the game.
Example 4: A typical web server runs in an infinite loop as the server responds to all the client requests. It takes a request for a web page, returns a web page, and waits for the subsequent request. It will come out of an indefinite loop only when the admin shuts down the server manually.
while (true)
{
Read request
Process request
}Off-by-one error in a loop
This is an error involving boundary condition of the loop i.e. initial or termination condition of loop variables. Such a problem can arise when programmer makes mistakes like this:
- Using <=" instead of "<" while checking the expression in the loop condition.
- Fails to consider a sequence that starts at zero rather than one.
Off-By-One example 1
create array X with 5 elements
for i from 0 to 5
print X[i]The program above will cause an array out-of-bounds error because it tries to access X[5], while the highest valid index is 4. This happens because array indexing starts at 0 in most programming languages. The corrected code is shown below.
create array X with 5 elements
for i from 0 to 4
print X[i]Off-By-One Example 2
- Case1: for (int i = 1; i < n; i = i + 1) { ... }
- Case2: for (int i = 0; i <= n; i = i + 1) { ... }
Suppose we want to process n elements of an array starting from index 0. In the first case, loop will execute n - 1 time and in the second case, loop will execute n + 1 time. Both are situations of off-by-one error. The loop can be written correctly as: for (int i = 0; i < n; i = i + 1) { ... }.
Examples of various loop patterns
Single loop increasing by 1
Finding the nth Fibonacci using bottom-up approach of DP
for i from 2 to n
Fib[i] = Fib[i - 1] + Fib[i - 2]Kadane algorithm loop of finding maximum subarray sum
for i from 1 to n - 1
curr_maxSum = max(curr_maxSum + X[i], X[i])
if maxSum < curr_maxSum
maxSum = curr_maxSumBoyer–Moore voting algorithm of finding majority element in an array
for i from 0 to n - 1
if count == 0
majorityCandidate = X[i]
if X[i] == majorityCandidate
count = count + 1
else
count = count - 1Nested loop patterns
Nested loop of the Bubble sort algorithm.
for i from 0 to n - 1
for j from 0 to n - i - 2
if X[j] > X[j + 1]
temp = A[j]
X[j] = X[j + 1]
X[j + 1] = tempNested loop of the Insertion sort algorithm
for i from 1 to n - 2
key = X[i]
j = i - 1
while j >= 0 and X[j] > key
X[j + 1] = X[j]
j = j - 1
X[j + 1] = keyNested loop of finding transpose of a square matrix
for i from 0 to n - 1
for j from i + 1 to n - 1
swap X[i][j] and X[j][i]Single loop increasing by 2
A single loop of finding max and min in an array
while i < n
if X[i] < X[i + 1]
if X[i] < min
min = X[i]
if X[i + 1] > max
max = X[i + 1]
else
if X[i] > max
max = X[i]
if X[i + 1] < min
min = X[i + 1]
i = i + 2Single loop of sorting an array in a waveform
for i from 0 to n - 1, increasing by 2
if i > 0 and X[i - 1] > X[i]
swap X[i] and X[i - 1]
if i < n - 1 and X[i] < X[i + 1]
swap X[i] and X[i + 1]Single loop Increasing or decreasing by a factor of 2
Loop of exponential search in an unbounded array.
while i < n and X[i] <= key
i = i * 2Loop of iterative binary search
while left <= right
mid = left + (right - left) / 2
if X[mid] == key
return mid
else if X[mid] < key
left = mid + 1
else
right = mid - 1Loop of searching iteratively in a BST
while root is not null
if key < root.data
root = root.left
else if key > root.data
root = root.right
else
return trueTwo pointers loop: pointers moving in the opposite direction
Two-pointers loop of reversing an array.
while left < right
temp = X[left]
X[left] = X[right]
X[right] = temp
left = left + 1
right = right - 1Two pointers loop of finding pair sum in a sorted array
while l < r
if X[l] + X[r] == k
return 1
else if X[l] + X[r] < k
l = l + 1
else
r = r - 1Two pointers loop: pointers moving in the same direction
Two-pointers loop of merging algorithm in merge sort
while i < n1 and j < n2
if X[i] <= Y[j]
A[k] = X[i]
i = i + 1
else
A[k] = Y[j]
j = j + 1
k = k + 1Two-pointers loop of partition algorithm in quicksort
for j from left to right - 1
if x[j] < pivot
i = i + 1
swap X[i] and X[j]Two-pointers loop of finding loop in a linked list: Floyd algorithm
while slow not null and fast not null and fast.next not null
slow = slow.next
fast = fast.next.next
if slow == fast
return trueLoop on stack and queue data structures
BFS Traversal of a binary tree using queue
while Q is not empty
temp = Q.dequeue()
print temp.data
if temp.left is not null
Q.enqueue(temp.left)
if temp.right is not null
Q.enqueue(temp.right)Pre-order traversal in binary search using stack
while S is not empty
temp = S.pop()
print temp.data
if temp.right exists
S.push(temp.right)
if temp.left exists
S.push(temp.left)Critical ideas to think!
-
Sometimes we forget to initialize and update variable used in the loop condition. This is a serious programming error.
-
Although loops typically iterate over only one variable, sometimes loop can work with multiple variables.
-
When we declare a variable inside loop, the scope of that variable ends with the end of loop statement. In other words, the scope of the loop variable is inside the loop, and it can not be accessed from outside the loop.
int w for(int x = 0; x < 5; x = x + 1) { int y // we can use x, y, w here } int z // we can only use w, z here; x and y are only visible in the scope of the loop.
Critical concepts to explore in Loop
- break and continue loop statements
- Two pointers and sliding window approach
- The idea of iterator in data structure
- Iteration vs. Recursion comparison
- Iterative problem-solving approaches
- Time complexity analysis of various loops
Coding problems to practice using loop
- Convert roman to integer
- Fizz Buzz Problem
- Look-and-Say Sequence
- Move zeroes to an end
- Merge two sorted array
- Print a given matrix in spiral form
- Rotate a matrix by 90 degrees
Enjoy learning, Enjoy coding, Enjoy algorithms!
