How to Teach Arrays in Computer Science
Tags: teaching, education, computerscience, programming
Published: 2019-05-18 00:07:11

It may seem odd that I’m trying to teach arrays when I’ve already written [an article about the data structure](https://therenegadecoder.com/code/array-data-structure/). But, articles are only so useful at conveying a concept. In this article, we’ll cover a few methods for conveying the concept in a classroom setting. If all goes well, I might make this into a series!

## What Are Arrays?

Before we dive in, I’d like to preface this article by stating that the approach in this article is largely language-agnostic. In other words, I won’t focus on any specific languages, but I will draw from my Java, C/C++, C#, and Python experience. As a result, there may be some concepts used that aren’t necessarily language-agnostic (i.e. indexing from zero, strings, etc.). Regardless, I think there are plenty of lessons to be learned by having concrete examples.

Naturally, my target audience with this article is fellow teachers who are looking for some new methods to teach the same old concepts. In addition, I’m looking to use this article as a way to document some of the things I’ve learned over the years. As a result, you can expect this article to grow and develop over time.

So, what are arrays? Well, I’m assuming you already know. If not, maybe you should check out [my article on Arrays](https://therenegadecoder.com/code/array-data-structure/), but to summarize:

An array is a collection of data. More specifically, an array is a fixed-size chunk of memory that is split into cells for data storage. The size of the data type determines the size of each cell and the overall size of the array.

In C-like languages, arrays are defined as follows:

```java
int[] numbers = new int[10];
```

In this example, we’ve defined an integer array of size 10. In other words, we can store at most 10 integers. Naturally, we can make arrays of any type and any size. However, those parameters of the array are fixed after declaration.

Alright, that’s enough review for now! Let’s continue!

## Learning Objectives

When teaching arrays, we should have a handful of goals we want to reach by the end of the lesson. In no particular order, here are a few of mine (using Java as an example).

**Students should be able to:**

- Understand and use array-related terminology: 
  - Array
  - Element
  - Index 
- Read and write valid array syntax: 
  - Declare: `int[] arr;`
  - Define: `arr = new int[10];`
  - Set: `arr[3] = 5;`
  - Get: `int x = arr[2]`
- Accomplish usual array tasks:
  - Populate
  - Traverse
  - Search
  - Sort
  - Copy

Depending on the lesson, we may want to expand or narrow the scope of this list. Regardless, this is a great start!

## Challenges

When it comes to learning arrays, students may run into a few challenges. In this section, I’ll share some of the challenges I’ve noticed, and how I try to address them.

### No Data Structures Intuition

By the time arrays are introduced, students usually have no intuition around data structures. If they want to store some values, they often opt for as many variables as it takes to get the job done.

To address this knowledge gap, I like to relate arrays to something they’ve used quite a bit already: strings. After all, strings are just character arrays with extra functionality.

One transferable skill from strings is indexing. If students understand how to retrieve characters from a string by index, they should be comfortable indexing an array. Likewise, strings often start indexing at zero, so students familiar with strings should be able to draw the connection.

Regardless, this may be the first time a student is dealing with the concept of a data structure, so it’s important to relate the idea to collections they might know from everyday life.

### No Indexing Intuition

For some students, arrays might be the first time they’ve ever had to start counting from zero. For most students, indexing from zero is counterintuitive. After all, we typically start counting from one in everyday life. Of course, starting from zero isn’t exactly a foreign concept. After all, we usually start from zero with continuous data like timelines, so there are plenty of opportunities for real world parallels.

As mentioned already, strings can be a great place to start if you’ve already introduced them. In many programming languages, strings are character arrays, so the parallels should be clean cut. Just be aware that strings are often immutable, and arrays are typically not.

### No Reference Type Intuition

If arrays are the first time a student is exposed to objects, they’re bound to run into a few problems. For instance, this may be their first time dealing with references, so it’s important to demonstrate that copying is a nontrivial task.

Also, as mentioned previously, students may have used strings before. Unfortunately, the parallels between strings and arrays sort of break down when talking about reference types. In many languages, strings are immutable, so you can’t actually make changes to them like you can to an array. Be aware of this mental leap if you choose to use strings in your examples.

## Methods

Given the learning objects and challenges, how do we go about actually teaching arrays? In this section, I’ll cover some of my favorite methods with examples.

### Teaching Through Related Principles

As mentioned several times already, there’s a good chance that students already have some familiarity with a data type that closely mimics arrays: strings. After all, if your course starts with Hello World, then you’ve already exposed your students to strings.

I like to use strings because a lot of languages model them using arrays. In languages like Java, it’s not a stretch to go from `str.charAt(0)` to `str[0]`. In other languages like Python (which uses something closer to an array list), the syntax is exactly the same. As a result, there’s a good chance you’ve already taught arrays.

Of course, there are usually a few loose ends you need to tie up. For example, initialization is usually a bit different. Be certain to share that arrays may have a different initialization syntax than strings:

```java
String str = "Hello"; 

// vs 
char[] str = {'H', 'e', 'l', 'l', 'o'}; 

// vs char[] 
str = new char[5]; 
str[0] = 'H'; 
str[1] = 'e'; 
str[2] = 'l'; 
str[3] = 'l'; 
str[4] = 'o';
```

Eventually, you’ll need to isolate the concept of arrays from strings after students have transferred some of their knowledge. I like to use the challenge of copying arrays as a segue into more interesting topics like nested arrays and array lists.

### Teaching Through Real World Examples

While strings are a great tool for teaching arrays, we’re not really eliminating the problem of teaching arrays. After all, concepts like indexing have to be taught at some point. Enter: real world examples.

When teaching arrays, I like to draw parallels between concepts like paper lists and spreadsheets. With paper lists and spreadsheets, each item is usually assigned some number which we can relate to indices in an array.

As with many real world examples, the analogy usually breaks at some point. For instance, real world lists usually don’t have a limitation on how many items can be in them whereas arrays do.

As a result, I sometimes prefer to opt for a bookcase analogy. Each shelf is an array bound by the width of the shelf. Of course, books can be different sizes which breaks the fundamental definition of an array, but I find it can be a better analogy than a paper list.

Whatever analogy you choose, be aware of its limitations, and only use it as a way to bridge what your students already know with what they need to know.

## Visual Aids

Finally, let’s get to the good stuff! After all, when I teach, I like to draw a lot of pictures, so let’s look at a few visual aids for arrays.

### Memory Maps

One tool I’ve found useful over the last year is the memory map. If you’re not familiar with the idea, it’s basically an empty grid which you can use to demonstrate how objects might be stored in memory.

[![Memory Map Diagram](https://i0.wp.com/therenegadecoder.com/wp-content/uploads/2019/04/memory-map-diagram.png?resize=800%2C534&ssl=1)](https://therenegadecoder.com/?attachment_id=15777)

When you use a memory map for arrays, you can segment out a section of the memory map to demonstrate a contiguous block of memory. Then, you can fill various cells with numbers or characters to begin demonstrating the idea of arrays.

To me, the real power in memory maps is showing how pass-by-value works. In other words, you can show how a function might copy an array reference when passed as an argument.

### Stack and Heap

If you want to get into the nitty gritty details, you may want to consider introducing the concepts of stack and heap. You don’t necessarily need to explain the concepts in depth considering your students’ lack of array knowledge, but I find visualizing the two sections of memory to be very helpful.

[![Stack and Heap Diagram](https://i1.wp.com/therenegadecoder.com/wp-content/uploads/2019/04/stack-and-heap-diagram.png?resize=800%2C534&ssl=1)](https://therenegadecoder.com/?attachment_id=15780)

I like to draw a stack that just contains a call to the main method which creates an array. Then, I like to show that the address to the array gets stored on the stack while the array itself is placed in the heap. This usually further solidifies the idea of reference types.

### Arrays

Yeah, it may seem silly, but sometimes the best way to explain a concept is to draw it directly. There are a lot of ways to draw an array, but I use two different kinds of diagrams typically: one uses the array syntax while the other likes like a one-dimensional grid.

[![Array Diagram](https://i0.wp.com/therenegadecoder.com/wp-content/uploads/2019/04/array-diagram.png?resize=800%2C534&ssl=1)](https://therenegadecoder.com/?attachment_id=15781)

In either case, the idea should be clear. For instance, each cell has some index and stores some data. Then, you can use this visualization to demonstrate the various interactions you can have on an array like insertion and deletion.

In fact, I find the array visualization to be the best in terms of scalability. You can use it to show all sorts of actions like sorting, traversal, and population.

## Activities

While analogies and visual aids are great for introducing computer science material, it’s critical that you actually provide something for the students to do to reinforce their understanding.

### Labs

It’s typical for computer science curriculum to include a lab component where students explore a concept alongside the instructor. For arrays, that means running through tasks that force the student to interact with the data structure. Typical tasks might include:

- Initialization: create an array
- Population: fill the array with items
- Traversal: perform an operation on every item in the array
- Search: find an item in the array

Of course, there are more advanced tasks like:

- Sorting: rearrange the items in the array according to some order
- Copying: duplicate an array
- Nesting: explore multi-dimensional arrays

And, I’m sure there are plenty of other activities you can do in lab. Just pick a few of the topics above and find a way to make it interesting. For example, it might be fun to do a Caesar cipher with arrays. Ask students to load up an array with some characters then shift them by some offset. Here are a couple of labs I’ve seen in the wild:

- [Coin Changing](http://web.cse.ohio-state.edu/software/2221/web-sw1/extras/instructions/coin-change.html): use arrays to denote coin denominations for making change
- [Selection Sort](http://web.cse.ohio-state.edu/cse1223/sp2019/closedlabs/CSE1223ClosedLab09.html): sort an array of numbers

Ultimately, the goal in lab is to stimulate some reasoning about the topic. I usually like to employ the Socratic method in lab. Instead of answering questions directly, I’ll try to point the students in the right direction by asking them pointed questions. Of course, this can become a time crunch if you have a lab filled with 40 students like I did, so don’t be afraid to give away solutions.

### Games

A lot of people may find games a little unprofessional for adults, but I find they can be great for injecting some excitement into the classroom. If students are having fun with the material, you know you’re doing something right. Just make sure it’s authentic and not too gimmicky.

For instance, I once held a [jeopardy game](https://study-games.therenegadecoder.com/) for the class. Essentially, I had the students get into teams. Then, for each question, every group had 15 seconds to write their answer on the board. If the group got it, they got the points. The competitive nature of the game forced students to think quickly. As a result, when students clearly didn’t know an answer, I was able to pause and explain it.

Due to the nature of jeopardy, answers have to be short. Naturally, It can be difficult to come up with 25 interesting short answer questions just related to arrays, so you may want to seek other options. For instance, platforms like [Top Hat](https://tophat.com/) and [Kahoot!](https://kahoot.com/) are great for generating quiz-like games. Students join in with their smart phones or laptops and face a series of questions. Naturally, this can turn into a bit of a competitive game among your students who all want to be the first to share the right answer.

In terms of content, definitions of terms like arrays, traversal, and index are all great. In addition, you can share code snippets and ask students for the result (i.e. `list[i]`). Whatever you choose to do, the students will appreciate the break in lecture.

### Interactive Lessons

One thing I always try to do is make lectures interactive. Whether that means asking questions or organizing group projects, it doesn’t really matter. Interactivity is key here. An engaged class is a learning class, and that’s all the more important when working with challenging computer science topics.

Personally, I used Top Hat to periodically quiz students throughout class. This helped me gauge understanding without having to constantly ask “does that make sense?” For arrays, I might ask basic indexing questions to ensure students know that arrays start from zero (or whatever the convention is in your language of choice).

I also like to give students a break from lecture by giving them a coding problem to solve for a few minutes in groups. For example, I might ask the class to break up into groups and write a code snippet which can compute the average of the numbers in an array. After a few minutes, I’ll let the students share their work, and I might even share an example of my own. Ultimately, I like to push the idea that there are a lot of ways to solve the same problem.

## Homework

What you send your students home with is just as important as what you teach in class. Make sure you’re intentional with your homework assignments, and you’re not just creating busy work.

### Quizzes

A lot of classes I’ve been in have had some form of online quizzes to ensure students are keeping up with the work. I recommend keeping the point value low on quizzes, so students don’t feel pressured when they don’t understand something. After all, these quizzes are for you, the instructor, not the students. It’s your job to assess the growth of your students, and quizzes can be a nice way of accomplishing that.

In terms of array-related quizzes, I recommend covering high-level concepts only. For instance, it’s helpful to show code snippets and ask students to tell you what they do:

```python
x = [1, 4, 6] 
print(x[1]) # What does this print?
```

These sort of comprehension questions can help you gauge your students’ understanding of arrays.

In terms of format, you can easily issue quizzes outside class as homework. Alternatively, you may leverage quizzes as in class checkpoints. Either way, I think there is some value in tracking progress regularly.

### Projects

As with any well-rounded computer science curriculum, I think it’s a good idea to send your students home with a project or two. Ideally, projects should be harder than the material you go through in class and in lab. That way, students have a chance to really fight through problems on their own or in small teams.

When I took an intro programming class, we were asked to make a game. In particular, we made something similar to [Bejeweled](https://en.wikipedia.org/wiki/Bejeweled) where there is a grid of colors that you can match. The grid, of course, is made of a set of nested button arrays which relate to columns and rows of the game board. Naturally, there are a lot of these kinds of grid-based games. For instance, you might ask students to implement a simple version of [2048](https://en.wikipedia.org/wiki/2048_(video_game)) or even the [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).

If games seem too challenging, you can always opt for any number of array manipulation projects: sorting, searching, etc. Alternatively, you could go the data science route. For instance, you could ask students to fill an array with numbers and perform statistics computations on the collection: max, min, average, standard deviation, median, mode, etc.

Depending on your students’ experience level, you may want to provide them with a template of methods to fill out. Alternatively, you could provide an API and ask the students to reproduce the functionality in code.

In either case, be careful with your deadlines. In my opinion, students should be given a couple weeks to complete projects. The extra time should make them feel less rushed, so you get better results. Also, longer timelines forces students to focus on their time management skills. Most students will wait until the last minute anyway, but people like me will appreciate the breathing room.

### Problem Sets

While quizzes are great for checkups and projects are great for practice, problem sets are great for theory. In other words, create problem sets when you want students to stretch their understanding.

In terms of arrays, problem sets should include questions that push the boundaries on what students already know. For instance, it might be interesting to ask students how they would implement an array list without telling them about array lists. This forces students to think about how to handle the case where an array is at capacity and a user tries to add another element. It also gets them to touch on topics like copying.

Alternatively, problem sets can be used to reinforce jargon. I wouldn’t necessarily have students copy and paste definitions, but it may be helpful to have them give definitions in their own words. For example, you could have them explain to you what an array is and how it is used.

Personally, I like compare and contrast questions the most. Unfortunately, students are probably being exposed to data structures for the first time, so arrays stand alone. However, it may be a good opportunity to ask about the differences between primitive types and reference types (language-dependent of course).

As students get deeper in their computer science curriculum, I find that professors tend to go the problem set route since topics are more theoretical. Regardless, problem sets can be a good chance for students to really explain their thought process.

## Feedback

As always, I’m aware I’m not the only computer science educator in the world. If you’ve taught arrays in the past, what are some of your favorite ways of conveying the material? Feel free to share your thoughts.

Otherwise, thanks for stopping by! I appreciate the support, and [I hope you’ll continue to stick around.](https://therenegadecoder.com/members/)