Three Program Templates for Working with Arrays, Lists, or Vectors

These templates make working with sequenced data automatic

All programming languages provide some means of storing data sequentially. Some languages use arrays for this purpose. Some languages use the term list rather than array. Some languages provide both arrays and another sequenced data collection type – the vector (C++) or the ArrayList (Java and C#). To simplify things, I will call a data structure used to store sequential data a collection.

This article will demonstrate six program templates that the beginning programmer should learn to make decisions about how to work with these collections more automatic.  I will show you the pseudocode for the template and then provide two or three examples in different languages so you can see how the template is used. Sometimes there will be multiple pseudocode examples when there can be multiple ways of using the template, such as when adding data to an array versus adding data to a vector.

Fill an Array (or List or Vector, etc.)

This first program template is used when taking data from the user and storing it in a collection in order to make the data easier to work with. For example, if I want to collect the grades from a test and sort them from highest to lowest grade, it’s much easier to do this when the data is in a collection than if I tried to sort independent variables.

Here is the pseudocode for filling an array with data:

Declare the array with a size
Set an array index variable to 0
While there is more input:
  Read a value
  Store the value in the array at the index position
  Increment the index position by 1

Here is the pseudocode for filling a C++ vector with data:

Declare the vector with data type
While there is more input:
  Read a value
  Push back the value onto the vector

Here is the pseudocode for filling a Python list with data:

Declare the list
While there is more input:
  Read a value
  Append the value onto the list

Here is an example of filling an array in JavaScript:

let grades = new Array();
const NUM_GRADES = 5;
for (let i = 0; i < NUM_GRADES; i++) {
  putstr("Enter a grade: ");
  let grade = parseInt(readline())
  grades[i] = grade;

And here is an example of filling a vector in C++:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> grades;
    const int NUM_GRADES = 5;
    int grade;
    for (int i = 0; i < NUM_GRADES; i++) {
       cout << "Enter a grade: ";
       cin >> grade;
       grades.push_back(grade);
    }
    return 0;
}

Here is one more example in Python, using a sentinel value to control the input:

grades = []
grade = int(input("Enter a grade: "))
while grade != -1:
  grades.append(grade)
  grade = int(input("Enter a grade: "))

This template is used when you want to populate a data structure with interactive input. You can, of course, initialize most data structures with data without involving the user but that technique is covered with a syntax template, not a program template.

Process Every Element

Once you’ve filled a collection with data, you will want to perform some type of computation on that data. Frequently, you will want to access every element of the collection, such as to add it to a total to determine an average, or to sort the data into order, or even just to display the data on the screen. The Process Every Element template is used for these purposes.

There are different pseudocode examples for this template depending on the language you are using and the way you want to access the data. Most languages let you access a collection using an index, but many languages also let you use a simpler technique where you let the language do the indexing. I’ll demonstrate all these methods and discuss when to use them.

First, here is the pseudocode for processing every element using indexing:

For index = 0 through the length of the collection minus 1:
  Process the element at the index

Here is an example using this pseudocode in JavaScript, where the array is initialized at declaration:

let grades = new Array(71, 88, 91);
for (let i = 0; i < grades.length; i++) {
  putstr(grades[i] + " ");
}

This looks similar in other languages that use C-style syntax. In Python, the for loop looks a bit different:

grades = [71, 88, 91]
for i in range(0, len(grades)):
  print(grades[i], end=" ")

Indexed access to a collection can lead to errors if you accidentally try to access a collection element that is beyond the bounds of the collection. To remedy this, most languages now have a construct that allows you to access every element of a collection without using an index. Generally, this is called a for-each loop, with each language implementing this loop type differently.

We can, though, write the pseudocode in a general way and demonstrate its use in different languages. Here it is:

For each element in a collection:
  Process the element

Here is how the for-each loop is used in C++:

int main()
{
    const int NUM_GRADES = 3;
    int grades[NUM_GRADES] = {71, 88, 91};
    for (int grade : grades) { // range for loop
        cout << grade << " ";
    }
    return 0;
}

This works equally the same if the data is stored in a vector.

In JavaScript, the right for loop to use for an array is a for-of loop. Here is a program that computes the average of the grades in an array using the for-of loop:

let grades = new Array(71, 88, 91);
let total = 0;
for (const grade of grades) {
  total += grade;
}
let average = total / grades.length;
print("Average:", average);

The consensus of programming gurus is to use a for-each type loop whenever you are accessing every element of a collection like an array or vector if that type of loop is available in your programming language. Using the for-each type loop helps avoid either syntax errors (most languages) or logic errors (C++) in languages that allow access to memory outside the bounds of a collection.

Search a Collection

This program template is for linear or sequential search where the search begins at the beginning of a collection and either ends when the search finds the element searched for, or the search reaches the end of the collection without finding the element searched for.

As with the Process Every Element template, this template can be used with an indexed loop or with a for-each type loop. Here is the indexed template pseudocode:

get value to search for
set index to 0
for index < length of collection
  if collection[index] equals value to search for
    return success
if at end of collection
  report failure

 Here is an example of this template at work in Python, where a function is defined to search for a value in a list:

def search(coll, value):
  for i in range(0, len(coll)):
    if coll[i] == value:
      return True
  return False
from random import seed
from random import randint
seed(1)
grades = []
for i in range(10):
  grades.append(randint(50,100))
print(grades)
value = int(input("Enter search value: "))
if search(grades, value):
  print(value,"is in grades.")
else:
  print(value,"is not in grades.")

This program uses random number generation to build the list of grades and displays the list so we can verify the search function works by entering both values that are in the list and values that aren’t in the list.

The program template for doing a for-each search is like the indexed template:

get value to search for
start at beginning of collection
if current element is equal to value searched for
  return success
if at end of collection
  return failure

Here is an example of this template in use with C++, using a vector:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;

bool search(vector<int> vec, int value){
  for (int number : vec) {
     if (number == value) {
        return true;
     }
  }
  return false;
}

int main()
{
    srand(time(0));
    vector<int> numbers;
    for (int i = 1; i <= 10; i++) {
        numbers.push_back(rand() % 100 + 1);
    }
    for (int number : numbers) {
        cout << number << " ";
    }
    cout << endl;
    int value;
    cout << "Enter a value to search for: ";
    cin >> value;
    if (search(numbers, value)) {
        cout << value << " is in numbers." << endl;
    }
    else {
        cout << value << " is not in numbers." << endl;
    }

    return 0;
}

Here’s a hint with C++. You can’t use a range for loop in a function if the collection argument is an array. You can only use a vector in this situation. You can traverse an array with a range for loop in the main function, you just can’t use that type of loop in a value-returning function.

Program Templates and Programming Expertise

One key to becoming an expert programming expert is learning the different program templates that are used to solve problems. Much like chess grand masters become that way by studying famous chess match board positions, learning to quickly recognize when a program template should be used, and knowing how to use it effectively, will move you in the direction of becoming a programming grand master.