Week 2 Lecture 2

Custom Data Types

Last lecture

  • Control flow
  • conditions
  • if/else if/else
  • while loops
  • scans

Today

  • Nested loops
  • Custom data types

if statements recap

  • A condition is a true/false value (1/0)
  • We can execute an expression to calculate the condition
    • my_age > drinking_age -> will evaluate to true/1 if age is greater than drinking_age
  • Conditions are useful in many places, if statements, while loops, etc.

While loops

while(<condition>) {
    do_something_over_and_over();
}
  • if true, run the body
  • at end of body, check condition again
  • if true, run the body...

Nested loops

  • Simply having a while loop within a while loop
  • Each time the outer loop runs, the inner loop runs an entire set (the inner loop runs a lot)

Why are nested loops useful?

Why are nested loops useful?

How can we print something like this?

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

What about a half-pyramid?

1
12
123
1234
12345

Custom Data Types

Custom data types

  • So far, we have used built-in C data types (int, char, double)
  • These store a single item of that type
  • What if we want to store a group of related data?

^ These three things are related...

We can define our own data types (structures) to store a collection of types

Enter the struct

UNSW_student struct

To use, we simply say:

struct UNSW_student Jake;

struct (structures)

  • Are variables made up of other variable(s)
  • They have a single identifier
  • Can still access the sub-variables

Defining a struct

Example

Defining a struct

Example

^ Notice, no values... we are only defining.

Full program example

But how do I access the actual data...

the . operator

DEMO

Another custom data type

The enum

Imagine I wanted to store days of the week

The problem

  • Have to remember that 1 is Monday
  • Could accidentally set 8 to day_of_week

Enums (the solution)

  • Store a range or set of possible values
  • Assigns a more meaningful name to state

Syntax

Example

Using enums

Under the hood

Advantages over other approaches

  • We provide limitations on the possible values (has to be defined in the enum)
  • We give a nice label to values (Sat)
    • We don't have to remember that 1 is Monday (or was it 0? 🤔)
  • Could use #define but these can clutter our code if we have many

struct 🤝 enum

Feedback