Lesson 12 Arrays 2007.11.7. 2 Objectives: About the Fibonacci sequence One-Dimensional Arrays Array...

37
Lesson 12 Arrays 2007.11.7

Transcript of Lesson 12 Arrays 2007.11.7. 2 Objectives: About the Fibonacci sequence One-Dimensional Arrays Array...

Lesson 12 Arrays

2007.11.7

2

Objectives:• About the Fibonacci sequence• One-Dimensional Arrays• Array Initialization• Arrays as Function Arguments• Case Study: Computing Averages and Standard

Deviations• Two-Dimensional Arrays

3

Fibonacci Numbers One pair rabbit give birth

to a new pair baby rabbits each year

The baby rabbits need to wait one year to bear new baby

fn+1 = fn + fn-1

f0 = 1

f1 = 1

4

Fibonacci Numbers in Nature

1

2

3

5

8

13

21

5

Compute the Fibonacci numbers recursively

int fib(int n) { if (n <= 2) return 1; else return fib(n-1) + fib(n-2); }

6

Time complexity of the recursive algorithm

fib(5)

fib(3) fib(4)

+ The growth rate of

the computing time with the problem size

fib(1) fib(2)

+

fib(0) fib(1)

+

fib(2) fib(3)

+

fib(1) fib(2)

+

…exponential

7

Use iterative algorithm

Liner complexityO(n)

8

Use the Golden Ratio: (1+ sqr(5))/2

F(n) = round (

pow (1+sqr(5)) / 2, n) / sqr(5)

)

9

By recursive powering

formula for multiplying two symmetric 2x2 matrices:

[ F(n+1) + F(n) F(n) + F(n-1) ] [ F(n +1 ) F(n) ]

[ F(n+2) F(n+1)] [ F(n+1) F(n) ]

10

By recursive powering (cont.)

[ 1 1] [ 1 0]

n

[ 1 1] [ 1 0]

n/2 [ 1 1] [ 1 0]

n/2

*

+[ 1 1] [ 1 0]

logn

11

Arrays: Introduction

Atomic variable: variable whose value cannot be further subdivided into a built-in data type

Aggregate data type: data type with two main characteristics Its values can be decomposed into individual data elements,

each of which is either atomic or another Aggregate data type It provides an access scheme for locating individual data

elements within the data structure

12

Name + space + access scheme

00611001

00611002

00611003

00611004

00611005

00611006

00611007

00611008

00611009

00611010

00611011

刘栩佳樊怡张昊严霄李伟强叶翔蔡浩李鑫李彬彬安马太宫照恒

uid list name list

Arrays: Introduction

13

Arrays A set of data items with same type Stored in consecutive memory

Fixed in size throughout program

—— not dynamic

index

Arrays: Introduction

14

Create a one-dimensional array

#define NUMELS 5

int grades[NUMELS];

Const expression

15

To access an element Format: arrayname[ index value ]

First element at position 0positionoffsetdeviation

grades[3]

One-Dimensional Arrays

16

Use a subscripted variable Subscripted variables can be used anywhere

scalar variables are valid grades[0] = 98; grades[1] = grades[0] - 11;

Any expression that evaluates an integer may be used as a subscript#define NUMELS 5total = 0;for (i = 0; i < NUMELS; i++) total = total + grades[i];

17

Input and Output of Array Values Array elements can be assigned values by:

using assignment statements interactively, using the scanf() function

#define NUMELS 5for(i = 0; i < NUMELS; i++){ printf("Enter a grade: "); scanf("%d", &grades[i]);}

Be careful: C does not check the value of the index being used

18

Sample output:Enter a grade: 85Enter a grade: 90Enter a grade: 78Enter a grade: 75Enter a grade: 92grades 0 is 85grades 1 is 90grades 2 is 78grades 3 is 75grades 4 is 92

Input and Output of Array Values

From temporal sequenceTo spatial sequence

Nextround

Nextelement

19

Input and Output of Array Values

20

Array Initialization Examples of initializations:

int grades[5] = {98, 87, 92, 79, 85};

double length[7] = {8.8, 6.4, 4.9};

char codes[5]= {‘h', ‘e', ‘l', ‘l', ‘o'};

char codes[] = {‘h', ‘e', ‘l', ‘l', ‘o'};

char codes[] = "sample"; /* size is 7 */

21

Passing an array to a function

By reference Via pointer (left behind)

22

Pass array by reference

23

Pass array by reference

24

Find MAX:

write proof inside the function

25

Case Study: Computing Averages and Standard Deviations

n-1

Average = ∑ a[ i ] n

i =0

Standard deviation = √ ∑(a[ i ] – Ave)2 / n

26

Requirements Specification

Need two functions Determine the average… Determine the standard deviation…

…of a list of integer numbers Each function must accept the numbers as an array and

return the calculated values to the calling function We now apply the top-down development procedure to

developing the required functions

27

Analyze the Problem

Array of data Main control function

Find the average

ave

Find the average

avestd

double findAvg( int [] ); double stdDev( int [], double)

?

28

Select an Overall Solution

Problem-Solver Algorithm is adapted: Initialize an array of integersCall the average functionCall the standard deviation functionDisplay the returned value of the average

functionDisplay the returned value of the standard

deviation function

29

Computing Averages and Standard Deviations

30

Computing Averages and Standard Deviations

31

Two-Dimensional Arrays A two-dimensional array, or table, consists of

both rows and columns of elements Can be treated as array of arrays

int ar[3][4];

32

Two-Dimensional Arrays (continued)

Initialization:#define NUMROWS 3#define NUMCOLS 4int val[NUMROWS][NUMCOLS] = { {8,16,9,52}, {3,15,27,6}, {14,25,2,10} };

The inner braces can be omitted:int val[NUMROWS][NUMCOLS] = {8,16,9,52,3,15,27, 6,14,25,2,10};

Initialization is done in row order

33

Two-Dimensional Arrays (continued)

34

Two-Dimensional Arrays (exp)

35

Common Programming Errors Forgetting to declare the array Using a subscript that references a nonexistent

array element Not using a large enough conditional value in a for loop counter to cycle through all the array elements

Forgetting to initialize the array

36

Summary

A single-dimensional array is a data structure that can store a list of values of the same data type

Elements are stored in contiguous locations Referenced using the array name and a subscript

Single-dimensional arrays may be initialized when they are declared

Single-dimensional arrays are passed to a function by passing the name of the array as an argument

37

homework : Program exercise:

8.2 4; 8.3 5; 8.4 11a

Due time: 12/Nov.