arrays chap 8. 2 without array if you want to create lottery winning numbers you need 7 variables (6...

40
Arrays Chap 8

Upload: marjory-felicity-melton

Post on 19-Jan-2018

220 views

Category:

Documents


0 download

DESCRIPTION

3 Without Array Same things happen when you want to… –Store grades of the whole class –Store data of members –… We need to define a group of variables with the same meaning ALL AT ONCE !

TRANSCRIPT

Page 1: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

Arrays

Chap 8

Page 2: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

2

Without Array• If you want to create Lottery winning

numbers…– You need 7 variables (6 for winning numbers

and 1 for the special number)– Every time you choose a winning number, you

have to check if it has been chosen.

– Um… Program becomes ugly!

Page 3: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

3

Without Array• Same things happen when you want to…

– Store grades of the whole class– Store data of members– …

• We need to define a group of variables with the same meaning ALL AT ONCE!

Page 4: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

4

The Idea of Using an Array

a1 a2 a3 a4 a5 a6a[ ]

a[0] a[1] a[2] a[3] a[4] a[5]

Page 5: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

5

Array ( 陣列 )• To define a group of variables with the sa

me meaning at once• Syntax to define an array:dataType arrayName[arraySize];Ex: int students[6]; // 班級學生人數

6 rooms for this array

students

Each element in this array is of type int32 35 31 34 32 33

6 classes

Page 6: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

6

Accessing Array ( 存取陣列資料 )

Its subscript starts from 0. Referring to an element

Ex: students[4]The element 4 of the array studentsThe 5th element of the array students

students

students[0]students[1]

students[2]students[3]

students[4]students[5]

Page 7: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

7

怪 怪 怪 怪 怪

Accessing Array ( 存取陣列資料 )

Every students[i] is of type int• students[0]=32; // assign value• students[2]=students[0]-1;// read value

怪students

students[0]students[1]

students[2]students[3]

students[4]students[5]

32 31

Page 8: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

8

怪 怪 怪 怪 怪

Accessing Array ( 存取陣列資料 )

• printf("%d", students[2]);// It prints out 31• scanf("%d", &(students[5]));// If 33 is given• students[5]++;

怪students

students[0]students[1]

students[2]students[3]

students[4]students[5]

32 31 3334

Page 9: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

9

Typical Array Operations• Idioms of typical operations on an array a of

length N:for (i = 0; i < N; i++) a[i] = 0; /* clears a */for (i = 0; i < N; i++) /* reads data */ scanf("%d", &a[i]); /* into a */for (i = 0; i < N; i++) sum += a[i]; /* sums the elements of a */

Page 10: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

10

Example• Define an integer array of size 100 and

set every element as 0.• Set the value of each element as its subsc

ript.• Set the value of each element as the squa

re of its subscript.

Page 11: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

11

Example• Define a 70-element integer array score.• Input the scores of 70 students.• Print out the scores of 70 students.

Page 12: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

12

Subscripts• A subscript can be an integer,

or an integer expression.– students[ 3 ]– students[ i ]– students[ i+1 ]– students[ i+j ]– students[ myFunc( ) ]– students[ sorted[ i ] ]

Page 13: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

13

Array Initialization• You can give initial values when defining.int days[6]={31,28,31,30,31,30};• If no sufficient values are given, the values

of rest elements will be set to be 0.int days[6]={31,28};// initial value of days is {31,28,0,0,0,0}

• So, if you want an all-0 array:int days[6]={0};// initial value of days is {0,0,0,0,0,0}

Page 14: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

14

Array Initialization• If the array size is not given, its size will be

the number of elements in the initializer list.

int days[]={31,28,31,30,31,30};will create a 6-element array.

Page 15: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

15

Program: Checking a Number for Repeated Digits• After the user enters a number, the

program prints either "Repeated digit" or "No repeated digit":Enter a number: 28212Repeated digit

• The number 28212 has a repeated digit (2); a number like 9357 doesn’t.

Page 16: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

16

repdigit.cint main(){ int digit_seen[10] = {0}; int n; int digit; printf("Enter a number: "); scanf("%d", &n); while (n > 0) { digit = n % 10; if (digit_seen[digit]) break; digit_seen[digit] = 1; n /= 10; } if (n > 0) printf("Repeated digit\n"); else printf("No repeated digit\n"); return 0;}

Page 17: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

17

repdigit.cint main(void){ bool digit_seen[10] = {false}; long n; int digit; printf("Enter a number: "); scanf("%ld", &n); while (n > 0) { digit = n % 10; if (digit_seen[digit]) break; digit_seen[digit] = true; n /= 10; } if (n > 0) printf("Repeated digit\n"); else printf("No repeated digit\n"); return 0;}

Page 18: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

18

Example• Check if a date month 月 day 日 is valid.

int month;int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};printf(" 請以 月 / 日 的格式輸入日期: ");scanf("%d/%d", &month, &day);if ( month < 1 || month > 12 ) printf(" 不合法的日期。 \n");else if ( day < 1 || day > days[month-1] ) printf(" 不合法的日期。 \n");

month ??

day ??

Page 19: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

19

Operator sizeof()• sizeof(z) returns the memory size (in byte

s) required for this variable z.– int a; char b;– sizeof(a) → 4– sizeof(b) → 1

• Or, of data types– sizeof(unsigned short int) → 2– sizeof(bool) → 1

Page 20: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

20

Operator sizeof()• So, for an array a, sizeof(a) returns the me

mory size (in bytes) required for this array a.int a[10]; sizeof(a) → 40char b[10]; sizeof(b) → 10

• sizeof(arrayName)/sizeof(array_element0):gives the number of elements in an arrayint a[10];sizeof(a)/sizeof(a[0]) → 10

Page 21: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

21

Array Size vs. Number of DataEx: int scores[100]; // 學生成績• It defines a 100-element array in advance t

o store scores of students.• But in fact, the actual number of students i

s still unknown.• You need to define an integer variable to s

tore the number of students.

Page 22: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

22

Practice• Ask the user to input the scores (-1 for

termination) and save them in an array.– Print out all the scores.

Page 23: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

23

More about Array Index• Example: to calculate the statistics of stud

ents' scores– 90~99 ### 人– 80~89 ### 人– 70~79 ### 人– 60~69 ### 人– …

• Given score[i] → number[??]++;

• int score[100];• int number[10];

number[0]: 0~9 人數number[1]: 10~19 人數number[2]: 20~29 人數…

number[score[i]/10]++;

Page 24: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

24

More about Array Index• Example: to calculate the statistics of stud

ents' scores– 91~100 ### 人– 81~90 ### 人– 71~80 ### 人– 61~70 ### 人– …

• Given score[i] → number[??]++;

• int score[100];• int number[10];

number[0]: 1~10 人數number[1]: 11~20 人數number[2]: 21~30 人數…

number[(score[i]-1)/10]++;

Page 25: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

25

Practice in Array Index• 計算成績分布

– 0~14 ### 人– 15~29 ### 人– 30~44 ### 人– 45~59 ### 人– …

• score[i]: ?? → number[??]++;

• int score[100];• int number[10];

– number[0]: 0~14 人數– number[1]: 15~29 人數– …

Page 26: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

26

Practice• Calculate the statistics of students' scores

and graph it with histograms.範圍 人數 圖表90~99 5 *****80~89 12 ************70~79 18 ******************60~69 9 *********…

Page 27: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

27

0 1 … 38 390 …1 …2 …3 …4 …5 …

2-Dimensional ArraydataType arrayName[size1][size2];Ex. int grade[6][40]; // 各班級所有學生的成績

grade

grade[3][1]=73;grade[0][38]=98;

代表班級代表學生座號

73

98 →→→→row

↓ ↓ ↓ ↓ ↓column

Page 28: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

28

N-Dimensional ArraydataType arrayName[size1][size2]…[sizeN];Ex. int grade[6][3][40]; // 成績 [班級 ][科目 ][ 座號 ]

• To save the English score of the 23th student in the 1st class, you should doscanf("%d",&score[ 0 ][ 1 ][22]);

代表班級代表科目 { 國文 , 英文 , 數學 }

代表學生座號

? ? ?

Page 29: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

29

Practice• 印出所有學生各科成績:

1 年 1 班 1 號同學國文 98 分1 年 1 班 1 號同學英文 95 分1 年 1 班 1 號同學數學 92 分1 年 1 班 2 號同學國文 89 分1 年 1 班 2 號同學英文 78 分…2 年 3 班 5 號同學數學 97 分

Page 30: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

30

Practice• Calculate the average Math scores among

the 1st year students.• Calculate the mean of total scores in 二年一班 .• Calculate the average English scores of e

ach 3rd-year class.

Page 31: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

31

Ex: Prepare an Identity Matrix• A pair of nested for loops is perfect:

#define N 10 double ident[N][N];int row, col; for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (row == col) ident[row][col] = 1.0; else ident[row][col] = 0.0;

100

010001

Page 32: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

32

Array Initialization• Example:int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 1, 0, 0, 1, 0}, {1, 1, 0, 1, 0, 0, 0, 1, 0}, {1, 1, 0, 1, 0, 0, 1, 1, 1}};

Page 33: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

33

Array Initialization• If an initializer isn’t large enough to fill a m

ultidimensional array, the remaining elements are given the value 0.

int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 1, 0, 0, 1, 0}};// the last two rows will contain zeros

Page 34: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

34

Array Initialization• If an initializer isn’t large enough to fill a multidim

ensional array, the remaining elements are given the value 0.int m[5][9] = {{1, 1, 1, 1, 1, 0, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1}, {0, 1, 0, 1, 1, 0, 0, 1}, {1, 1, 0, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 0, 0, 1, 1, 1}};

// m[1][8], m[2][8], and m[3][8] will contain zeros

Page 35: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

35

Array Initialization• We can even omit the inner braces :int m[5][9] = {1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1};

– It is risky, since an extra element (or even worse, a missing element) will affect the rest of the initializer

Page 36: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

36

Example• Chinese numbers

Page 37: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

37

Array of Strings• char * subject[3]={ " 國文 ", " 英文 ", " 數學 "};• printf("%s", subject[1]);• PS. More about strings will be introduced l

ater in Chapter 8.

Page 38: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

38

Random Number GeneratorTo get a random number ( 亂數 ):• Add #include <stdlib.h>• Add #include <time.h>• Add a line in the beginning of main(): srand( (unsigned)time(NULL) );

Page 39: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

39

Random Number GeneratorTo get a random number ( 亂數 ):• Use rand() to get a random number.

– The value is between 0 and RAND_MAX.– For a random number between 0~7, use rand()%8

– For a random number between 1~8, use rand()%8+1 , and so on.

Page 40: Arrays Chap 8. 2 Without Array If you want to create Lottery winning numbers You need 7 variables (6 for winning numbers and 1 for the special number)

40

Practice• Write a program to simulate rolling a dice f

or 1000 times. Print out how many times each value has occurred.

1 occurs 169 times2 occurs 143 times3 occurs 179 times4 occurs 167 times5 occurs 180 times6 occurs 162 times