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)

Slides:



Advertisements
Similar presentations
南投縣社區大學 Excel 實務應用入門 講師 : 林泉成
Advertisements

Introduction to Java Programming Lecture 10 Array I Declaring, Creating, and Initializing Arrays.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
Chapter 8 Arrays and Strings
CS 106 Introduction to Computer Science I 02 / 19 / 2007 Instructor: Michael Eckmann.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
A First Book of ANSI C Fourth Edition
Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Computer programming Lecture 5. Lecture 5: Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character arrays.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
CHAPTER: 12. Array is a collection of variables of the same data type that are referenced by a common name. An Array of 10 Elements of type double.
Flow of Control Part 1: Selection
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
A Quick Start of C Introduction. 2 Terminology Program 程式 Programming language 程式語言 Code 程式碼 Compiler 編譯器 –cc, GNU gcc, g++,… –IDE: MS Visual C++, Dev.
1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C arrays ❏ To be able to pass arrays and array elements to functions.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
WEEK 6 Class Activities Lecturer’s slides.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
COP 3275: Chapter 08 Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA.
ICS103 Programming in C Lecture 11: Arrays I
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
UNIT 10 Multidimensional Arrays.
+ Arrays & Random number generator. + Introduction In addition to arrays and structures, C supports creation and manipulation of the following data structures:
Arrays.
Computer Programming for Engineers
Chapter 8: Arrays Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Move the first element to the.
2D-Array 二維陣列 1 *****0 ***** 1 ***** 2 ***** 3 ***** 4 ***** 5 ***** 6 ***** 7 ***** 8 ***** 0 1 * 2 ** 3 *** 4 **** 5 ***** 6 ****** 7 ******* 8 ********
8. ARRAYS. Aggregate variables Scalar variables –Single value Aggregate variables –Collection of values –Arrays: elements have the same type.
 Pearson Education, Inc. All rights reserved Passing Arrays to Methods To pass array argument to a method – Specify array name without.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Arrays What is an array… –A data structure that holds a set of homogenous elements (of the same type) –Associate a set of numbers with a single variable.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
 2005 Pearson Education, Inc. All rights reserved Arrays.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
© 2016 Pearson Education, Ltd. All rights reserved.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays An Array is an ordered collection of variables
CNG 140 C Programming (Lecture set 8)
int [] scores = new int [10];
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Chapter 7 Arrays PROGRAMMING IN ANSI C.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Arrays I Handling lists of data.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

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) –Every time you choose a winning number, you have to check if it has been chosen. –Um… Program becomes ugly!

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 !

4 The Idea of Using an Array a1a2a3a4a5a6 a[ ] a[0] a[1] a[2] a[3] a[4] a[5]

5 Array ( 陣列 ) To define a group of variables with the same 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 int classes

6 Accessing Array ( 存取陣列資料 )  Its subscript starts from 0.  Referring to an element Ex: students[4]  The element 4 of the array students  The 5th element of the array students students students[0] students[1] students[2] students[3] students[4] students[5]

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] 3231

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]

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 */

10 Example Define an integer array of size 100 and set every element as 0. Set the value of each element as its subscript. Set the value of each element as the square of its subscript.

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

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 ] ]

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}

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.

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: Repeated digit The number has a repeated digit (2); a number like 9357 doesn’t.

16 repdigit.c int 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; }

17 repdigit.c int 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; }

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 12 ) printf(" 不合法的日期。 \n"); else if ( day days[month-1] ) printf(" 不合法的日期。 \n"); month ?? day ??

19 Operator sizeof() sizeof(z) returns the memory size (in bytes) 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

20 Operator sizeof() So, for an array a, sizeof(a) returns the memory size (in bytes) required for this array a.  int a[10]; sizeof(a) → 40  char b[10]; sizeof(b) → 10 sizeof(arrayName)/sizeof(array_element0): gives the number of elements in an array  int a[10];  sizeof(a)/sizeof(a[0]) → 10

21 Array Size vs. Number of Data Ex: int scores[100]; // 學生成績 It defines a 100-element array in advance to store scores of students. But in fact, the actual number of students is still unknown. You need to define an integer variable to store the number of students.

22 Practice Ask the user to input the scores (-1 for termination) and save them in an array. –Print out all the scores.

23 More about Array Index Example: to calculate the statistics of students' 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]++;

24 More about Array Index Example: to calculate the statistics of students' 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]++;

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 人數 –…

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 ********* …

27 2-Dimensional Array dataType arrayName[size1][size2]; Ex. int grade[6][40]; // 各班級所有學生的成績 grade grade[3][1]=73; grade[0][38]=98; 代表班級 代表學生座號 → row ↓↓↓↓↓ column

28 N-Dimensional Array dataType 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 do scanf("%d",&score[ 0 ][ 1 ][22]); 代表班級 代表科目 { 國文, 英文, 數學 } 代表學生座號 ???

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 分

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 each 3rd-year class.

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;

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}};

33 Array Initialization If an initializer isn’t large enough to fill a multidimensional 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

34 Array Initialization If an initializer isn’t large enough to fill a multidimensional 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

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

36 Example Chinese numbers

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

38 Random Number Generator To get a random number ( 亂數 ): Add #include Add a line in the beginning of main() : srand( (unsigned)time(NULL) );

39 Random Number Generator To 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.

40 Practice Write a program to simulate rolling a dice for 1000 times. Print out how many times each value has occurred. 1 occurs 169 times 2 occurs 143 times 3 occurs 179 times 4 occurs 167 times 5 occurs 180 times 6 occurs 162 times