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.

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.

4 Program Templates Every Beginning Programmer Needs to Learn

Program templates are the key mental representation for successful programming

Photo by Patrick Amoy on Unsplash

Program templates are common patterns of programming code usage that come up again and again as solutions to programming problems. A key skill in computer programming is learning to recognize these patterns and then applying them to unique situations. In this article I’m going to discuss four program templates every beginning programming student should commit to memory and practice recognizing and applying in their programming practice.

Program templates, especially these beginning templates, are often not taught specifically either in textbooks or by programming instructors. They should be, though, as learning them will give students key mental representations that make writing their programs easier.

An old Pascal textbook I happen to own, Designing Pascal Solutions, by Mike Clancy and Marcia Linn, teaches and uses program templates extensively and you should look for this book if you are interested in learning about program templates. The program templates I discuss in this article come directly from this book.

This book is also a great example of a textbook that emphasizes project-based learning. I find that students learn better when they have a set of projects to work on, rather than just unrelated problem sets. I’ll talk more about project-based learning for teaching computer programming in another article.

Input-Process-Output

In many ways, every computer program you write is an application of this template. If you are not just writing a “Hello, world!” program, your program will be taking some data in (input), transforming (process) it in some way, and displaying the result (output) or doing something else with it, such as writing it to a file. For the beginning programmer, applying this template is the best way to get started in writing a program to solve a problem.

This template can be written in pseudocode as:

Input all the values
Process all the values
Output the results of the processing

Here is an example of a problem that uses this template:

Find the grade average by first entering three grades from the keyboard. Add the three grades together to get a total. Divide the total by the number of grades to get the average. Display the average.

Below is the sample code to solve this problem in Python. I require students to add a comment before each step of the template to indicate their knowledge of the template.

#input
grade1 = int(input("Enter the first grade: "))
grade2 = int(input("Enter the second grade: "))
grade3 = int(input("Enter the third grade: "))
num_grades = 3
#processing
total = grade1 + grade2 + grade3
average = total / num_grades
#output
print("The grade average is",average)

Having students memorize this program template helps them organize their thoughts on how to go about solving problems. This lessens the cognitive load so that they can use it to concentrate on getting the syntax correct as well as the logic necessary to solve the problem.

Prompt, Then Read

This template is a very basic pattern but one that beginning students don’t necessarily know. When teaching this, I emphasize that the prompt needs to be very informative so that the user enters exactly the information needed.

The pseudocode for this template is:

Display a message asking for a specific input (value)
Read the input (value)

Here are some code examples of this template in JavaScript:

putstr("Enter your six-digit id number: );
id_number = readline();
putstr("Enter your first name: ");
firstName = readline();
putstr("Enter your last name: ");
lastName = readline();
putstr("Enter your salary: ");
salary = parseInt(readline());

It is especially important for new programming students to learn and understand the importance of clear prompts for guiding users as to how input should be received. I find this instruction is also useful in helping students learn the importance of the specificity of data so that proper values are computed.

Do Something a Specified Number of Times

This is the first template I teach my students when I introduce them to for loops. In fact, I don’t introduce loops explicitly first, I introduce the template and then demonstrate the for loop as a means of implementing the template.

Here is the template:

Repeat a specified number of times:
  Perform some action

The first example I demonstrate in class is a classic “Hello, world!” example – Display “Hello, world!” five times on the screen. Here is the code in C++:

# write "Hello, world!" to the screen five times
for(int i = 1; i <= 5; i++) {
  cout << "Hello, world!";
}

Then I will modify the example and combine it with the “Input One, Process One” template, by having students prompt the user to enter their first name and having the program say hello to the name entered:

string firstName;
# say "Hello" to a name five times
for (int i = 1; i <= 5; i++) {
  #input one (also prompt and read)
  cout << "What is your first name? ";
  cin >> firstName;
  #process one
  cout << "Hello, " << firstName << "!" << endl;
}

At this point, my students are ready for a problem so I give them this one: Prompt the user to enter five grades and add them to a total. Here is the code I am looking for as a solution:

int grade;
int total = 0;
const int NUM_GRADES = 5;
#enter and total five grades
for (int i = 1; i <= NUM_GRADES; i++) {
  #input one - also prompt and read
  cout << "Enter a grade: ";
  cin >> grade;
  #process one
  total = total + grade
}

Notice that the comments for each step are required. Again, having my students enter a comment for each step in the template helps cement in their minds the steps of the process.

Input One, Process One

This template is introduced when I teach my students about loops. I usually introduce it as part of a problem that involves having the user input some data and then doing something to that data.

The pseudocode for this template is:

Repeat the following steps:

  Input a value
  Do something to the value

I typically use this problem to introduce the template and to have my students practice writing loops: Write a program that prompts the user to enter a grade and add the grade value to a total variable.

The code I am looking for looks like this (in Python):

count = 1
total = 0
while count <= 5:
  #input one
  grade = int(input("Enter a grade: "))
  #process one
  total = total + grade
  count = count + 1

The comments before the steps in the template are important and I always require them so that I know the student understands how the template works. Not only do these comments confirm their template knowledge, but they also help the student build a solid mental representation of the template by explicitly saying where they are in the template’s steps.

Program Templates are Chunks of Programming Expertise

Researchers in the expertise field have long recognized that experts become experts by “chunking” the key skills and techniques in their field. The classic example is the thousands of board positions chess grand masters intimately know through years and years of intense study. The important thing to know about chunking is that these chunks are not learned through just playing more games of chess. The people who become chess grand masters study the board positions in isolation from a complete game, then they are able to apply this knowledge in order to gain advantages over their opponents in actually chess matches.

The beginning programmer can use program templates to the same advantage. Spend some time memorizing the various program templates, both why and how they are used to solve regularly-encountered programming scenarios, and you will find that you will more quickly master your programming language.

Then, when you feel you’ve mastered these templates, start using them to solve harder and harder problems. This is the essence of deliberate practice and it is what always separates the experts in a field from the rest. You won’t become an expert by solving the same problems time and again. You have to continually challenge yourself with new and interesting problems.

How to Learn to Program: Writing Code Templates

Programming expertise requires knowing and using hundreds of templates

Photo by Patrick Amoy on Unsplash

This article is the fourth in a series of articles on a sequenced instructional approach to teaching computer programming. The steps in the sequence are: 1) Learning how to read code and understand what it does; 2) Learning how to write code from clear instructions; 3) Learning how to read program templates that solve common computer programming problems; and 4) Learning how to write program templates to solve programming problems.

You can learn more about this approach by reading A theory of instruction for introductory programming skills by Benjamin Xie and his fellow researchers at the University of Washington.

What is a Program Template?

A program template is a pattern of common code usage that can be applied to a programming problem. For example, the technique for swapping two variable values, used in sorting algorithms, is a program template because it can be applied any time you need to swap variable values.

Processing all the elements of an array (or vector or list) is another example of a program template. There are many, many program templates the learning programmer needs to learn in order to become an expert programmer. Programming expertise requires knowing and using hundreds of templates.

Expert Programmers Think in Program Template Chunks

As I explained in my article on reading program templates, program templates represent “chunks” of knowledge programmers need to be able to pull up almost instantaneously when solving programming problems. You can think of program templates like board positions in a chess match that chess grandmasters learn in order to use them to win a match.

Chess grand masters don’t get that way by just playing lots and lots of chess matches, though they do need to play lots of matches to become an expert. What they do is they spend hours studying the board positions of past famous chess matches to learn what positions are favorable for winning a match and how to get into those positions in order to defeat their opponent.

For beginning and intermediate computer programmers, program templates are like these chess board position chunks. By learning which templates should be used for solving most common programming problems, the programmer can access a template from memory with little work and instead use their brain power for more creative purposes.

Writing Program Templates Follows Understanding Program Templates

The step before using program templates to solve problems is learning about the different program templates that are available. Program templates are learned based on the program construct you are currently studying.

If you are just starting out and learning about variable assignment, it is appropriate to learn the program template for variable swapping. If you are working on branching statements, it is appropriate to learn the min/max template for determining the largest or smallest value from a data set. If you are learning about loops, the read one element then process it template is ripe for exploration.

I discussed how to learn to read program templates in a recent article and if you are just coming to this article without having read that one, go back and read it and I’ll be here when you get back.

How to Learn to Write Program Templates

As I’ve said, you can’t start writing program templates until you’ve practiced reading them and understanding their syntax and their logic. Then you can begin applying program templates to problems.

Let’s look at some problems and the templates that solve them. Many of these examples are taken from the paper by Benjamin Xie I referenced at the beginning of this article.

We’ll start with a variable swap problem: Cynthia has two mice that she uses with her laptop, but one of them is better contoured to her hand and she needs to use that one for the long project she is about to do. Unfortunately, the battery in that mouse is about drained and her other mouse has a stronger battery. Cynthia asks us to write a JavaScript program for her to exchange the batteries in her two mice so she can work longer with the better mouse.

Here’s the program:

let mouse1_battery = 1; // number indicates the battery charge
let mouse2_battery = 10;
let temp_mouse = mouse1_battery;
mouse1_battery = mouse2_battery;
mouse2_battery = temp;

The crucial concept to understand is that two exchange the two batteries, a temporary mouse must be used to hold a battery while one mouse is without a battery.

I have also demonstrated this concept physically by asking two students to come to the front of the class and put one hand behind their back. Then I give each of them a different colored marker and ask them to exchange markers without using the other hand and without dropping a marker. Of course, they can’t do it and must ask a third student (the temporary variable) to come to the front to help them. Programming instructors should spend more time creating physical demonstrations of the abstract concepts of computer programming.

Find the Minimum/Maximum

Here is an example of a branching template (JavaScript using the Spidermonkey shell): Find the minimum and maximum grades in a set of three grades entered by the user.

Here is the program:

putstr("Enter the first grade: ");
let grade1 = parseInt(readline());
putstr("Enter the second grade: ");
let grade2 = parseInt(readline());
putstr("Enter the third grade: ");
let grade3 = parseInt(readline());
let max = 0;
if (grade1 > grade2 && grade1 > grade3) {
  max = grade1;

}
else if (grade2 > grade1 && grade2 > grade3) {
  max = grade2;
}
else {
  max = grade3;
}
print("The max grade is",max);

For this template, the key concept is that each element must be tested against the other two elements and the comparisons must be made for all possibilities. In this case, there were three variables to compare but the template works for any number of compared elements.

Input – Process – Output

The last template we’ll look at is “input-process-output”. I usually start out a class of new programmers by telling them that this template is really the essence of every computer program, and it is certainly appropriate for the first few lessons in programming where students are learning how to assign values to variable and manipulate the variables using arithmetic or maybe some simple string processing (concatenation, for example).

The type of problem I use to test my students ability to recognize this template is like this one in C++: Prompt the user to enter three test scores with one prompt. Define a constant that represents the number of test scores. Sum the variables to get the total and then divide the total by the number of test scores to get the average. Display the average to the user using appropriate output (meaning more than just the bare number).

To demonstrate their knowledge of the template, I have them comment each part of the template.

Here is one student solution to the problem:

// input
int grade1, grade2, grade3;
const int NUM_GRADES = 3;
cout << "Enter three test scores, separated by a space: ";
cin >> grade1 >> grade2 >> grade3;
// process
int total = grade1 + grade2 + grade3;
double average = total / NUM_GRADES;
// output
cout << "The average of the test scores is: "
     << average << endl;

This solution does everything right except accurately compute the average. The reason is C++ does integer division so since the variable total is an integer and the constant NUM_GRADES is an integer, the result of the division is also an integer.

I have already taught them about integer division but it usually takes two or three programs before the concept sticks in their heads, so I remind them they must convert one of the operands in the average calculation to a floating-point type.

Program Templates are Pervasive in Computer Programming

There are many more program templates, of course, then I’ve demonstrated here. One of the best, and only, template-based introductory computer programming textbooks I’m aware of, Designing Pascal Solutions by Michael Clancy and Marcia Linn, identifies twenty templates that should be learned. There are many more for more advanced computer programming concepts, such as design patterns for object-oriented programming and the many algorithms used for searching and sorting data and for use with advanced data structures such as graphs and trees.

Become an Expert by Chunking Program Templates

Just as chess players improve their play by “chunking” the board positions of famous chess matches of the past, student programmers should be studying program templates so that they become chunks in the programmer’s mind. How do you do this? First, you must learn what the many different program templates are and where and when they are appropriate to use. Then, you need to practice using them on programming problems until their use becomes second nature.

And finally, you must keep extending your command of program templates by moving on to newer and more challenging programming problems. Try solving problems in a domain you’re not familiar with. If you are comfortable using imperative and object-oriented languages, spend a few months learning a functional language. If you are getting too complacent using relational databases, try using a NoSQL database on your next project. In all of these new domains, try to use the program templates you’ve learned to solve problems, and if the templates don’t apply in that domain, you’ll be learning new templates you can add to your toolbox.

And remember that expertise is a journey, not a destination.

How to Learn to Program: Reading Program Templates

Photo by Kelly Sikkema on Unsplash

Recognizing templates makes you a more expert programmer

The third step in a sequential instructional approach to learning computer programming is learning how to read program templates. A template is a set of programming instructions that represent a common code use pattern. Templates provide a means of moving from learning how to write code to being able to use programs to solve problems. Becoming an expert programmer involves learning to recognize when a specific template should be used to solve a problem.

Examples of Programming Templates

A first example of a template is “Variable swap”. The template looks like this:

  1. You are given two variables with values.
  2. Introduce a temporary variable and assign it the value of the first variable.
  3. Assign the first variable the value of the second variable.
  4. Assign the second variable the value of the temporary variable.

This template can be applied to every situation when you need to swap the values in two variables. This comes up most often in sorting applications, but it can happen in other situations as well.

Another template example is “Read one, process one”. The template is defined as:

  1. Get a value from the user or from a data structure.
  2. Perform some computation with the value.
  3. Go back to step 1 until there is no more data or the user chooses to stop.

This template can be used in several situations. One is when you need to read the elements of an array in order to perform some task, such as finding the average of a set of test scores stored in the array. Another example is when you want to prompt the user to enter data for either a set number of iterations or until the user chooses to quit by using a sentinel value.

A third template example is “Max/min”. This template is used to find the maximum and/or minimum values of a set of data. The template looks like this:

  1.  Use if statements to compare a first value with the other values in the data set.
  2. If there are remaining values to check, skip the first value checked and repeat step 1 for the other values.
  3. The else condition is reached if there are no other values to compare.

This template is used in many situations when searching or sorting data and is also a good template to use to have students practice using Boolean logic.

How to Practice Reading Code Templates

Students practice reading code templates by looking at templates and determining if they have been implemented correctly or not. If the template has not been implemented correctly, the student needs to be able to spot were the code was written incorrectly and correct it so that the template works the way it is supposed to.

Here is an example of an incorrect variable swap program in Python:

number1 = 1
number2 = 2
temp = number1
number2 = number1
number1 = temp

The student then does a variable trace on the program and discovers that number1 and number2 both end up with the same value – 1.

To correctly solve the problem, the student needs to see that after the first variable’s value is assigned to the temporary variable, the first variable needs to get the second variable’s value and the second variable gets the temporary variable’s value. The code should look like this:

number1 = 1
number2 = 2
temp = number1
number1 = number2
number2 = temp

Here is an example from another template – processing all the elements of an array, this time written in C++, and this code is also written incorrectly:

int grades[] = {81, 77, 75, 89, 78};
int total = 0;
for (int i = 0; i <= 5; i++) {
  total += grades[i];
}

When a variable trace is done on this program, including drawing out the array, the students sees that the loop goes beyond the upper bound of the array and accesses uninitialized data. Here is what a trace of this code looks like:

Variable trace for processing all elements of an array

In C++, this is not an error and the value of total will be modified by whatever numeric data (I call it junk data) is stored in memory at the location the program tried to access. Students need to be experienced at reading code to understand why this error occurred.

Describing Program Templates in English

Another exercise I use with my students is have them read code that implements a template and have them describe what the code does. This is a very eye-opening exercise for my students because they discover that having weak knowledge of either the template and the code, or both, makes it hard to write up a good description.

The following Python code implements a digit processing template that breaks down a number into its constituent digits:

n = 2945
print(n)
while n > 0:
  digit = n % 10
  print(digit, end=" ")
  n = int(n / 10)

An example description of this program is:

This is a digit-extraction program. The program breaks down a number into individual digits by computing the remainder of the number when divided by 10 (modulus) and then dividing the number by 10 to permanently remove the digit. Because Python does floating-point division, when the division operation is performed, the result must be converted to an integer before being stored back in the number. The program loops until the number reaches 0 or into the negative.

The process of having the student write out the description of the program helps seal the meaning of the program in the student’s mind. I often even have my students write this out on paper rather than type it up since recent research has shown hand-writing facts help students memorize them better than typing them up does because typing tends to cause the typist to just let the words flow through their fingers while they are typing rather than paying attention to the what the words are saying.

Program Templates are Chunks of Expertise

Researchers in the field of expertise have long found that experts become experts by “chunking” the important patterns in their field. The classic example is board-position chunks chess grand masters spend hours studying. By studying these positions over and over, the chess player will be able to recall them very quickly when needed during a chess match.

In much the same way, program templates are the board position chunks of programming, especially for beginning programmers as they transition to intermediate and advanced levels of expertise. By learning to read and understand how program templates work, the learning programmer makes these templates available to them for faster problem solving and more programming efficiency.

Reading and understanding program templates is the third step in the sequenced instructional approach to learning computer programming. The first step is learning to read code and the second step is learning to write code based on a set of clear instructions. The last step in the sequence is learning to apply program templates to unique situations and I’ll be covering this step in a future article.

How to Learn to Program: Writing Code

Photo by Christopher Robin Ebbinghaus on Unsplash

You can’t write code before you can read code

The four steps in a sequenced instructional approach to teaching programming are: 1) reading and understanding code; 2) writing code; 3) reading and understanding program templates; and 4) applying program templates to unique situations. I discussed the first step in the process in a previous article and in this article I dive into the second step: writing code from simple, clear instructions.

The Transfer from Reading Code to Writing Code

A mistake that many programming and textbook authors make when teaching beginning programmers is having the learner start writing code too soon. The beginning programmer needs to spend a lot of time reading code and learning to be able to predict the behavior of a sequence of code before they see it executed.

Learning how to read code should be broken down by programming construct, such as if statements and different types of loops. Before a learner can be expected to write an effective while loop, for example, they should have practiced reading while loops and tracing the code many times in many different situations, such as count-controlled loops and sentinel-controlled loops. It is only after having practiced on loops by tracing multiple times will the learner have enough experience understanding the behavior of loops to be able to start writing their own, effective loops.

It is when the learner starts to write code too soon that they experience errors in their code. They will receive syntax errors if they haven’t read enough code in a programming construct to understand how the construct should be formed. Then, if they aren’t experienced with predicting the behavior of a programming construct through code reading, they will have logic errors in their code when trying to write programs using that construct.

Learning to Write Code

At this stage of a learner’s development, learning to write code involves taking clear, simple instructions and translating them into a program.

Here’s one example of clear, simple instructions involving variable swap:

  • Declare x and y as variables and set them to the values 1 and 2, respectively.
  • Declare temp as a third variable and set its value to x.
  • Set x’s value to y.
  • Set y’s value to temp.
  • Display the new values of x and y.

The learning programmer should be able to translate these instructions into a working program. Here is the translation into Python:

x = 1
y = 2
temp = x
x = y
y = temp

Here is another example to use when learning the if-else construct:

  • Prompt the user to enter the cost of a soda.
  • If the cost of the soda is less than or equal to $2, then recommend buying the soda.
  • If the cost of the soda is greater than $2, then recommend not buying the soda.

Here is the translation in JavaScript (using the Spidermonkey shell):

putstr("Enter the price of a soda: ");
let price = parseFloat(readline());
if (price <= 2.00) {
  print("You can buy the soda.");
}
else {
  print("Do not buy the soda.");
}

Commenting Code for Understanding

Though there is some dispute among programmers as to when and how much to comment code, the learning programmer should be writing comments often. They should do this to demonstrate their understanding of what they are writing.

Each line of code should have a comment that expresses what the programmers thinks that line of code should be doing. Here’s an example of how a learner should be using comments in a program that utilizes a while loop to sum numbers entered by the user:

# set accumulator to zero
total = 0
# counter to control loop starts at 1
count = 1
# loop condition tells how many times to iterate
while count <= 10:
  # prompt the user to enter a number
  print("Enter a number:", end=" ")
  # get number as string from user
  number = input()
  # convert number to integer

  number = int(number)
  # add number to the total
  total = total + number
  # increment the count by 1 so loop will stop
  count = count + 1
# display the total
print(total)

Of course, the experienced programmer would never put such obvious comments in their programs, but learning programmers need to make their intentions explicit, both for themselves and for whoever is giving them feedback.

Even though comments can be placed at the end of a statement, I prefer learners put the comments before the line. This forces them to state what the next statement is going to do and then they can write that statement.

Eventually, as learning programmers become more experienced, I allow them to drop the comments from their code for constructs they have demonstrated proficiency with. When they learn a new construct, however, their first coding attempts must include comments for each statement.

Comments are Important for Understanding Errors

I have my students write comments before every line so that I can check their intention. This way, I can more easily decide if an error is caused by a misuse or misunderstanding of syntax or a misuse or misunderstanding of program logic.

Another way to state this is to say that comments allow me to quickly figure out if a student understands what to use a programming construct for and/or if a student doesn’t understand how to properly construct that programming construct. When this is the case, I take the student back to the first step and have them do more variable and program tracing until they feel confident they understand how that construct works.

But the comments aren’t just for the teacher. As the student is beginning to learn how to write code, writing the comment first allows them to think through what they are going to do and make sure they understand the problem they are trying to solve.

Memorizing Syntax Templates is Important

All through the code reading phase and into the code writing phase, if necessary, I have my students learn and memorize the syntax template for each construct they are learning. This is important because while they are writing code, if they have the syntax template for a construct memorized, they already know how to form the construct syntactically and they can concentrate on using it to solve a problem. This reduces cognitive load and it also lessens the chances that the student will make many syntax errors while moving through the code writing phase.

I have written separately about syntax templates, but here are some examples for a few popular languages:

Variable declaration – Java:

data-type variable-name;

Assignment statement – C#:

variable-name assignment-operator expression;

for loop – C++:

for (init-variable; condition; variable-mod)
{
  statements;
}

while loop – Python:

while (condition):
  statements

function (traditional) – JavaScript:

function function-name (parameter list)
{
  statements;
  return statement;
}

When these templates are memorized, the student can concentrate on using them rather than having to recall how they are formed. I quiz my students daily on syntax templates at the end of class, just like my junior high civics teacher used to quiz us on state capitols at the end of every class.

Code Writing is Just Step 2 in the Process

As important as learning to write code is for any beginning programmer, it is just a second step in a four-step process. First, the learning programmer needs to know how to read and interpret (in the non-technical sense) code. Next, he or she needs to learn how to write code from clear, precise instructions. The third step, and the next article in this series, is to be able to apply a template of common code use for the construct they are learning. And finally, the learning programmer needs to be able to apply these templates to unique problems.

Once the student reaches this fourth stage, they are ready to move into more advanced programming topics such as algorithms, data structures, and object-oriented programming.

How to Learn to Program: Variable and Program Tracing

A variable trace example

There are four main steps to learning any new programming construct. The first step is learning how to read code by doing variable and code traces. The second step is writing code from pseudocode. The third step is to learn how to read code templates, such as a template for swapping two variables or a template for testing if a value is within an acceptable limit. The fourth step is to be able to apply learned code templates to unique problems.

These steps are laid out as a theory of sequential instruction in a paper by a group of researchers at the University of Washington. The lead author of the paper is Benjamin Xie, and you can find the paper here at his web site.

In this article, I’m going to discuss the first step in this theory of programming instruction – learning how to read code by practicing variable and code tracing.

Why Learning How to Trace Code is Important

Variable and code tracing (program tracing) are used to teach students how to read a program and accurately predict its behavior by being able to follow the control flow from the beginning of the program to the end of the program. In the paper by Xie, et.al., the authors declare that tracing code is a different skill than writing code and is a skill that must be mastered before learning to write code. A learner can’t be expected to write original code if they have not mastered reading code and predicting its behavior. A great way to teach this skill is by tracing code, both variables and whole programs.

Variable Tracing

There are several ways to practice variable tracing. One way is to perform a variable trace on a program. This technique is often taught at the very beginning of a course as students are introduced to how program process arithmetic statements. For example, the figure below shows a sample C++ while loop and a variable trace where new values for variables are written down and then marked off when the variable obtains a new value:

Tracing two variables

A more involved problem might have the student demonstrate how array data is used in a calculation. Given this JavaScript program:

let grades = new Array(71, 88, 83, 92, 67);
let total = 0;
let average = 0.0;
for (let i = 0; i < grades.length; i++) {
  total += grades[i];
}
average = total / grades.length;
print("The average grade is", average);

Tracing a program that uses an array

This example demonstrates another way to show variables and their updates as a program executes.

Program Tracing

Program tracing has the student indicating the flow of control in a program, sometimes by drawing arrows indicating the flow and other times by circling lines that are executed or marking out lines of code that aren’t executed. We’ll look at examples of all of these in this section.

The first type of program tracing is drawing arrows to indicate the flow of control in a program. The figure below demonstrates how to show the control flow for a program that has one loop and an if statement inside the loop:

Indicating program flow with arrows

The other way you can trace a program is to circle the lines of a program that execute and mark through the lines of a program that don’t execute. Here is an example of using this technique on a program that involves an if-else if statement:

Indicating control flow with circles and lines

This program trace indicates the second print statement will execute because the temperature is above 60 and it is rainy outside.

These types of exercises require students to learn how to predict the behavior of a program by understanding how a program construct affects the program’s control flow.

Parsons Problems

A Parsons Problem is a set of scrambled lines of code that the student must put into the correct order so that the program executes properly. These types of problems are excellent for determining a student’s ability to read code. They have also been shown to be more efficient for teaching programming than exercises in writing code or fixing errors in existing code (see this paper).

Here is an example of a simple Parsons Problem involving variable swapping using a Parsons Problem generator. The first screen shot is the program with the code in the correct order:

Then click the Generate an Exercise button and the code is jumbled up and placed into blocks, as shown below:

The student then drags the blocks into the blank area to the right and then hits the Evaluate button to see if they’re answer is correct, as shown in this next screen shot:

Parson Problems are a fun and different way to test code reading knowledge and need to find a bigger role in computer science education. I will devote a future article to more on why Parsons Problems are so effective.

Reading Code Comes Before Writing Code

As Benjamin Xie and his co-authors state in the paper A theory of instruction for introductory computer programming, students learn programming better when they are introduced to code reading first via the use of various tracing techniques. Practicing reading code and participating in practice drills via code and variable tracing, along with learning how to recognize code errors, help the student gain a better understanding of how code works before they first even try to write one program. One of the major faults with computer programming education today is that instructors have their students writing code as early as the first day, which is way too soon for new programmers.

Beginning programming students need to learn to read code, understand what it means, how it works, how to recognize errors in programs, and why it works before they begin writing their own code.

Once students do begin writing code, they need to start slowly by taking clear, English-like instructions and turning those instructions into working code before they start working on harder problems. This step is the subject of my next article.

How to Learn to Program: Start with an Interpreted Language

Photo by Code💻 Ninja⚡ on Unsplash

So you want to learn how to write computer programs? Where do you start? What language do you learn first? In this article, I’m going to suggest that you start with an interpreted language that has a shell program (also called a REPL) you can use to practice with.

What is a Shell Program?

A shell program is a program that allows you to type in programming statements and receive the output from those commands immediately. Shell programs are also called REPLs, with stands for Read-Evaluate-Print-Loop. In other words, a REPL is a program that reads programming statements, evaluates (executes) them, prints their output, and then loops back so you can enter another statement.

Languages such as Python and JavaScript have shell programs you can use to practice writing programs. This is because Python and JavaScript are interpreted languages (go here for more information on interpreted programming languages) and it is common to implement a shell program for an interpreted language. Languages such as C++ and Java, which are compiled languages (go here for a definition of compiled programming languages), don’t have REPLs that come with the language but there are separate REPL programs you can buy. However, I suggest you start your programming education with either Python or JavaScript because interpreted programming languages are generally easier to learn than compiled languages, so let’s see how you can get REPLs for those two languages.

As I began my programming education many years ago during the dark first PC ages, just about every PC came with a BASIC interpreter, some of which had the interpreter installed in ROM. You just boot up the computer and you’re immediately in the shell program. I still remember how easy it was to sit down at the computer with my textbook and just start entering BASIC statements to see what would happen. That’s how learning programming should be for everybody.

Python and JavaScript Shell Programs

When you download the Python language you automatically get a shell program. To use it, simply open a command prompt window and type ‘python’. You will see a little message and then the Python shell program prompt will appear:

>>>

The Python shell is now waiting for you to enter Python statements for it to evaluate. I’ll show you how to work with the Python shell later in this article.

Getting a REPL for JavaScript is a little harder. A very popular choice in the JavaScript world is a program called node.js. Node is a system for creating JavaScript applications but when you download Node, you also get a JavaScript REPL. Go to Node’s home page and download Node. Once it is installed, you can start the shell program by typing ‘node’ at a command prompt. The program loads and you see a prompt like this:

Now you can start entering JavaScript statements and have the shell program interpret them.

Another option for JavaScript is the SpiderMonkey shell program. This shell program is developed by Mozilla (Firefox) and it also interprets JavaScript code but has a few different features than Node. You can find the SpiderMonkey shell program here. After you download the right shell program for your computing environment, you can open the shell program by typing ‘js’. The shell prompt appears like this:

js>

And you’re ready to start entering JavaScript statements.

A third way to use a JavaScript interpreter is to open a web browser and find the developer tools option for that browser. There will be an interpreter of some type located there you can use to execute JavaScript statements. Here is a screen shot of the JavaScript interpreter in use with Firefox:

Example Shell Interactions

Here are some screen shots that show some examples of interacting with the Spidermonkey, Node, and Python shell programs, in that order.

Node shell interaction
Spidermonkey shell interaction
Pytbon shell interaction

As you can see from these examples, interacting with the shell is easy and very intuitive. Just enter the statements you want to execute and you can immediately see the result in the shell.

Writing Shell Scripts

The JavaScript and Python shell programs also let you write what are called shell scripts. A shell script is a program that is written in a text file and then given to the program interpreter to run. Once you’ve mastered a language using the shell program, you’ll want to switch to shell scripts for writing more complex programs.

Here is an example of writing a shell script for Spidermonkey. I work in a Windows environment so the first thing I do is open Notepad (no judgement, please) and type in my program. I have to make sure when I save the file to save it with a .js extension, as required by the shell. Here is a screen shot of the text file:

A JavaScript shell script for the Spidermonkey shell

The next step is to execute the script from the command line. Here is a screen shot:

I can execute the same program as-is with Node, except I need to change the print function to console.log since Node doesn’t use the print function. Here is the screen shot:

I can do the very same thing with Python. First, create a Python program in a text editor and be sure to save it with a .py extension. If you are copying my program, you’ll need to make one or two changes, but I’ll leave those as an exercise for you, as any good instructor would do. Then call the shell program with the name of the script file. Here is a screen shot:

Online Interpreter Environments

There are several online JavaScript and Python interpreters you can use. Just do a search for web-based JavaScript or Python interpreters and you will be shown several sites you can use for exploring these languages online. One of my favorite sites that hosts many different languages is repl.it. I encourage you to explore their site and play around with the many interpreters found there. This site also have online compilers you can use to learn compiled languages such as C++ and Java without having to download and install a compiler and/or an IDE to write, compile, and run programs.

Why Start with an Interpreter?

Learning an interpreted programming language for your first programming language has several advantages over learning a compiled language first:

  1. An interpreter allows you to enter a statement and see the results immediately. A compiler forces you to go through the edit-compile-build-run cycle every time you want to evaluate a program.
  2. Interpreted languages have a more user-friendly syntax than do compiled languages. For example, Python doesn’t require curly braces for designating blocks of code (it uses indention) and Python statements don’t have to end with a semicolon.
  3. The ease of entering statements and seeing their results encourages exploration because there isn’t such a long program development cycle (see reason 1 above).
  4. Some programming concepts are easier to demonstrate first using an interpreter. For example, when I am teaching my students that a literal evaluates to itself, it’s hard to demonstrate this with a compiled language. With an interpreter, a learner can simply type a literal value into the shell and see that the shell returns just that value. Another example is order of operations. A learner can modify the order of operations in an arithmetic statement and see immediate changes without going through the compiling cycle.

Learning Programming with an Interpreter

If you are just starting out learning to program, pick a language that has a shell program you can use. The best way to learn programming is to explore what the language can do with short, simple programs, building your way up to harder, more complex programs. You can do this best with a shell program. If you are learning C++ or Java, look for one of the shell programs I mentioned earlier in this article.

The most important thing to do is just start. Start writing programs and start right now.

Learning How to Program: Creating Syntax Template Chunks

One of the traits that separate experts in a field from amateurs is the expert’s ability to call up structures from memory at a very fast rate. In programming, one set of structures all beginning programmers should memorize are the syntax templates of the major programming constructs for a programming language. Programming constructs can also be considered chunks. In this article I’ll discuss what syntax templates are, how and why they are considered chunks, and why chunking is important for developing programming expertise.

Syntax Templates

A syntax template is the formal definition of a programming construct. In this section we’ll look at several example templates covering the major fundamental programming constructs in several popular programming languages.

Syntax templates describe the grammar of a programming language. These templates are used as models of how to write the various programming constructs of a language. For example, in C++, here is the syntax template for declaring a variable:

data-type variable-name;

This template indicates that to declare a variable in C++, you start with the data type of the variable, follow that with a variable name, and end the statement with a semicolon. Applying this to a real program, a variable declaration could look like this:

string name;

Most programming languages allow you to declare a variable and assign it a value in the same statement. Here is that syntax template for JavaScript code:

const|var|let variable_name assignment-operator expression;

In this example, there are three possible ways to start a variable declaration: const, var, or let. The bar indicates that a variable declaration can use any one of these keywords. The assignment operator is the = character and the symbol could be used in the template, but I prefer the name, as this aids in helping the student memorize the template.  

I have the hardest time explaining to beginning students what expression means in the template. They may have already seen that literals are often used in these types of statements and that doesn’t jibe with what they believe expressions are. I must convince them that literals are just expressions that evaluate to themselves. If the language has REPL shell, you can demonstrate how a literal evaluates to itself by simply typing a literal at the command prompt and showing how the return value is just the literal.

Assignment statements have their own syntax template. Here is the assignment statement syntax template for Python:

variable-name assignment-operator expression

if statements have a syntax template for each type of if: simple if, if-else, and if-else if. Here are the templates for if statements in Java (and C, C++, etc.):

if (relational expression)
{
statement(s);
}

if (relational expression)
{
statement(s);
}

else
{
statement(s);
}

if (relational expression)
{
statement(s);
}

else if (relational expression)
{
statement(s);
}


[else
{
statement(s);
}]

Notice that inside the blocks the “s” in statement(s) is in parentheses. This means that there can be one statement or multiple statements (we’ll ignore the fact that there can be no statements at all) in each of the blocks.

The hardest part of teaching these if templates to students is the if-else if statement. The ellipsis in the template indicates that there can be multiple else if blocks and the square brackets around the else block indicates that it is optional.

Also notice that my use of syntax templates puts curly braces around the different blocks even if there is only one statement in the block. This is becoming the more standard usage when writing blocks after relational expressions to cut down on errors.

Syntax templates for loops are written similarly. Here is the syntax template for a C++ while loop:

while (relational expression)
{
  statement(s);
}

The syntax template for a while loop in Python, however, looks like this:

while relational-expression:
  statement(s)

Similarly, the syntax template for for loops in languages that follow C-like syntax looks like this:

for(variable-init; relational expression; variable-mod)
{
  statement(s);
}

The Python for loop looks quite a bit different. Here is the syntax template:

for iterator-var in sequence:
  statement(s)

Function definitions have a syntax template as well. For C-like languages, the template looks like this:

return-type function-name(parameter list)
{
  [statement(s);]
  return expression;
}

Or like this for void functions:

void function-name(parameter list)
{
  statement(s);
}

I have my students indicate in the template that the statements in a function body are optional, since it is possible to define a function that only has a return statement. This template also leaves out additional modifiers to member functions in C++, such as const. I do include this when I have my students learn the templates for member functions.

Why Memorizing Syntax Templates is Important – Chunking

One of the key techniques learning researchers have identified as necessary for expert performance is the use of chunks. So what is a chunk? Barbara Oakley, an engineering professor at Oakland University, in her book A Mind for Numbers: How to Excel at Math and Science, defines chunks as “pieces of information that are bound together through meaning.” In chess, chunks are patterns of board pieces that represent different stages of a chess game played by expert chess players. Chess grand masters store about fifty thousand chess game chunks in their minds and can recall them in seconds when playing a chess game.

Why are chunks so important? The ability to chunk individual concepts makes the expert that much quicker at solving problems. For the chess player, being able to recognize a pattern of chess pieces as a chunk quickly allows them to both decide their next move faster and allows them to analyze how that move will affect future moves in ways that just looking at the individual pieces of a chess board simply would not allow.

For learning programmers, it’s very important to learn how to recognize when a specific programming construct is needed and how to use that construct without having to go back to notes on how the construct is formed. The second part to chunking is learning how to solve a problem by applying different chunks (constructs) in the right place at the right time. Computer programs always consist of if statements here, function calls there, and loops in several places. The knowledge needed to write good computer programs is built from the ground up and the foundation of this knowledge are the fundamental programming constructs we’ve been talking about in this article.

How to Create Programming Construct Chunks

The first step in creating a chunk from a programming construct is to focus on learning the syntax template. Study it carefully, but not just in one long session but over a longer period, such as two or three times in a day, and every other day until you really know it. Spaced learning is more effective than concentrated learning. During this learning time, try writing out the syntax template from memory and then checking your answer against your notes or the textbook. Retrieval practice is much better than just reading over the template time after time.

The second step is be sure you understand what the programming construct is used for and how to apply it to specific problems. I tell my students to start by doing a variable trace over several example problems until they completely understand how the construct works.

Next, run several of the examples from a class lecture or the textbook to see what output the program returns. Modify the values of the variables in the program and try to predict what the output will be.

Once you’re comfortable with this step, the final step is to start trying to solve some problems that use the construct in order to understand the context in which the construct is used. It is great if you can start by working from pseudocode of the problem, either your own or pseudocode that is provided to you before you try to solve problems completely from scratch.

Another way to perform this step is to work from problem templates. There are several problem templates in computer programming, such as variable swapping, computing a running total, etc. These templates give you the context for solving a problem and allow you to apply the construct to the template. Then, once you’ve mastered using the template, you will start seeing how to apply it to unique problems.

With little differences here and there, these are the steps that all learners take as they become experts in their field.

Practice Makes Chunks

Your ability to become a great computer programmer depends on your ability to chunk the various programming constructs so that you can immediately recognize when a chunk is needed and how to apply that chunk to the problem at hand. Constructs become chunks through consistent practice over time. The first step is to memorize the syntax template of the construct. The second step is to understand how the construct works and the third step is to know how to use the construct and when the construct’s use is appropriate. The best way to create programming construct chunks is to practice them a little every day. As you learn a new construct, put it into your programmer’s toolbox and use it, along with the other constructs you already know, to solve new and harder problems. Doing this regularly puts you on the path to programming expertise.

Become a Great Programming Through Deliberate Practice

Developing Greater Programming Skills

In this final article on using deliberate practice to become a great programmer, I discuss how and why programmers need to be continually working to improve their programming skills through specific practice.

Expert Performance is Based on Incremental Skill Development

To become an expert programmer, you must master the many skills programming requires. The first, and most important step, is to master the fundamental constructs of programming, including decision making constructs, repetition constructs, modularization constructs, data structures, and algorithms. These skills are all taught in the course of a four-year degree in computer science, though its possible for a self-taught programmer to learn them on their own. If that’s the case, the self-taught programmer will still need the advice of a wise, more experienced programmer to ensure that the learner is developing their skills in a proper, useful way.

As Anders Ericsson and Robert Pool state in their book, Peak: Secrets from the New Science of Expertise, the fundamental skills of a field must be taught properly, and learned properly, before moving on to more advanced skills because learning advanced skills necessarily depend on being able to perform the fundamental skills properly and if this is not the case, the programmer will have to go back are relearn the fundamentals before moving on.

Advanced Programming Skills Depend on Fundamental Programming Skills

Like many fields, advanced programming skills depend on the programming adequately learning more fundamental programming skills. For example, you can’t master even a basic sorting algorithm such as the shell sort or even the bubble sort if you haven’t mastered writing loops, since these algorithms rely on loops for their implementation. From there, you can’t go on to master a more advanced sorting algorithm, such as QuickSort, if you haven’t mastered the more fundamental skill of recursion, which is used in many implementations of QuickSort.

It’s really very simple – you can’t become an expert programmer until you master the fundamental skills of programming.

How to Master Fundamental Programming Skills

A recent paper by researchers at the University of Washington (UW) outlined a theory of sequenced instruction for learning computer programming. I have written previously on the best way to teach computer programming on my blog – How Introductory Computer Programming Should be Taught, where this a link to the original paper. We can apply these same techniques to learning computer programming fundamentals. The four steps outlined here should be performed for each new program construct being learned – from simple statement execution, through decision making, through looping, and through developing functions and subroutines. Skipping any of the four steps can lead to misconceptions concerning the construct being learned.

The first step is to learn how to read programming code. The best way to do this is by performing variable traces of existing programs. Tracing the values of variables teaches you how to follow the flow of a program by keeping up with the values of variables during program execution. Research has shown that students who can understand how a program works by tracing its variables will have an easier time learning to write code.

The next step after reading code is writing code. You learn this by taking a set of problem solving steps, either written in pseudocode or plain English, and translating them into a program. The student should be able to perform this step without considerable trouble if they have been adequately taught how to read code first.

The third step is to learn patterns of usage of the construct. This is often taught by presenting templates of usage to the student. An example of a template is variable swap. The template could look like this:

There are two variables whose values are to be swapped. Introduce a third variable, often called the temporary value and assign it the value of the first variable. Then assign the value of the second variable to the first variable. Finally, assign the value of the temporary variable to the second variable.

This looks like pseudocode and if the second step has been learned well, it is a straightforward exercise to translate the template into code. This step should be performed several times so that it is engrained as a pattern.

The last step is to then learn to apply the template to unique situations. An example given in the paper by the UW researchers is a scenario where a person has two flashlights, each one having a different specific use. The first flashlight is needed but its battery is weak compared to the second flashlight. The student is asked to write code to swap the batteries of the two flashlights. If the student understands the variable swap template, they can apply the template directly to write the code to swap the batteries in the two flashlights.

The UW researchers found that students in their classes who learned various Python programming constructs using this sequenced instruction performed better on tests than did students who were taught with a more traditional sequence of instruction.

Learning and Practicing Advanced Programming Skills

The key to becoming an expert through deliberate practice is to continually be working on harder problems just beyond your current capabilities. Once a programmer has mastered programming fundamentals, possibly including object-oriented programming if your language uses it as a primary paradigm, the next step is mastering data structures and algorithms.

The first step is to master the fundamental data structures of your language, whether it’s the array or the list. These data structures form the basis for many of the advanced data structures used in programming. You can find exercises you can use to practice your mastery of these data structures in any computer programming textbook or online at one of the many computer programming tutorial sites.

As you’re mastering these fundamental data structures, you should also be working to gain mastery over two fundamental algorithms that use arrays and lists – searching and sorting. Learning how to search through an array or list will help you later when you learn more advanced searching algorithms, such as heuristic search. The two fundamental searching algorithms you should learn first are linear search and binary search.

After searching, the next most common task to perform on a set of sequential data (the type of data typically stored in a list or array) is sorting. There are several elementary sorting algorithms that should be learned (insertion, bubble, shell) before moving on to the more advanced sorting algorithms (QuickSort and MergeSort).

These algorithms can also be found in any computer programming textbook and there are also several excellent online sources you can use to learn how to use these algorithms.

Once these fundamental data structures and algorithms are mastered, students should move on and master more complex data structures and algorithms. It would take too long to mention all the data structures specifically, but the general groups are trees, graphs, hash tables, and heaps. Each of these data structures has their own set of algorithms that are used to search the data stored in them.

Where to Find Problems to Solve

The best place to learn about advanced data structures and algorithms is initially in one of the many computer science textbooks written on these topics. The problem with these books is that, for the working programmer, the material is too theoretical. What the working programmer really needs to know is how is a data structure or algorithm used in practical applications and where do I find it in a particular language’s library, or if its not found in a library, how do I implement it for a practical application?

I have found that the best place to work on these skills is by working through a book on programming problems for job interviews. While the use of this type of problem solving in job interviews is controversial, the material the books cover is quite practical and can really help programmers gain more mastery over their craft.

Three of these books that I’ve found useful are: Programming Interviews Exposed by John Mongan and Noah Kindler; Cracking the Coding Interview by Gayle McDowell; and Daily Coding Problem by Lawrence Wu and Andrew Miller.

Here are two examples of problems from Daily Coding Problem, starting with a data structure problem followed by an algorithm problem:

Given a sorted array, convert it into a height-balanced binary search tree.

Given an array of strictly the characters, R, G, and B, segregate the values of the array so that all the Rs come first, the Gs come second, and the Bs come last. You can only swap elements of the array.

The beauty of books like Daily Coding Problem is that they not only provide you with challenging problems to solve and the solutions, but they also provide good explanations of the solutions so the reader can better use this information on a job interview. An important facet of deliberate practice is that the developing expert must have access to good, immediate feedback.

All programmers, even those not looking for new jobs, should be working out of one of these books on a regular basis.

Expertise is a Journey, Not a Destination

Becoming an expert computer programmer is an ongoing process. Regardless of where you are in your mastery of computer programming, there is always a next level you can, and should be, striving to obtain. If you think you can get to a point where your programming education is finished, you are wrong. The best thing you can do is recognize that to become a truly expert computer programming, you must embrace the fact that the journey never ends and learning to love the process of becoming an expert computer programmer is more important than achieving complete mastery, because complete mastery is impossible to obtain.