Lecture 5

Fall 2018

Narges Norouzi

Recap

  • break & continue keywords
  • 1-D arrays
  • 2-D arrays - more to come today

Multi-dimensional Arrays

2D array or Array of Arrays

Demo

Matrix Addition

Rows by columns or columns by rows

  • Consider int[][] m = new int[3][4];

  • Is that 3 rows by 4 columns or 3 columns by 4 rows?

  • The answer is that it can be either

    • As long as you are consistent with your column/row placement

Rows by columns or columns by rows

  • This makes it 3 columns by 4 rows

 

 

 

 

  • This makes it 3 rows by 4 columns

 

 

 

Jagged Array

Jagged Array

Explicit Initialization

Methods

Methods

  • A method is like a machine

  • Zero or more inputs

  • Zero or one output

  • Other names:

    • Function

    • Procedure

Applications

  • Scientists use mathematical functions to calculate formulas.

  • Programmers use functions to build modular programs.

Example

Example

Example

Example

Example

Example

Example

Flow of control

flow of control

  • What happens when a function is called:

  1. Control transfers to the function code.

  2. Argument variables are assigned the values given in the call.

  3. Function code is executed.

  4. Return value is assigned in place of the function

    name in calling code.

  5. Control transfers back to the calling code. This is known as "pass by value”.

break

Scope

  • Scope (of a variable):

    • The code that can refer to that variable.

Example

Memory management in stack

 

  • What happens in memory when we call functions?

 

  • What happens in memory when we define variables?

Zybooks chapters we covered

  • Chapter 5 section 5.9
  • Chapter 6:
    • section 6.1
    • section 6.2
    • section 6.3
    • section 6.4
    • section 6.6
    • section 6.7

Copy of CMPS12A - Lecture 5

By Narges Norouzi

Copy of CMPS12A - Lecture 5

  • 52