Professional Documents
Culture Documents
Chap 5
Chap 5
1
Name Addr Content
Lecture++;
Lecture 19
2
5.1 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];
7
Assigning values to an array
For loops are often used to assign values to an array
list[0]
list[1]
Example: list[2]
list[3]
int list[5], i; list[4]
for(i=0; i<5; i++){
list[i] = i;
} 0 list[0]
OR 1 list[1]
2 list[2]
for(i=0; i<=4; i++){ 3 list[3]
list[i] = i; 4 list[4] 8
}
Assigning values to an array
Give a for loop to assign the below values to list
9
Input from a data file
Arrays are often used to store information from a data file
int k;
double time[10], motion[10];
FILE *sensor3;
sensor3 = fopen(“sensor3.dat”, “r”);
for(k=0; k<10; k++) {
fscanf(sensor3, “%lf %lf”,
&time[k], &motion[k]);
}
10
Exercise
Show the contents of the arrays defined in
each of the following sets of statements.
11
Exercise
int data[100], i;
Store random numbers [0,99] in data
for (i=0; i<100; i++)
data[i] = rand() % 100;
Store random numbers [10,109] in data
for (i=0; i<100; i++)
data[i] = (rand() % 100) + 10;
OR
for (i=0; i<100; i++)
data[i] = rand_int(10,109);
12
Computations on one-D arrays
13
Find Maximum
Find maximum value in data array
int data[100], max, i;
for (i=0; i<100; i++)
data[i] = rand_int(10,109);
max = data[0];
for (i=1; i<100; i++){
if (data[i] > max)
max = data[i];
}
printf("Max = %d\n",max);
14
Find average
Find average of values in data array
int data[100], sum, i, avg;
for (i=0; i<100; i++)
data[i] = rand_int(10,109);
sum = 0;
for (i=0; i<100; i++){
sum = sum + data[i];
}
avg = (double)sum/100;
printf(“Avg = %lf\n", avg);
15
Number of elements greater
than average
After finding the average as shown in
previous slide, use the following code
count = 0;
for (i=0; i<100; i++){
if (data[i] > avg)
count++;
}
printf(“%d elements are “
“greater than avg”, count);
16
Find pair sum
Find sum of every pair in data and write into pair array
data[0]=5
data[1]=7 } pair[0]=12
}
data[2]=15 pair[1]=20
data[3]=5 . …
… .
pair[49]=15
… .
data[98]=3
data[99]=12 } 17
solution
data[0]=5 data[0]=12
data[1]=7 data[1]=7
data[2]=15 data[2]=5
data[3]=5 .
data[3]=15
… . …
… . …
data[98]=3 data[98]=3
data[99]=12 data[99]=5
19
solution
int data[100], i, j, k, tmp;
for (i=0; i<100; i++)
data[i] = rand_int(1,109);
for (n=0; n<30; n++){
i=rand_int(0,99);
j=rand_int(0,99);
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
} 20
Copy array1 to array2 in
reverse order
0 1 2 3 4 5
array1 6 3 1 9 7 2
array2 2 7 9 1 3 6
21
Print sum of top-bottom pairs
A[0]=3
A[1]=6
…
A[49]=5
+ …. + +
A[50]=3
A[98]=4
A[99]=5 22
Random numbers from an
irregular range
Suppose you want to generate 50
random numbers, but you want to
chose them uniformly from a set of
given numbers like 52 67 80 87 90 95
Can you do this using arrays?
23
}
Grade[0]
Grade[1]
Group avg ….
Grade[9]
}
Suppose we have Grade[10]
a sorted array of …
hundred grades. Grade[19]
We want to find Grade[20]
the average of …
top ten, second
}
top ten students Grade[90]
etc.
….
Grade[99] 24
Name Addr Content
Lecture++;
Lecture 20
REVIEW
25
Name Addr Content
Lecture++;
Lecture 21
MIDTERM 2
26
Name Addr Content
Lecture++;
Lecture 22
27
Arrays as
Function Arguments
28
Function Arguments
Individual elements of an array can be passed
as regular arguments.
void donothing(int a, int b)
{
…
}
int main(void)
{
/* Declare variables and functions */
int array[5] = {1,2,3,4,5};
donothing(array[2], array[4]);
}
Calls donothing(3, 5); 29
Passing Arrays to Functions
Arrays are always pass by reference
Modifications to the array are reflected to main program
The array name is the address of the first element
The maximum size of the array must be specified at the
time the array is declared.
The actual number of array elements that are used will
vary, so the actual size of the array is usually passed as
another argument to the function
30
main()
Exercise
{
int a[2]={3, 5};
int c; a[0]=3
c = sum_arr(a, 2) a[1]=5
}
c=? 8
int sum_arr(int b[], int n)
{
b=
int i, sum=0;
n=2
for(i=0; i < n; i++)
sum = sum + b[i]; i=0 1 2
return(sum); sum=0 3 8
31
}
main()
Exercise
{
int a[2]={3, 5};
int c;
c = sum_arr(a, 2) a[0]=3 20
} a[1]=5
int sum_arr(int b[], int n) c=? 8
{
int i, sum=0;
b=
for(i=0; i < n; i++)
n=2
sum = sum + b[i];
i=0 1 2
b[0] = 20;
return(sum);
sum=0 3 8
32
Exercise
Write a function to find maximum value in the array
data
int main()
int maximum(int fdata[],
{ int n)
int data[100],i, max; {
int i, fmax;
for (i=0; i<100; i++) fmax = fdata[0];
for (i=0; i<n; i++)
data[i] = rand() % 100; if(fdata[i] > fmax)
max = maximum(data,100); fmax = fdata[i];
return(fmax);
printf("Max = %d\n",max); }
return(0);
} 33
Exercise
What is the output of the following program?
35
5.4 Statistical measurements
In engineering, analyzing the statistical
characteristics of data is important
Suppose we have an array of
/* Determine sum of
values in the array. */
sum = x[0];
for (k=1; k<=n-1; k++)
sum = sum + x[k];
mu = mean(x, n);
41
Name Addr Content
Lecture++;
Lecture 23
42
5.6 Sorting an array
0 1 2 3 4 5
6 3 1 9 7 2
1 3 6 9 7 2
1 2 6 9 7 3
1 2 3 9 7 6
1 2 3 6 7 9
1 2 3 6 7 9
43
Selection Sort (solution 1)
void selection_sort(double x[], int n)
{
int k,j,m;
double temp;
for(k=0; k<=n-2; k++) {
m = k;
for(j=m+1; j<=n-1; j++)
if(x[j] < x[m]) m = find_min_pos(x, n, k);
m = j;
temp = x[k];
x[k] = x[m]; swap(x, k, m);
x[m] = temp
}
} 44
Selection Sort (solution 2)
45
Selection Sort cont’d
int find_min_pos(double fx[], int fn, int fk)
{
int j;
int m=fk;
for (j=m+1; i<=fn-1; j++)
if (fx[j] < fx[m])
m = j;
return(m);
}
46
Selection Sort cont’d
47
Reverse an array
0 1 2 3 4 5
6 3 1 9 7 2
2 7 9 1 3 6
48
Reverse an Array
void reverse(double x[], int n)
{
int i=0, j=n-1;
while (i<j) {
swap(x,i,j);
i = i + 1;
j = j - 1;
}
return;
49
}
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}
50
5.7 Search Algorithms
Unordered list
Linear search
In a loop compare each element in array
with the value you are looking for ()
Ordered list
Linear search
A better solution is known as Binary search
(but we will skip it this time, it is like
looking for a word in a dictionary)
51
Unordered list – linear search
int search1(int x[], int n, int value)
{
int i;
for(i=0; i < n; i++) {
if (x[i]== value)
return i;
}
return(-1);
}
52
Ordered list – linear search
int search2(int x[], int n, int value)
{
int i;
for(i=0; i < n; i++) {
if (x[i]== value)
return i;
else if (x[i] > value)
break;
}
return(-1);
} 53
Name Addr Content
Lecture++;
Lecture 24
54
Strings (strings are discussed in
Section 6.6 of the textbook )
A string is an array of characters
char data[10] = “Hello”;
char data2[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}
Use printf to print strings
printf(“%s”,data);
Can be accessed char by char
data[0] is first character End of String
Symbol
H e l l o \0
0 1 2 3 4 5 6 7 8 9
data 55
Strings
Each character has an integer representation
a b c d e … … … … z
97 98 99 100 101 ………………………112
A B C D E … … … … Z
65 66 67 68 69 ……………………… 90
0 1 2 3 4 5 6 7 8 9
48 49 50 51 52 53 54 55 56 57
\0 \n
0 10 56
Strings
Characters can be interpreted as integers
char c = ‘A’;
printf(“%c \n”,c);
prints A
printf(“%d \n”,c);
prints 65
Printf(“%c \n”,65);
prints A
57
Exercise
Write a function to count the number of characters in
a string.
Idea: count the number of characters before \0
H e l l o \0
58
Solution
int count_letters(char cdata[])
{
int i=0;
return(i);
}
59
Exercise
Write a function that prints a string in reverse
Idea: find the end of the string and print the
characters backwards.
H e l l o \0
Output: olleH
60
Solution
void print_reverse(char pdata[])
{
int size,position;
size = count_letters(pdata);
position = size - 1;
while (position >= 0) {
printf("%c",pdata[position]);
position = position -1;
}
printf("\n");
return;
}
61
Exercise
Write a function that compares 2 strings S1 and S2
using lexicographic order.
Idea: compare character by character
Return
a neg value if S1 < S2,
H e l l o \0
0 if S1 == S2
a pos value if S1 > S2
H e l o o \0
62
Solution (incomplete)
63
Solution (complete)
int compare(char cdata1[], char cdata2[])
{
int i= 0;
while (cdata1[i] != ‘\0’ && cdata2[i] != ‘\0’
&& cdata1[i] == cdata2[i])
i = i + 1;
64
Exercise: Spell out a number
in text using arrays of strings
Write a program that reads a number
between 1 and 999 from user and spells
out it in English.
For example:
453 Four hundred fifty three
37 Thirty seven
204 Two hundred four
65
Name Addr Content
Lecture++;
Lecture 25
66
More Examples of one
dimensional arrays
67
Trace a program
Trace the following program and show how
variables change in memory.
int main() x[0] 3
{ x[1] 5
int x[5]={3, 5, 3, 4, 5}; x[2] 3
int i, j, count;
x[3] 4
for(i = 0; i < 5; i++){
x[4] 5
count = 1;
i ?
for(j = i+1; j < 5; j++){
j ?
if (x[i] == x[j]) count++;
count ?
}
printf(“%d %d \n”, x[i], count);
} 68
}
Count how many times a
value appears in the array
int find_count(int cdata[], int n, int x)
{
int count = 0;
int i;
for (i = 0; i<n; i++){
if (cdata[i] == x) 6 3 1 9 7 2
count = count + 1; 1 2 3
0 4 5
}
return (count);
find_count(A,6,2) returns 1
} find_count(A,4,2) returns 0
69
Insert unique RNs
Insert random numbers into an array so that each
number appears in the array at most once.
int A[6];
for (i=0; i<6; i++)
A[i] = rand() % 10;
6 3 1 9 6 2
A
Produces
Duplicates
70
Insert unique RNs (cont’s)
Insert random numbers into an array so that each
number appears in the array at most once.
void initialize(int idata[], int n)
{
int i=0, j, elem; 6 3 1 9 6
while (i<=n) { A
elem = rand() % 10;
if (find_count(idata,i,elem) == 0) { Try a new
idata[i] = elem; number
i = i + 1;
}
}
}
71
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 3 6 4
if found, put ID into C 9 5
1 8
7 2
72
Use arrays to represent A and B
Hand example
A 6 3 1 9 7 2 B 4 2 5 6 1 8
6 1 2
C
73
Solution
int intersection(int A[],int B[],
int C[], int n)
{
int i=0, j=0, k=0;
for(i=0; i < n; i++) {
for(j=0; j < n; j++) {
if (A[i]==B[j]){
C[k]=A[i];
k++;
break;
} 6 3 1 9 7 2
}
} 4 2 5 6 1 8
return(k);
6 1 2 74
}
Another Solution
int intersection(int A[], int B[],
int C[], int n)
{
int i=0, k=0, elem;
while (i < n) {
elem = A[i];
if(find_count(B,n,elem) == 1) {
C[k] = elem;
k = k + 1;
}
i = i + 1; 6 3 1 9 7 2
}
return(k); 4 2 5 6 1 8
}
6 1 2 75
What if A and B were sorted?
78
Exercise: Histogram
Suppose somehow we read npts integer
numbers from a file into an array declared by
int x[100]. We know that all the values are
integers between 0 and 10. Now suppose we
want to find how many 0’s ,1’s, …, 10’s exist in
the array x.
Write a function that will take x and npts as
the parameters and prints out the number of
0’s ,1’s, …, 10’s that exist in the array x
79
solution
void my_function(int x[], int npt)
{
int i, hist[11]={0};
82
Name Addr Content
Lecture++;
Lecture 26
83
5.8 Matrices (2D-array)
A matrix is a set of numbers arranged in a grid with rows and columns.
A matrix is defined using a type declaration statement.
datatype array_name[row_size][column_size]; 4
int matrix[3][4]; 1
0
Row 0 4 1 0 2 2
-1
Row 1 -1 2 4 3 2
4
Row 2 0 -1 3 1 3
0
-1
3
in memory 84
Accessing Array Elements
int matrix[3][4];
matrix has 12 integer elements
85
Initialization
int x[4][4] = { {2, 3, 7, 2},
{7, 4, 5, 9},
{5, 1, 6, -3},
{2, 5, -1, 3}};
int x[][4] = { {2, 3, 7, 2},
{7, 4, 5, 9},
{5, 1, 6, -3},
{2, 5, -1, 3}};
86
Initialization
int i, j, matrix[3][4];
for (i=0; i<3; i++)
for (j=0; j<4; j++)
matrix[i][j] = i; matrix[i][j] = j;
j
j
0 1 2 3
0 1 2 3
0 0 0 0 0
0 0 1 2 3
i 1 1 1 1
1
i 1 0 1 2 3
2 2 2 2 2
2 0 1 2 3 87
Exercise
Write the nested loop to initialize a 2D
array as follow
0 1 2 int i, j, x[4][3];
1 2 3 for(i=0; i<4; i++)
2 3 4 for(j=0; j<3; j++)
3 4 5 x[i][j] = i+j;
88
2-Dim Arrays as Arguments to Functions
void print_m(int m[3][4],
int r, int c)
90
Max in 2D
Find the maximum of int matrix[3][4]
0 1 2 3
int max = matrix[0][0]; 1 0 2
0 0
for (i=0; i<3; i++)
1 -1 2 4 3
for (j=0; j<4; j++)
2 0 -1 3 1
if (matrix[i][j] > max)
max = matrix[i]
[j];
91
Find a value in 2D
Find the number of times x appears in int matrix[3][4]
0 1 2 3
int count = 0; 1 0 2
0 0
for (i=0; i<3; i++)
1 -1 2 4 3
for (j=0; j<4; j++)
2 0 -1 3 1
if (matrix[i][j] == x)
count = count +
1;
92
Matrix sum
Compute the addition of two matrices
0 1 2 3 0 1 2 3 0 1 2 3
0 0 1 0 2 0 3 -1 3 1 0 3 0 3 3
1 -1 2 4 3 + 1 1 4 2 0 = 1 0 6 6 3
2 0 -1 3 1 2 2 1 1 3 2 2 0 4 4
93
solution
int matrix1[3][4],
matrix2[3][4],
sum[3][4];
// initialize matrix1 and matrix2
94
Exchange Two Rows
4 6 2
0 5 3
0 8 1 4 6 2
2 1 4 2 1 4
0 8 1
0 5 3
95
Transpose
void transpose(int a[NROWS][NCOLS],
int b[NCOLS][NROWS])
a
{
/* Declare Variables. */
1 5 3 int i, j;
4 2 6
/* Transfer values to the
transpose matrix. */
b
for(i=0; i<NROWS; i++) {
1 4 for(j=0; j<NCOLS; j++) {
b[j][i] = a[i][j];
5 2 }
}
3 6 return;
} 96
mine sweeper
If m[i][j] is 0, there is no mine in cell m[i][j]
If m[i][j] is 1, there is a mine in cell m[i][j]
Print the number of mines around cell m[i][j]
[i][j]
97
Solution (1) - incomplete
count=0;
if( m[i-1][j-1] ) count++;
if( m[i-1][j] ) count++;
if( m[i-1][j+1] ) count++;
if( m[i][j-1] ) count++;
if( m[i][j+1] ) count++;
if( m[i+1][j-1] ) count++;
if( m[i+1][j] ) count++;
if( m[i+1][j+1] ) count++; 98
What if [i][j] is not in the
middle?
[i][j]
[i][j] [i][j]
99
Solution (1) – complete
NR: is number of rows
NC: number of columns
count=0;
if( i>0 && j>0 && m[i-1][j-1] ) count++;
if( i>0 && m[i-1][j] ) count++;
if( i>0 && j<NC-1 && m[i-1][j+1] )
count++;
if( j>0 && m[i][j-1] )
count++;
if( j<NC-1 && m[i][j+1] ) count++;
if( i<NR-1 && j>0 && m[i+1][j-1] ) count++;
if( i<NR-1 && m[i+1][j] 100
) count++;
int r,Solution (2)
c, count=0; NR: is number of rows, NC: number of columns
4 5 3 2 1 0
6 1 6 1 2 3
4 3 1
2 10
6 2 5
102
Matrix multiplication
double a[3][2], b[2][4], c[3][4];
Find c = a * b;
3 4 22 29 45 35
2 3 7 1
5 2 x = 18 40 47 21
4 5 6 8
1 6 26 33 43 49
3*2 + 4*4=22 3*3 + 4*5=29 3*7 + 4*6=45 3*1 + 4*8=35
1 5 2 x = 1 18 40 47 21
4 5 6 8
2 1 6 2 26 33 43 49
i i
j=0
c[i][j] =
2
i=0 3 4 x k = a[i][k=0]*b[k=0][j] +
4 a[i][k=1]*b[k=1][j]
k
104
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;
} 105
Exercise: Find possible values
for cell s[i][j] in Sudoku
4 1 7 6 8
8 4 3 7
5 3 4
7 4 1
3 1 9 [i][j] 7 4 6
6 8 9
3 5 7
8 2 6 9
4 5 1 8 3
106
Exercise:
Dynamic programming
0 1 2 3 4 5
1 max
+
2
x x x x x
x x x x
x x x x
108
Example: 3
Closest Points 1
1 2
109
Skip
Study Section 5.9 (terrain navigation)
Study Section 5.10*
Study Section 5.11* (optional)
Study Section 5.12* (optional)
Study Section 5.13* (optional)
110