COMP1511

Static arrays

Week 3 Lecture 2

functions/procedures recap

  • Reusable blocks of code
  • Callable multiple times
  • variables within a function are scoped to that function

PI function

Would be annoying to write this every time we need to calculate!

Forward declaration

^ problem! main doesn't know that pi exists yet!

Forward declaration

^ Solved! We forward declared pi!

Quick functions recap demo

Arrays

So far, we can store a single item in each variable

What if you wanted to store many values?

Number of ice creams eaten

Seem repetitive?

  • Many variables would clutter the program
  • Many variables would not always be efficient

Data structures

  • Are common structures (not structs) used to store multiples of data
    • Usually (especially in COMP1511) of the same data type
  • Can scale, easily storing a handful, up to thousands, or more elements of data!

Data structures in COMP1511

We will look primarily at two data structures:

  • arrays (today)
  • linked lists (future)

    These are very, very powerful data structures you will use forever

Arrays

  • A collection of data, all of the same type. (homogonous)
  • We have a single identifier for the entire array
  • It is a random access data structure, meaning we can access any element in the array at any time

Arrays

  • We can ready or modify individual elements
  • It is a contiguous data structure

contigu-what?

Let's visualise arrays

Static arrays have a set size

(which you specify)

int array

  • This int array will store 5 integers
  • 32bit * 5 elements = 160 bits of memory used

The array declaration syntax

int ice_cream_per_day[7];

Declare + initialise

^ Note you can only do this when you declare, not later!

^ Will initialise all elements to 0

Creates:

Accessing elements

Writing elements

arrays 🤝 loops

The power of arrays

^ Does this look repetitive?

If only we had a way to count :(

Bad

Good

Demo

Lecture Feedback