Download presentation
Presentation is loading. Please wait.
1
Lecture 10 Arrays
2
Introduction Suppose, you need to store years of 100 cars. Will you define 100 variables?
3
Introduction Algorithms usually work on large data sets
Sort a set of numbers Search a specific number in a set of numbers How to read and store a set of data? To read Repeat the scanf statement Use the loop statements To store the data Save each data in a single variable?? 3000 int variables! ! ! !
4
Example Write a program that get 10 number from user, then sort them. Finally write sorted numbers.
5
Array An ordered collection of same type variables A vector of
Integers, chars, floats, … Example An array of 8 integer 0 1 2 3 4 5 6 7 3 1 5 11 10 19 12 An array of 5 chars
6
Arrays in C Array declaration in C
<Elements’ Type> <identifier>[<size>] <Elements’ Type>: int, char, float, … <size> Old compilers (standard): it should be constant New compilers (standard): it can be variable Elements in array From 0 to (size – 1) Usage <identifier>[index]
7
One-Dimensional Arrays
Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100; An array is an indexed data structure to represent several variables having the same data type: int y[100]; y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]
8
One-Dimensional Arrays (cont’d)
An element of an array is accessed using the array name and an index or subscript, for example: y[2] which can be used like a variable In C, the subscripts always start with 0 and increment by 1, so y[5] is the sixth element The name of the array is the address of the first element y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]
9
Example int num[20]; num is array of 20 integers
num[0] is the first integer variable num[19] is the last integer float farr[100]; farr is array of 100 floats farr[0] is the first float farr[49] is the 50th float farr[99] is the last float
10
Example
11
Array Arrays and structures are “static” entities in that they remain the same size throughout program execution.
12
Example int number[10]; int i, j = 3; i = 5; //-1 < i < 10
number[i + j] = 1; j = number[i]; j = number[i + 1]; j = number[i] + 1; //6th number is 0 //?? //?
13
Array in memory For example : int a[10];
Defines an array of ints with subscripts ranging from 0 to 9 There are 10*sizeof(int) bytes of memory reserved for this array. You can use a[0]=10; x=a[2]; a[3]=a[2]; etc. You can use scanf("%d",&a[3]); 9 8 7 6 5 4 3 2 1 10 a
14
Array Representation int A[3]; A[2] 0x1008 A[1] 0x1004 A[0] 0x1000
All elements of same type – homogenous Last element (index size - 1) First element (index 0) array[0] = 3; array[2] = 4; array[10] = 5; array[-1] = 6; No bounds checking!
15
Array-Bounds Checking
C, unlike many languages, does NOT check array bounds subscripts during: Compilation (some C compilers will check literals) Runtime (bounds are never checked) It is the programmer’s responsibility to ensure that their programs are correctly written and debugged!
16
No Index Out of bound Checking:
There is no index out of bound checking in C, for example the following program compiles fine but may produce unexpected output when run.
17
Using Constants to Define Arrays
It is useful to define arrays using constants: #define MONTHS 12 float a [MONTHS]; What is #define advantages? We can use const instead of #define.
20
Initializing Arrays Initialization of arrays can be done by a comma separated list following its definition For example: int array [4] = { 100, 200, 300, 400 }; This is equivalent to: int array [4]; array[0] = 100; array[1] = 200; array[2] = 300; array[3] = 400; You can also let the compiler figure out the array size for you: int array[] = { 100, 200, 300, 400};
21
Array Initialization When the size if known in compile time
If defined as a local variable (automatic storage class) It is not initialized to any value If defined as a global variable (external storage class) All elements are initialized to 0
22
Array Initialization (cont’d)
Remember that objects with static storage duration will initialize to 0 if no initializer is specified:
23
Assigning values to an array
Give a for loop to assign the below values to list list[0] list[3] list[4] list[1] list[2] 4 3 2 1
24
Accessing Array Elements
Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1.
25
Array Elements An Example to show that array elements are stored at contiguous locations
26
Find Maximum Find maximum value in data array
27
Find average Find average of values in data array
28
Number of elements greater than average
After finding the average as shown in previous slide, use the following code
29
} } } Find pair sum data[0]=5 pair[0]=12 data[1]=7 pair[1]=20
Find sum of every pair in data and write into pair array } data[0]=5 data[1]=7 data[2]=15 data[3]=5 … data[98]=3 data[99]=12 pair[0]=12 pair[1]=20 … pair[49]=15 } . }
30
solution
31
Randomly re-shuffle numbers 30 times
data[0]=5 data[1]=7 data[2]=15 data[3]=5 … data[98]=3 data[99]=12 data[0]=12 data[1]=7 data[2]=5 data[3]=15 … data[98]=3 data[99]=5 .
32
solution
33
Reverse an array 1 2 3 4 5 6 3 1 9 7 2 2 7 9 1 3 6
34
Reverse an Array
35
Print sum of top-bottom pairs
… A[49]=5 A[50]=3 A[98]=4 A[99]=5 + + + ….
36
} } } Group avg Suppose we have a sorted array of hundred grades.
…. Grade[9] Grade[10] … Grade[19] Grade[20] Grade[90] Grade[99] Group avg } Suppose we have a sorted array of hundred grades. We want to find the average of top ten, second top ten students etc. }
37
Initializing Variable Length arrays
38
ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﺩﺪﻋ 20 ﻪﻛ ﻱﺍﻪﻣﺎﻧﺮﺑ ﺯﺍ ﺮﺘﻜﭼﻮﻛ ﻭ ﺮﺘﮔﺭﺰﺑ ﺩﺍﺪﻋﺍ ﺩﺍﺪﻌﺗ
9 #include <stdio.h> #define SIZE 20 void main(void){ int number[SIZE]; double average; int sum, large_size, small_size, i; ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﺩﺪﻋ 20 ﻪﻛ ﻱﺍﻪﻣﺎﻧﺮﺑ ﺯﺍ ﺮﺘﻜﭼﻮﻛ ﻭ ﺮﺘﮔﺭﺰﺑ ﺩﺍﺪﻋﺍ ﺩﺍﺪﻌﺗ .ﺪﻨﻛ ﺏﺎﺴﺣ ﺍﺭ ﻦﻴﮕﻧﺎﻴﻣ sum = large_size = small_size = 0; for(i = 0; i < SIZE; i++){ int tmp; scanf("%d", &tmp); number[i] = tmp; sum += number[i]; } average for(i = = (1.0 * sum) / SIZE; 0; i < SIZE; i++) C99 also has support for variable length arrays on the stack Also, note that the stack is usually much more limited; it's not certain you can allocate very large arrays there if(number[i] >= average) large_size++; else small_size++; printf("average = %f\n", average); printf("Small Size = %d, Large Size = %d\n", small_size, large_size); }
39
ﻪﺘﺷﺭ ﻚﻳ ﻭ ﺩﺍﺪﻋﺍ ﺩﺍﺪﻌﺗ ﻪﻛ ﻱﺍﻪﻣﺎﻧﺮﺑ ﻭ ﺮﺘﮔﺭﺰﺑ ﺩﺍﺪﻋﺍ ﺩﺍﺪﻌﺗ ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﺩﺪﻋ
#include <stdio.h> void main(void){ int n; printf("Enter n: ", n); scanf("%d", &n); int number[n]; double average; int sum, large_size, small_size, i; 10 ﻪﺘﺷﺭ ﻚﻳ ﻭ ﺩﺍﺪﻋﺍ ﺩﺍﺪﻌﺗ ﻪﻛ ﻱﺍﻪﻣﺎﻧﺮﺑ ﻭ ﺮﺘﮔﺭﺰﺑ ﺩﺍﺪﻋﺍ ﺩﺍﺪﻌﺗ ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﺩﺪﻋ .ﺪﻨﻛ ﺏﺎﺴﺣ ﺍﺭ ﻦﻴﮕﻧﺎﻴﻣ ﺯﺍ ﺮﺘﻜﭼﻮﻛ sum = large_size = small_size = 0; for(i = 0; i < n; i++) scanf("%d", &(number[i])); for(i = sum average for(i = 0; i < n; i++) += number[i]; = (1.0 * sum) / n; 0; i < n; i++) if(number[i] >= average) large_size++; else small_size++; printf("average = %f\n", average); printf("Small Size = %d, Larg Size = %d\n", small_size, large_size); }
40
Arrays and Functions
41
Array Elements in Functions
int number[20]; number[i] is an integer variable Array element can be used for call by value input Array element can be use for output
42
Arrays in Functions (cont’d)
Array cannot be used as output type of function int [] f(int x, int y); //compile error Arrays can be used in input list of functions Arrays are not passed by Call By Value Arrays are passed by Call By Reference If we change array elements in a function The element is changed in the caller function
43
Arrays in Functions (version 1)
44
Exercise a[0]=3 a[1]=5 c=? 8 b= n=2 i= sum=
45
Exercise a[0]=3 20 a[1]=5 c=? 8 b= n=2 i= sum=
46
تابعی که یک ارایه به طول 10 را می گیرد و اعضای آن را با اعداد 0 تا 9 مقداردهی میکند.
47
Array Size in Functions
If array is an input parameter of a function It cannot find out the size of the array Array size should be passed from caller function to called function Using definitions
48
Array Size in Functions (cont’d)
If array is declared in a function It knows the size of the array It can find out the size of the array using sizeof
49
ﻞﺤﻣ ﻭ ﺩﺮﻴﮕﺑ ﺍﺭ ﻪﻳﺍﺭﺁ ﻚﻳ ﻪﻛ ﻲﻌﺑﺎﺗ
.ﺪﻧﺍﺩﺮﮔﺮﺑ ﺍﺮﻧﺁ ﻮﻀﻋ ﻦﻳﺮﺘﮔﺭﺰﺑ
50
Search function Liner search Binary search
51
Unordered list – linear search
52
Ordered list – linear search
53
Binary Search Key = 76
54
Binary Search
55
Sort function Selection Sort Bubble Sort
56
Selection Sort
57
Implementation
58
Bubble sort Bubble sort Several passes through the array
Successive pairs of elements are compared If increasing order (or identical ), no change If decreasing order, elements exchanged Repeat
59
Bubble Sort
60
Bubble Sort
61
Bubble Sort
62
Bubble Sort
63
Bubble Sort
64
Bubble Sort
65
Bubble Sort
66
Bubble Sort
67
Bubble Sort
68
Bubble Sort
69
Bubble Sort
70
Bubble Sort
71
Bubble Sort
72
Bubble Sort
73
Bubble Sort
74
Bubble Sort
75
Bubble Sort
76
Bubble Sort
77
Bubble Sort
78
Bubble Sort
79
Bubble Sort
80
Bubble Sort
81
Bubble Sort
82
Implementation
83
Merge two sorted array Assume we have A and B arrays containing sorted numbers For example A = { 3, 5, 7, 9, 12} B = {4, 5, 10} Merge these two arrays as a single sorted array C, for example C = {3, 4, 5, 5, 7, 9, 10, 12}
84
Solution
85
Intersection Set Suppose we have two sets (groups) represented by A and B E.g., A is the set of students taking Math, B is the set of students taking Science. Find set C, the intersection of A and B, i.e., students taking both Math and Science For each element ID in A Search that ID in B if found, put ID into C 4 5 8
86
Use arrays to represent A and B Hand example
6 3 1 9 7 2 4 2 5 6 1 8 B i=0 i=1 j=0 j=3 i=2 i=3 i=4 i=5 i=6 j=1 j=2 j=6 j=1 j=2 j=3 j=4 j=5 j=0 j=1 j=2 j=3 j=4 j=0 k=0 k=1 k=2 k=3 6 1 2 C
87
Solution 6 3 1 9 7 2 4 5 8
88
Multidimensional Arrays
Arrays in C can have virtually as many dimensions as you want Definition is accomplished by adding additional subscripts when it is defined If element of an array is array itself, it will be Multidimensional array For example: int a [4] [3] ; 2-dimensional array 4 * 3 * sizeof(int) int a[4][3][2] 3-dimention array 4 * 3 * 2 * sizeof(int)
89
Multidimensional Arrays Representation
Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript
90
Examples Initialization Example:
short b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; If not enough, unspecified elements set to zero short b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 2 1 4 3 1 4 3
91
Initializing Multidimensional Arrays
The following initializes a[4][3]: int a[4] [3] = { {1, 2, 3} , {4, 5, 6} , {7, 8, 9} , {10, 11, 12} }; Also can be done by: int a[4] [3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; is equivalent to a[0][0] = 1; a[0][1] = 2; a[0][2] = 3; a[1][0] = 4; ... a[3][2] = 12;
92
Multidimensional Arrays
int t[10][20]; 10x20 matrix of integers t[1][1]; //t[1,1] compile error Integer variable in location (1,1)
93
Initializing Multidimensional Arrays
int num[2][3] = {1, 2, 0, 3, 4 = {{1, 2, 0},{3, , 7}; 4, 7}}; num[0][2] is 0, num[1][0] is 3 num[0][2] is ?, num[1][0] is ? int num[5][3] = {{1, 2,0},{3, 4, 7}}; num[2][2] is ?, num[1][2] is ? num[2][2] is 0, num[1][2] is 7 int num[2][3][2] = {{{1,2},{3,4},{5,6}}, {{1},{2},{3}}}; num[0][2][1] is 6, num[1][0][1] is 0 num[0][2][1] is ?, num[1][0][1] is ? int num[][2] = {{1,1},{2,2},{3,3}}; num[1][1] is ?, num[2][0] is ? num[1][1] is 2, num[2][0] is 3
94
Array In Memory
95
Initialization j i j i 1 2 1 2 3 matrix[i][j] = j; 0 1 2 3 1 2 0 1 2 3
1 2 i j 1 2 i 1 2 1 2 3
96
Exercise Write the nested loop to initialize a 2D array as follow 1 2
1 2 3 4 5
97
An Example
98
Multidimensional Arrays in Functions
Can be used as input of functions All dimensions except the first one must be given void func(int a[10][20][5]); Input is a 10x20x5 integer matrix void func(int a[][20][30], int size); void func(int size1, int size2, int a[size1][size2]); Input is a matrix of integers that both rows and columns are variable
99
Multidimensional Arrays in Functions
The first subscript therefore only indicates the amount of storage that is needed when the array is declared Others are required because the computer needs to know how far along to increment the pointer for each "row"
100
#include <stdio.h>
37 #include <stdio.h> void displayMatrix (int nRows, int nCols, int matrix[nRows][nCols]){ int row, column; for ( row = 0; row < nRows; ++row) { for ( column = printf ("%5i", printf ("\n"); 0; column < nCols; ++column ) matrix[row][column]); } ﺲﻳﺮﺗﺎﻣ ﻚﻳ پﺎﭼ ﻱﺍﺮﺑ ﻲﻌﺑﺎﺗ } int main (void){ int sampleMatrix[3][5] = {{ 7, 16, 55, 13, 12 }, { 12, 10, 52, 0, 2, 4, 9 }}; printf ("Original matrix:\n"); displayMatrix (3, 5, sampleMatrix); 7 }, { -2, 1, }
101
ﺲﻳﺮﺗﺎﻣ ﻩﺩﺎﻬﻧﺍﺮﺗ ﻪﺒﺳﺎﺤﻣ
#define SIZE 5 ﺲﻳﺮﺗﺎﻣ ﻩﺩﺎﻬﻧﺍﺮﺗ ﻪﺒﺳﺎﺤﻣ // Matrix Transpose void swap(int a[SIZE][SIZE], int i, int j){ int tmp; tmp = a[i][j]; a[i][j] a[j][i] = a[j][i]; = tmp; } void transpose(int a[][SIZE]){ int i, j; 0; i for(i = < SIZE; i++) for(j = i; j < SIZE; j++) swap(a, i, j); }
102
2-Dim Arrays as Arguments to Functions
void print_m(int m[3][4], int r, int c) void print_m(int m[][4], int r, int c) { int i,j; for (i=0; i < r; i++) { for (j=0; j < c; j++) printf("%.5d ",m[i][j]); printf("\n"); } return; int i, j, matrix[3][4]; for (i=0; i<3; i++) for (j=0; j<4; j++) matrix[i][j] = i; print_m(matrix, 3, 4);
103
Matrix sum Compute the addition of two matrices + = 0 1 2 3 0 1 2 3
1 2 3 -1 3 1 3 3 3 + -1 2 4 3 1 4 2 = 6 6 3 1 1 1 -1 3 1 2 1 1 3 2 4 4 2 2 2
104
solution int matrix1[3][4], matrix2[3][4], sum[3][4];
// initialize matrix1 and matrix2 for (i=0; i<3; i++) for (j=0; j<4; j++) sum[i][j]= matrix1[i][j]+matrix2[i][j];
105
Exchange Two Rows 4 6 2 5 3 8 1 4 6 2 1 8 5 3
106
Transpose 1 5 3 4 2 6 1 4 5 2 3 6 void transpose(int a[NROWS][NCOLS],
int b[NCOLS][NROWS]) { /* Declare Variables. */ int i, j; /* Transfer values to the transpose matrix. */ for(i=0; i<NROWS; i++) { for(j=0; j<NCOLS; j++) { b[j][i] = a[i][j]; } return; a 1 5 3 4 2 6 b 1 4 5 2 3 6
107
Matrix multiplication
double a[3][2], b[2][4], c[3][4]; Find c = a * b; 3 4 5 2 1 6 22 29 45 35 18 40 47 21 26 33 43 49 2 3 7 1 4 5 6 8 = x 3*2 + 4*4=22 3*3 + 4*5=29 3*7 + 4*6=45 3*1 + 4*8=35 5*2 + 2*4=18 5*3 + 2*5=40 5*7 + 2*6=47 5*1 + 2*8=21 1*2 + 6*4=26 1*3 + 6*5=33 1*7 + 6*6=43 1*1 + 6*8=49
108
Matrix Multiplication cont’d
j j 22 29 45 35 18 40 47 21 26 33 43 49 3 4 5 2 1 6 1 2 1 2 2 3 7 1 4 5 6 8 = x i i j=0 c[i][j] = a[i][k=0]*b[k=0][j] + a[i][k=1]*b[k=1][j] 2 4 3 4 k = i=0 x k
109
Matrix Multiplication cont’d
#define N 3 #define M 2 #define L 4 void matrix_mul(a[N][M], int b[M][L], int c[N][L]) { int i, j, k; for(i=0; i < N; i++) { for(j=0; j < L; j++) { c[i][j] = 0; for(k=0; k < M; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } return;
110
Common Bugs & Avoiding them
You cannot assign a value to array int a[4], b[4]; a = b; // Error Each array name refers to a constant pointer. Can’t change where the array name refers to But you can change the array elements, via pointer arithmetic (int []) ??? (int) ??? (int) ??? (int) ??? (int) int m[4]; m
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.