Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structured Programming Instructor: Prof. K. T. Tsang Lecture 6: Arrays 数据序列, 数组 1.

Similar presentations


Presentation on theme: "Structured Programming Instructor: Prof. K. T. Tsang Lecture 6: Arrays 数据序列, 数组 1."— Presentation transcript:

1 Structured Programming Instructor: Prof. K. T. Tsang Lecture 6: Arrays 数据序列, 数组 1

2 Arrays (p.22 K&R) 数据序列, 数组 An array is a collection of data elements that are of the same type (e.g., a collection of integers, characters, doubles). Array provide a convenient vehicle to hold a collection, and to reference its individual elements. We need to know the maximum number of elements the array can hold before declaring it. 2

3 Declaration of Arrays An array is a compound type that consists of a type, an identifier, and a dimension. int test_scores[40] Type Identifier Dimension, must be a constant. 3

4 How Array is stored in memory? When an array is declared, a block of memory is reserved so that they are stored one after another. Example: int A[5](4-bytes each) 100………… Memory address:1024… 1020 A[1]A[2]A[3]A[4]A[0] 102810361032 4

5 Array Applications Given a list of test scores, determine the maximum and minimum scores. Read in a list of student names and rearrange them in alphabetical order (sorting). Given the height measurements of students in a class, output the names of those students who are taller than average. 5

6 Arrays - example #define MAXLINE 1000 /*define for C preprocessor*/ const int MaxStudents = 100; int number_of_students = 100; const int array_size = 3; char name[99];/*ok*/ char line[MAXLINE];/*ok*/ int student_ID[MaxStudents];/*ok*/ int ia[array_size] = { 2, 8, 19 };/*ok, explicitly initialized*/ int ib[ ] = { 3, 5, 8 };/*ok, an array of dimension 3*/ int test_scores[number_of_students]/*error, dimension not a constant*/ 6

7 Subscript Suppose int A[10]; // array of 10 ints To access an individual element we must apply a subscript to list name A –A subscript is a bracketed expression The expression in the brackets is known as the index –First element of list has index 0 A[0] –Second element of list has index 1, and so on A[1] –Last element has an index one less than the size of the list A[9] Incorrect indexing is a common error 7

8 Accessing individual Array elements int digit[8]; /*define an array with 8 integers*/ digit[0] = 9; /*initialize individual array elements*/ digit[1] = 8; /*array index starts at 0*/ digit[2] = 6; digit[3] = 5; digit[4] = 4; digit[5] = 3; digit[6] = 2; digit[7] = 1; int sum =0; for (int i=0; i<8; i++) { //i is a local variable digit[i] = i + 2; sum = sum + digit[i]; } 8

9 Example: loops & array const int MaxSize = 10000; int A[MaxSize]; int n = 0, CurrentInput, i; while (n< MaxSize && scanf(“%d\n”, &CurrentInput)==1) { A[n] = CurrentInput; n++; } printf(“Total number of input data is\n”); for (i=0; i<n; i++) printf(“%d ”, A[i]); printf(“\n”); int SmallestValueSoFar = A[0]; for (i=1; i<n; i++) if (A[i] < SmallestValueSoFar) SmallestValueSoFar = A[i]; printf(“The smallest is %d\n”, SmallestValueSoFar); 9

10 Character arrays ( string 字串, 字符串 ) (p.28 K&R) C-style string always terminated with the null character. char name[7]; name[0]=‘H’; name[1]=‘e’; name[2]=‘l’; name[3]=‘e’; name[4]=‘n’; name[5]=‘\n’; name[6]=‘\0’;/*always ends with null character*/ char ch1[ ] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’ };/*ok*/ char ch2[ ] = “ world”;/*ok*/ ch1 = ch2 ;/*error, cannot assign one character array to another*/ 10

11 C-style string char ca[] = { ‘C’, ‘+’, ‘+’ };//no null, not C-style string char ca1[] = { ‘C’, ‘+’, ‘+’, ‘\0’ };//with null, C-style string char ca2[] = “C++”;//null terminator added automatically To assign one character array to another, use library function strcpy #include (void)strcpy(name, “Helen\n”); printf(“Hi, my name is %s”, name); 11

12 String copy: example code #include void str_copy(char s1[ ], char s2[ ]); int main() { char s2[ ] = “This is a string!"; char s4[99]; str_copy(s4, s2); printf("s4 %s\n“, s4); return 0; } void str_copy(char s1[], char s2[]) { int i = 0; while (s2[i] != '\0') { s1[i] = s2[i]; ++i; } s1[i] = '\0'; return; } 12

13 String library functions contained in string.h Copy string2 to string1: strcpy(string1, string2); Concatenate s2 to s1: strcat(s1, s2) Get the length of a string: len = strlen(s1) Compare 2 strings, 0 if equal, otherwise nonzero: strcmp(s1, s2) Important: The array used in the first argument of strcpy and strcat must be large enough to hold the generated string. 13

14 Example: String library functions #include char first[100], last[100], full_name[200]; int main() { strcpy(first, “Mary”); strcpy(last, “Wang”); strcat(full_name, first); strcat(full_name, “ “); strcat(full_name, last); printf(“Hello, my full name is %s\n”, full_name); return 0; } 14

15 String I/O #include /*for gets & puts*/ int main() { char message[200]; /*set enough storage for message*/ printf (“Please enter a message\n”); gets (message); /*input string from keyboard*/ printf (“The string just entered is:\n”); puts (message); /*displaying string on screen*/ return 0; } 15

16 Gets & puts gets(str) Characters\n Characters\0 str[ ] puts(str) Characters\0 str[ ] Characters\n (From keyboard) (To screen) 16 char str[200];

17 Passing array to function float mean (int n, float a[ ]) { float sum = 0.0; for (int i=0; i<n; i++) sum += a[i]; return (sum/(float)n); } float std_dev (int n, float a[ ]) { float sum = 0.0, x; x = mean (n, a); for (int i=0; i<n; i++) sum += (x-a[i])*(x-a[i]); return ( sqrt(sum/(float)n) ); } 17

18 Passing array to function (1) #include #define SIZE 6 float mean (int n, float a[ ]) float std_dev (int n, float a[ ]) void main() { float score[SIZE] = { 11., 9., 19., 15., 22., 7.}; for (int i=0; i<SIZE; i++) printf(“%f ”, score[i]); printf(“\n”); float x = std_dev(SIZE, score); printf(“standard deviation = %f\n”, x); } 18

19 Array sorting– “Bubble sort” void sort (int m, int x[ ]) { int i, j, temp; for (i=1; i<m; i++) for (j=0; j<m-i; j++) { if (x[j] > x[j+1] ) { temp = x[j]; x[j] = x[j+1] ; x[j+1] = temp ; } 19

20 20

21 How does bubble sort works Starting from the top of the array/list, swapping the large number to the bottom one by one, so that the largest will sink to the bottom of the list. Repeat the procedure so that the next largest number will sink to on top of the largest number. And so on until the smallest number bubbles to the top, and that is what the name of the algorithm “Bubble sort” means. 21

22 Using array sort #include void sort (int m, int x[ ]); void main() { int score[ ] = { 11, 9, 19, 15, 22, 7}; for (int i=0; i<6; i++) cout << score[i] << “ “; cout << endl; sort(6, score); for (int i=0; i<6; i++) cout << score[i] << “ “; cout << endl; } 22

23 23

24 24

25 Summary Array is a collection of data of the same type. Dimension (size) of a string must be a constant when it is first declared, because memory of array is allocated at compile time. String is an array of characters. C-style string always terminated with the null character. 25

26 Exercise [1] Given 2 integer arrays A & B, of dimension M & N, write a program to merge them into a single array C which contains every item from arrays A & B, in ascending order. [2] Given 2 string s1 = “Merry X’mas” and s2 = “Happy New Year”, write a function with the prototype: void strConcat (char s1[ ], char s2[ ]); so that the strings s1 & s2 will join and the result is stored in s1. Note: s1 must be large enough to hold the contents of both s1 & s2. [3] Write a function: int len = strLength(char s[ ]); so that it can count the number of characters in the string s. Test your function in a main program with char s[ ] = “Happy New Year”; 26

27 27 Write a program that will allow 2 users to play tic-tac-toe. It should ask for moves alternately from player X and player O. The program displays the game positions by a JFrame in the Swing package. When there is a winner it will flash a message box to tell who have won the game. Following code is a suggestion how the program should organize. You should follow your own idea to develop the program.


Download ppt "Structured Programming Instructor: Prof. K. T. Tsang Lecture 6: Arrays 数据序列, 数组 1."

Similar presentations


Ads by Google