4 More Program Templates Every Beginning Programmer Should Learn

Learning program templates leads to programming expertise

Photo by Jefferson Santos on Unsplash

In an earlier article I discussed four program templates every beginning programmer should learn. I also discussed why learning program templates is so important. Briefly, program templates are chunks of knowledge that programmers use to develop solutions to problems. Learning and practicing these templates allow programmers to more quickly develop solutions to the common, and uncommon problems, they frequently encounter in the course of writing a program.

The four templates I discussed before are: Input-Process-Output; Prompt, Then Read; Do Something A Specified Number of Times; and Read One, Process One. In this article I’m going to discuss four more templates: Select from Alternatives; Input and Process Until Done; Process in Cycles; and Accumulate Values Until Done.

I found these templates, along with many others, discussed in detail in the book Designing Pascal Solutions by Mike Clancy and Marcia Linn. Besides basing their exploration of the Pascal language on learning and using program templates, the book is project-based, with each chapter representing a different, long-form project for the student to complete. Project-based learning does not play a big enough role in introductory computer programming and I plan to create new learning material following the projects and program templates presented in this book.

Select from Alternatives

This program template is used to select a value based on multiple alternatives. Two programming constructs can be used when demonstrating this template. If the value being selected is a single value, such as a letter or a number, a switch statement can be used if the language provides this construct. For other situations, such as ranges of values, or if the language doesn’t provide the switch statement, as is the case with Python, you can use if statements.

The pseudocode for this program template looks like this:

if value1, choose alternative1
if value2, choose alternative2
if valuen, choose alternative-n
else, perform other action

Here are some examples. This first one, written in JavaScript, uses a switch statement to convert a decimal number to a Roman numeral:

putstr("Enter a number: ");
number = parseInt(readline());
switch (number) {
  case 1:
    print("I");
    break;
  case 2:
    print("II");
    break;
  case 3:
    print("III");
    break;
  case 4:
    print("IV");
    break;
  case 5:
    print("V");
    break;
  default:
    print("Did not recognize that input.");
}

This next example demonstrates how to use the Select from Alternatives template when the values are ranges (in C++):

int temp;
if (temp > 70 && temp <= 90) {
  cout << "Go hiking";
}
else if (temp > 50 && temp <= 70) {
  cout << "Play golf";
}
else if (temp > 28 && temp <= 49) {
  cout << "Bundle up then go hiking.";
}
else {
  cout << "Build a fire and stay inside." << endl;
}

Input and Process Until Done

This program template is used to teach both the while loop and the do while loop, especially when teaching students how to write sentinel-controlled loops that stop when the user enters a special value.

There are two pseudocode examples for this template. The first one is for while loops:

while not finished, do the following:
  read a value
  process it

This next one is for do-while loops:

repeat the following until finished:
  read a value
  process it

Here is a problem that requires the first version of this template: Write a loop that has the user enter grades, adding them to a total. Stop when the user enters -1. Here is the program in Python:

grade = 0
total = 0
while grade != -1:
  total = total + grade
  grade = int(input("Enter a grade: "))
print(total)

The do-while loop requires the conditional statement at the bottom of the loop, so it is used for different situations. Here is a sample problem: Write a program that prompts the user to enter their password until they enter it correctly. Here is a JavaScript solution:

let password = "letmein";
let login = "";
do {
  putstr("Enter your password: ");
  login = readline();
} while (login != password);
print("You're in!");

Process in Cycles

This program template is used to perform a cyclic process, such as performing an action in a loop when a certain condition occurs. This template often involves a test inside the loop that determines what action to perform.

Here is the pseudocode for this template:

for a specified number of times or while a condition is true:
  test for condition:
    perform action if true
  else:
    perform action if false

The test does not have to include an else clause but I included it in the pseudocode for completeness.

The first problem example involves entering numbers and testing to see if the number is even or odd and counting each occurrence. Here is the solution in Python:

evens = 0
odds = 0
number = int(input("Enter a number: "))
while number != -1:
  if number % 2 == 0:
    evens = evens + 1
  else:
    odds = odds + 1
  number = int(input("Enter a number: "))
print("Evens:",evens)
print("Odds:", odds)

Here is the next problem: Count and display the number of spaces in a string. This problem requires you to traverse the string like an array, checking to see if the current element is a space, incrementing a count variable if so.

Here is the solution in JavaScript:

let sentence = "now is the time for all good people";
let count = 0;
for (let i = 0; i < sentence.length; i++) {
  if (sentence[i] == " ") {
    count++;
  }
}
print("Number of spaces:",count);

Accumulate Until Done

This program template is used for several different programming problems. The first thing to notice is that it is an extension of a program template we’ve seen before: Input and Process Until Done. This template can be used for simple problems, such as adding values to a total until the input is complete, and for more complex problems, such as find the minimum and maximum values of data input by the user.

The pseudocode for this template is:

Initialize a variable or set of variables to store the values “accumulated”
Repeat for each value in the sequence entered:
  Accumulate the value

This template does not just have to be used to find a running total or product. As I suggested in the opening paragraph, you can also use it to find a minimum or maximum value. I’ll demonstrate this in one of the example programs below.

Here is the first problem this template matches: Have the user enter 10 grades. Sum the grades and display the average. Here is a solution to this program in C++:

int main()
{
    int total = 0;
    int grade;
    const int NUM_GRADES = 10;
    for (int i = 1; i <= NUM_GRADES; i++) {
        cout << "Enter a grade: ";
        cin >> grade;
        total += grade;
    }
    double average = static_cast<double>(total) / NUM_GRADES;
    cout << "The average is: " << average << endl;
    return 0;
}

This program template can also be used with a sentinel-controlled loop that accumulates values until the user stops the program by entering a sentinel value, such as -1. Here is that program in C++:

int main()
{
    int total = 0;
    int grade;
    int count = 0;
    cout << "Enter a grade (-1 to stop): ";
    cin >> grade;
    while (grade != -1) {
        total += grade;
        count++;
        cout << "Enter a grade (-1 to stop): ";
        cin >> grade;
    }
    double average = static_cast<double>(total) / count;
    cout << "The average is: " << average << endl;
    return 0;
}

This program template can also be used to determine the minimum or maximum value from a set of values. Here is an example of such a program in Python:

number = int(input("Enter a number: "))
minimum = number
maximum = number
for i in range(1,5):
  number = int(input("Enter a number: "))
  if number < minimum:
    minimum = number
  if number > maximum:
    maximum = number
print("Minimum:",minimum)
print("Maximum:",maximum)

This program “accumulates” a minimum and a maximum value by continually comparing the next number entered with the current minimum and maximum values, exchanging the values when necessary.

Teaching with Templates

Computer programming is by nature a problem-solving endeavor. Most computer programming textbooks teach by organizing the material by constructs – start with variables, move to arithmetic, then to decision-making, then to looping, then to functions, and then to array and on from there.

A better way to teach programming may be to organize the material by program templates. Teach variables by implementing the Prompt, Then Read template and then perhaps the Variable Swap template. Teach decision-making using the Select from Alternatives template. Teach looping with the templates discussed in this article, such as Process with Cycles or Input and Process Until Done. Arrays, lists, and/or vectors can be taught using the Process Every Element of a One-Dimensional Array template. Teaching with templates might provide better scaffolding for students than hitting them so hard over the head with syntax and unrelated exercises.

Chunking Leads to Expertise

As the many, many studies of experts have shown, developing complex mental representations (chunks) using techniques of deliberate practice turn intermediate performers into experts. In chess, the chunks grand masters learn are board positions of famous chess matches. In computer programming, the fundamental chunks that all programmers should learn and practice with are program templates. It is through many hours of study and practice using program templates that a student can move from being a merely adequate programmer to being an expert programmer able to solve the hardest programming problems.