Repetition Structures

Overivew

Repetition structures is the formal name for loops. Loops allow programmers to do amazing things in short lines of code. Loops are great because they allow a piece of code to be executed mutliple times without assuming or guess how many times the repetition needs to happen. Loops are a conditional structure which does depend on true or false (relational) expressions to drive them. However, unlike decision structures that use the condition to execute a body and move on with the code (hence if), the loop with recheck the condition after an execution (call an iteration) and reiterate the execution if the condition is still true. In programming, these are typically called while conditions.

On this page we will stay really high level and talk about loops in the following contexts: condition-controlled while loops, counting (for) loops, and nested loops. Once again, C++, Java, and C# will look very familiar in the structure of loops but Python will have a bit of a different approach.

Loops are also critical in future programming constructs such as arrays which are only sifted through using loops.

Looping guide line

Every loop in code should follow the same steps in order to iterate properly. Let's start with this abstract example:

var loopControlVariable = initialValue
while (loopControlVariable == True) {
  body
  loopControlVariable = updatedValue
}

Every loop has what we refer to as a loop control variable. We can identify the loop control variable as the the variable situated in the while statement. Once we identify the loop control variable the steps are as follows:

  • initialize the loop control variable
  • define the condition for the loop control variable to run the loop
  • update the loop control variable in the body of the loop

If the loop control variable is not updated int he body of the loop, the loop will be an infinite loop which is not what most programmer want. If a programmer really wants an infinite loop, they would write this:

while(true){
  ...
}

As we go through programming examples, note that the loop steps are always followed.

Condition-controlled loops

When a loop is condition-controlled that simply means that the code will continue iterating until some particular condition is met. Let's say for example that you are using the ATM and you have completed a transaction. The ATM shows a screen that says "Would you like to do something else?" This appears along with a Yes/No option. If you select yes, the program displays the options menu and you start all over again. If no is selected, the machine issues your card and ends your interaction.

Condition-controlled loops are considered indeterminate because we have no idea how many times the body wiil be executed, we just know that there is a proper condition to end the loop.

For our programming example let's consider a simple adder that will give the user the option to keep adding until they are satisfied.

Language Code
C++ #include<iostream>
using namespace std;

int main() {
  cout << "Adding Program\n\n";
  int num1, num2;
  char endProgram = 'n';
  while (endProgram == 'n') {

    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter second number: ";
    cin >> num2;
    cout << num1 << " + " << num2 << " = "
      << (num1 + num2) << endl;

    cout << "\nTo add another pair of numbers type 'n' or any other key to end: ";
    cin >> endProgram;
    endProgram = tolower(endProgram);
  }
}
C# using System;
Namespace Adder{
  class AdderProgram{
    static void Main(string[] args){
      Console.WriteLine("Adding Program\n");
      int num1, num2;
      string input;
      char endProgram = 'n';

      while (endProgram == 'n'){
        Console.Write("Enter first number: ");
        num1 = int.Parse(Console.ReadLine());
        Console.Write("Enter second number: ");
        num2 = int.Parse(Console.ReadLine());
        Console.WriteLine($"{num1} + {num2} = {(num1 + num2)}");

        Console.WriteLine("\nTo add another pair of numbers type 'n' or any other key to end: ");
        input = Console.ReadLine();
        endProgram = char.Parse(input.ToLower());
        }
      }
    }
}
Java import java.util.Scanner;

public class AdderProgram{
    public static void main(String[] args){
      Scanner keyIn = new Scanner(System.in);
      int num1, num2;
      String input;
      char endProgram = 'n';

      while (endProgram == 'n'){
        System.out.print("Enter first number: ");
        num1 = keyIn.nextInt();
        System.out.print("Enter second number: ");
        num2 = keyIn.nextInt();
        System.out.printf("%d + %d = %d%n", num1, num2, (num1 + num2));

        System.out.print("To add another pair of numbers type 'n' or any other key to end: ")
        input = keyIn.nextLine();
        endProgram = input.toLowerCase().charAt(0);
      }
    }
}
Python endProgram = 'n'
while endProgram == 'n':
  num1 = int(input("Enter first number: "))
  num2 = int(input("Enter second number: "))
  print (num1, " + ", num2, " = ", (num1 + num2))
  endProgram = input("To add another pair of numbers type 'n' or any other key to end: ")
  endProgram = endProgram.lower()

Programming Notes: There are a few things going on and many of it to make the program work for us. You may notice that in Java and C# there is a string variable to receive keyboard input because those languages do not read characters directly from the keyboard. Python does not even have a character data type so we just treat the string like a character.

Looping Notes: endProgram is the loop control variable initialized to 'n'. The test condition (condition for the loop to run) is that the loop control variable is equal to (==) 'n'. The loop control variable needs to be updated inside the body of the loop. In our example the program asks for input and sets endProgram to a new value. Here are the steps of program execution:

  1. set endProgram to 'n'.
  2. evaluate if endProgram == 'n' is true.
  3. exectue the arithmetic section.
  4. ask the user to enter how they wish to continue and sets endProgram to the user's entry.
  5. the while statement is executed to see if the condition is still true. If it is, steps 3 and 4 are executed again. If not, the program moves on.

Do-While loops

While Python does not support do-while loops, these loops are built to where the body of the loop is executed at least once. The body of the loop is written before the condition. A google search for do-while loops will give you more tips on how to use them.

Counting Loops

Counting loops are determinate repetition structures. We know how many times this loop will execute prior to the execution. We can use any loop construct (while) to execute a counting loop. However, the primary tool to use for counting is the for loop. This loop is awesome since it takes all three steps of loop design and puts them in one header line. Let's take the example we worked with on the condition-controlled side and set the code so that the user will find the sum to 5 pairs of numbers.

Language Code
C++ #include<iostream>
using namespace std;

int main() {
  cout << "Adding Program\n\n";
  int num1, num2;
  for(int count = 1; count <=5; count++){
    cout << "Addition #" << count << ":\n";
    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter second number: ";
    cin >> num2;
    cout << num1 << " + " << num2 << " = "
      << (num1 + num2) << endl;
  }
}
C# using System;
Namespace Adder{
  class AdderProgram{
    static void Main(string[] args){
      Console.WriteLine("Adding Program\n");
      int num1, num2;
      for(int count = 1; count <= 5; count++){
        Console.WriteLine($"Addition #{count}");
        Console.Write("Enter first number: ");
        num1 = int.Parse(Console.ReadLine());
        Console.Write("Enter second number: ");
        num2 = int.Parse(Console.ReadLine());
        Console.WriteLine($"{num1} + {num2} = {(num1 + num2)}");

        }
      }
    }
}
Java import java.util.Scanner;

public class AdderProgram{
    public static void main(String[] args){
      Scanner keyIn = new Scanner(System.in);
      int num1, num2;
      for(int count = 1; count <= 5; count++){
        System.out.printf("Addition #%d", count);
        System.out.print("Enter first number: ");
        num1 = keyIn.nextInt();
        System.out.print("Enter second number: ");
        num2 = keyIn.nextInt();
        System.out.printf("%d + %d = %d%n", num1, num2, (num1 + num2));

      }
    }
}
Python for count in range(1, 6):
  print("Addition #", count)
  num1 = int(input("Enter first number: "))
  num2 = int(input("Enter second number: "))
  print (num1, " + ", num2, " = ", (num1 + num2))

Notice that the initial condition, test condition, and how to count are included in the loop header in C++, C#, and Java. The body of the loop in these instances are a bit more simple than the body of while loops and do while loops because you do not have to worry about loop updates. C++, C#, and Java have the ++ operator that means increment. There is also a decrement operator --. This ++ operator adds 1 to an int variable. So if x = 5, then after x++, x = 6; The decrement operator is similar.

Python is a bit different. Python uses the in range() function that can be created three ways

  1. for count in range(5): where count starts and 0 and goes to 4 (5 iterations)
  2. for count in range(1, 6): where count starts at 1 and goes to 5 (5 iterations)
  3. for count in range(5, 0, -1): where count starts at 5 and goes to 1 but explicitly states to count by -1. This instance is usually used if incrememting by more than 1 or counting backwards.

The range is always one less than the end count.

For loops are also great for accumulations. So if we wanted to add the sum of the first ten numbers we could do the following:

int total;
for(int i = 1; i <=10; i++){
  total += i;
}

total is an accumulator that allows us to keep adding into it until it the count is reached.

Nested Loops

Like decision structures, loops can be written inside other loops. These are nested loops. When we put loops in other loops we can really perform a lot of work in short lines of code. A lot of notebooks feature the multiplication tables from one to 12. We can write that using nested loops. See the coding examples below.

Language Code
Assume all headers and functions/methods have been properly defined
C++ for(int i = 1; i <= 12; i++){
  cout << "-----" << i << "-----\n";
  for(int j = 1; j <= 12: j++){
    cout << i << " x " << j << " = " << (i * j) << endl;
  }
  cout << "------------\n";
}
C# for(int i = 1; i <= 12; i++){
  Console.WriteLine($"-----{i}-----");
  for(int j = 1; j <= 12: j++){
    Console.WriteLine($"{i} x {j} = {(i * j)}");
  }
  Console.WriteLine("------------");
}
Java for(int i = 1; i <= 12; i++){
  System.out.printf("-----%d-----", i);
  for(int j = 1; j <= 12: j++){
    System.out.printf("%d x %d = %d%n", i, j, (i * j));
  }
  System.out.println("------------");
}
Python for i in range(1, 13):
  print("-----", i, "-----\n")
  for j in range(1, 13):
    print(i, "x", j, "=", (i * j))
  print("------------\n")

We note then that the for loop written inside another for loop serves to form a nested loop. This particular piece of code will print the 144 products of numbers between 1 and 144 in little time. This demonstrates the power of loops. It is always good to be careful with using loops as they can cause a lot of nightmares if not properly handled.

Review

Loops are quite useful for helping programmers in solving really large tasks. Over the course of your career, you will learn more about how loops can be implemented in problem solving, including controlling reading data from files, websites, and using loops to control data from collections. I believe loops and decisions are two of the most valuable programming concepts that someone new to programming can learn.