Jump to content

Programming Fundamentals/Arrays/Dynamic Arrays

From Wikiversity

A dynamic array is a random access, variable-size list data structure that allows elements to be added or removed.[1] This activity introduces dynamic arrays. This activity will help you understand how to use dynamic arrays in a program.

Objectives

[edit | edit source]
  • Understand dynamic array concepts
  • Understand how dynamic array elements are added in a program.
  • Use a for loop to assign and display array values.

Prerequisites

[edit | edit source]

Learners should already be familiar with fixed-length arrays and the syntax for using dynamic arrays in their preferred programming language.

Introduction

[edit | edit source]

Review the following pseudocode.

Declare Integer values[]
Declare Integer value

For index = 0 To 2
    Output "Enter value " + (index + 1) + ":"
    Input value
    values.add(value)
End For

For index = 0 To 2
    Output values[index]
End For

Questions

[edit | edit source]
  • What syntax is used to define dynamic arrays in your preferred programming language?
  • What syntax is used to add dynamic array elements in your preferred programming language?

Activity

[edit | edit source]

With a partner, use Repl.it or your preferred integrated development environment (IDE) to create a program based on the pseudocode above.

  1. Start by declaring an empty dynamic array.
  2. Create a for loop to input three values into the array.
  3. Create a for loop to display the array values.
  4. Save the program.
  5. Test the program to verify that it works correctly.
  6. Trade places, so that both partners have an opportunity to "drive" the programming environment.
  7. Modify the program to increase the number of values in the array.
  8. Modify the program to decrease the number of values in the array.
  9. Experiment with using the wrong starting or ending index values in the for loop (For example, 1 to 3 rather than 0 to 2).
  10. Working together, create a list of changes that might be made to use dynamic arrays in programs you've already written. What parts could be replaced with a dynamic array? When should a dynamic array be used rather than a fixed-length array?

Applications

[edit | edit source]
  • Identify specific steps which must be followed when creating a program using dynamic arrays.
  • Discuss your activity experience with your classmates. What surprised you? What have you learned that you can apply to your own school or work environment?

References

[edit | edit source]