Iterative Control

 An iterative control statement is a control statement providing the repeated execution of a set of instructions. An iterative control structure is a set of instructions and the iterative control statement(s) controlling their execution. Because of their repeated execution, iterative control structures are commonly referred to as “loops.”

While Statement

  • A while statement is an iterative control structure that repeatedly executes a set of statements based on a provided Boolean condition.
  • An example of a while loop in Python is shown in Figure, where it's used to calculate the sum of the first n positive integers, with n entered by the user.
  • When the condition of a while statement is true, the statements within the loop are executed or re-executed.
  • The loop keeps running until the condition becomes false, at which point the iteration concludes, and control proceeds to the statement immediately after the while loop.
  • Importantly, it's possible that the first time the loop is encountered, the condition is false, leading to the loop never being executed.

Consider the following scenario based on the example in the figure:

  • User enters the value 3.
  • As the loop begins, the variable current (acting as a counter) starts at 1. The condition current <= 3 is true, so the loop body is executed.
  • During the first iteration, sum is updated to 1 (initially 0 + 1) and current becomes 2.
  • Loop continues for the second iteration, where sum becomes 3 (previous sum + current) and current becomes 3.
  • Third iteration further increases sum to 6 (previous sum + current) and current becomes 4.
  • At this point, as control returns to the top of the loop, the condition current <= 3 is false, leading to the loop's termination.
  • The final value of sum is 6 (1 + 2 + 3).

This process of execution is depicted in Figure below.