Title: Arrays and Matrices
1CSCI-125/ENGR-144 Engineering Problem Solving
with C Ch 5
2Name Addr Content
Lecture
Lecture
35.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 y100
y0 y1 y2 yk-1
yk yk1 y98 y99
4One-Dimensional Arrays (contd)
- An element of an array is accessed using the
array name and an index or subscript, for
example y5 which can be used like a variable - In C, the subscripts always start with 0 and
increment by 1, so y5 is the sixth element - The name of the array is the address of the first
element and the subscript is the offset
y0 y1 y2 yk-1
yk yk1 y98 y99
5Definition and Initialization
- An array is defined using a declaration
statement. - data_type array_namesize
- allocates memory for size elements
- subscript of first element is 0
- subscript of last element is size-1
- size must be a constant
6Example
- int list5
- allocates memory for 5 integer variables
- subscript of first element is 0
- subscript of last element is 4
- C does not check bounds on arrays
- list6 5 / may give segmentation fault or
overwrite other memory locations/
7Initializing Arrays
- Arrays can be initialized at the time they are
declared. - Examples
- double taxrate3 0.15, 0.25, 0.3
- char list5 h, e, l, l, o
- double vector100 0.0 / assigns
- zero to all 100 elements /
- int s 5,0,-5 /the size of s is 3/
8Assigning values to an array
For loops are often used to assign values to an
array
Example int list5, i for(i0 ilt5
i) listi i
OR for(i0 ilt4 i) listi i
9Assigning values to an array
Give a for loop to assign the below values to list
int list5, i for(i0 ilt5 i) listi
4-i
10Input from a data file
Arrays are often used to store information from a
data file int k double time10,
motion10 FILE sensor3 sensor3
fopen(sensor3.dat, r) for(k0 klt10 k)
fscanf(sensor3, lf lf, timek,
motionk)
11Exercise
Show the contents of the arrays defined in each
of the following sets of statements. int x3
-5, 4, 3 char letters 'a', 'b',
'c' double z4
12Exercise
- int data100, i
- Store random numbers 0,99 in data
- for (i0 ilt100 i)
- datai rand() 100
- Store random numbers 10,109 in data
- for (i0 ilt100 i)
- datai (rand() 100) 10
- OR
- for (i0 ilt100 i)
- datai rand_int(10,109)
13Computations on one-D arrays
14Find Maximum
- Find maximum value in data array
- int data100, max, i
- for (i0 ilt100 i)
- datai rand_int(10,109)
- max data0
- for (i1 ilt100 i)
- if (datai gt max)
- max datai
-
- printf("Max d\n",max)
15Find average
- Find average of values in data array
- int data100, sum, i, avg
- for (i0 ilt100 i)
- datai rand_int(10,109)
- sum 0
- for (i0 ilt100 i)
- sum sum datai
-
- avg (double)sum/100
- printf(Avg lf\n", avg)
16Number of elements greater than average
- After finding the average as shown in previous
slide, use the following code
count 0 for (i0 ilt100 i) if (datai
gt avg) count printf(d elements are
greater than avg, count)
17Find pair sum
- Find sum of every pair in data and write into
pair array
data05
data17
data215
data35
data983
data9912
pair012
pair120
pair4915
. . .
18solution
int data100, pair50, i for (i0 ilt100
i) datai rand_int(1,100) for (i0 ilt50
i) pairi data2i data2i1
19Randomly re-shuffle numbers 30 times
data05
data17
data215
data35
data983
data9912
data012
data17
data25
data315
data983
data995
. . .
20solution
int data100, i, j, k, tmp for (i0 ilt100
i) datai rand_int(1,109) for (n0 nlt30
n) irand_int(0,99) jrand_int(0,99)
tmp datai datai dataj dataj
tmp
21Copy array1 to array2 in reverse order
0
2
1
3
4
5
6
3
1
9
7
2
array1
2
7
9
1
3
6
array2
22Print sum of top-bottom pairs
A03
A16
A495
A503
A984
A995
.
23Random 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?
24Group avg
Grade0
Grade1
.
Grade9
Grade10
Grade19
Grade20
Grade90
.
Grade99
- Suppose we have a sorted array of hundred grades.
- We want to find the average of top ten, second
top ten students etc.
25Name Addr Content
Lecture
Lecture
26Arrays as Function Arguments
27Function 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 array5 1,2,3,4,5
- donothing(array2, array4)
Calls donothing(3, 5)
28Passing to Function
- Passing array elements
- call by value
- argument is array name with and index
- parameter is normal data type
- int status6
- status
- print_sts(status2)
- void print_sts(int passed_status)
-
12
function call
called function header
passed_status gets value of 12 copied to it
29Passing to Function
- Passing arrays
- call by reference
- argument is array name with no
- parameter has empty 1st
- int status6
- status
- printf_sts(status)
-
- void print_sts(int passed_array )
array name is passed - an address!
parameter is an array of same type but called
function does not know size sizeof() will not
help! (should pass as an additional parameter)
30Passing 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
31Exercise
main() int a23, 5 int c c
sum_arr(a, 2) int sum_arr(int b, int n)
int i, sum0 for(i0 i lt n i) sum
sum bi return(sum)
a03
a15
c? 8
b
n2
i0 1 2
sum0 3 8
32Exercise
main() int a23, 5 int c c
sum_arr(a, 2) int sum_arr(int b, int n)
int i, sum0 for(i0 i lt n i) sum
sum bi b0 20 return(sum)
a03 20
a15
c? 8
b
n2
i0 1 2
sum0 3 8
33Exercise
Write a function to find maximum value in the
array data
int main() int data100,i, max for (i0
ilt100 i) datai rand() 100 max
maximum(data,100) printf("Max d\n",max)
return(0)
- int maximum(int fdata,
- int n)
-
- int i, fmax
- fmax fdata0
- for (i0 iltn i)
- if(fdatai gt fmax)
- fmax fdatai
- return(fmax)
-
34Exercise
- What is the output of the following program?
- void print(int pdata, int n)
-
- int i
- for (i0 iltn i) printf("datadd\n",
- i,pdatai)
- return
-
- void modify(int fdata, int n)
-
- int i
- for (i0 iltn i)
- fdatai 1
- return
int main() int data10 for (i0 ilt10
i) datai rand() 100
print(data,10) modify(data,10)
print(data,10) return(0)
355.4 Statistical measurements
- In engineering, analyzing the statistical
characteristics of data is important - Suppose we have an array of measurements (double
data) - Let us develop functions to compute max, min,
mean (average), median, variance, std-dev of
these measurements
36max() and min()
double min(double x, int n) / Declare
variables. / int k double min_x /
Determine minimum value in the array. /
min_x x0 for (k1 k lt n k) if
(xk lt min_x) min_x xk /
Return minimum value./ return min_x
double max(double x, int n) / Declare
variables. / int k double max_x /
Determine maximum value in the array. /
max_x x0 for (k1 k lt n-1 k)
if (xk gt max_x) max_x xk /
Return maximum value./ return max_x
37mean()
double mean(double x, int n) / Declare
variables. / int k double sum /
Determine sum of values in the array. /
sum x0 for (k1 kltn-1 k) sum
sum xk / Return avg value. /
return sum/n
38median()
/ values in x must be sorted ! / double
median(double x, int n) / Declare
variables. / int k double median_x
/ Determine median of values in the
array. / k floor(n/2) if( n 2 !
0) median_x xk else median_x
(xk-1xk)/2 / Return median value. /
return median_x
Example x7, 9, 15, 27, 29 n5 median_x15
x3, 6, 7, 9 n4 median_x(67)/2 median_
x6.5
39variance()
double variance(double x, int n) /
Declare variables. / int k double mu,
sum0 mu mean(x, n) for (k0
kltn-1 k) sum sum pow(xk-mu, 2)
/ Return variance value. / return
sum/(n-1)
40std_dev()
double std_dev(double x, int n) / Return
standard deviation / return sqrt(variance(x,
n))
41Name Addr Content
Lecture
Lecture
425.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_namerow_sizecolumn_size
- int matrix34
4
1
0
2
-1
2
4
3
0
-1
3
1
4 1 0 2
-1 2 4 3
0 -1 3 1
Row 0
Row 1
Row 2
Column 3
Column 0
Column 2
Column 1
in memory
43Accessing Array Elements
- int matrix34
- matrix has 12 integer elements
- matrix00 element in first row, first column
- matrix23 element in last row, last column
- matrix is the address of the first element
- matrix1 is the address of the Row 1
- matrix1 is a one dimensional array (Row 1)
44Initialization
- int x44 2, 3, 7, 2,
- 7, 4, 5, 9,
- 5, 1, 6, -3,
- 2, 5, -1, 3
- int x4 2, 3, 7, 2,
- 7, 4, 5, 9,
- 5, 1, 6, -3,
- 2, 5, -1, 3
45Initialization
- int i, j, matrix34
- for (i0 ilt3 i)
- for (j0 jlt4 j)
- matrixij i
matrixij j
0 0 0 0
1 1 1 1
2 2 2 2
0 1 2 3
0 1 2 3
0 1 2 3
46Exercise
- Write the nested loop to initialize a 2D array as
follow
int i, j, x43 for(i0 ilt4 i) for(j0
jlt3 j) xij ij
0 1 2
1 2 3
2 3 4
3 4 5
47- If m is a 5x5 integer matrix, what is display by
this loop - for (i0 i lt5 i)
- printf(8d, m2i)
- what is displayed by this loop?
- for (i0 i lt5 i)
- printf(8d, mi4)
- If sq is a C array representing the matrix
- 4 5 18
- 2 4 9
- 8 4 12
- what is displayed by this loop?
- for (i0 i lt3 i)
- printf(8d, sqii)
482-Dim Arrays as Arguments to Functions
void print_m(int m34, int r,
int c)
void print_m(int m4, int r, int
c) int i,j for (i0 i lt r i) for
(j0 j lt c j) printf(".5d ",mij)
printf("\n") printf("\n") return
int i, j, matrix34 for (i0 ilt3 i)
for (j0 jlt4 j) matrixij
i print_m(matrix, 3, 4)
49Computations on 2D arrays
50Max in 2D
- Find the maximum of int matrix34
0 1 2 3
int max matrix00 for (i0 ilt3 i) for
(j0 jlt4 j) if (matrixij gt max)
max matrixij
1
2
0
0
0
-1
2
4
3
1
0
-1
3
1
2
51Find a value in 2D
- Find the number of times x appears in int
matrix34
0 1 2 3
- int count 0
- for (i0 ilt3 i)
- for (j0 jlt4 j)
- if (matrixij x)
- count count 1
1
2
0
0
0
-1
2
4
3
1
0
-1
3
1
2
52Matrix sum
- Compute the addition of two matrices
0 1 2 3
0 1 2 3
0 1 2 3
0
3
3
-1
1
3
1
2
0
3
3
0
0
0
0
0
6
6
3
1
4
2
0
-1
2
4
3
1
1
1
2
0
4
4
2
1
1
3
0
-1
3
1
2
2
2
53solution
- int matrix134,
- matrix234,
- sum34
- // initialize matrix1 and matrix2
- for (i0 ilt3 i)
- for (j0 jlt4 j)
- sumij matrix1ijmatrix2ij
54Exchange Two Rows
4 6 2
0 5 3
0 8 1
2 1 4
4 6 2
2 1 4
0 8 1
0 5 3
55Transpose
- void transpose(int aNROWSNCOLS,
- int bNCOLSNROWS)
-
- / Declare Variables. /
- int i, j
- / Transfer values to the
- transpose matrix. /
- for(i0 iltNROWS i)
- for(j0 jltNCOLS j)
- bji aij
-
-
- return
a
1 5 3
4 2 6
b
1 4
5 2
3 6
56Matrix multiplication
- double a32, b24, c34
- Find c a b
22 29 45 35
18 40 47 21
26 33 43 49
3 4
5 2
1 6
2 3 7 1
4 5 6 8
x
32 4422
33 4529
37 4645
31 4835
52 2418
53 2540
57 2647
51 2821
12 6426
13 6533
17 6643
11 6849
57Matrix Multiplication contd
j
j
0 1 2 3
0 1 2 3
22 29 45 35
18 40 47 21
26 33 43 49
3 4
5 2
1 6
0 1 2
0 1 2
2 3 7 1
4 5 6 8
x
i
i
j0
cij aik0bk0j
aik1bk1j
2
4
3 4
k
i0
x
k
58Matrix Multiplication contd
define N 3 define M 2 define L 4 void
matrix_mul(aNM, int bML, int cNL)
int i, j, k for(i0 i lt N i)
for(j0 j lt L j) cij 0
for(k0 k lt M k) cij
cij aik bkj
return
59 / Computes the product of M-by-N matrix a and
the N-dimensional vector x. The result is stored
in the output parameter v, an M-dimensional
vector./ void mat_vec_prod(double v, /
output - M-dimensional product vector /
double aMN, / input - M-by-N
matrix /
double x) / input - N-dimensional vector
/ int i, k for
(i 0 i lt M i) vi 0
for (k 0 k lt N k)
vi aik xk
60Name Addr Content
Lecture
Lecture
61Strings
- A string is an array of characters
- char data10 Hello
- char data2 H, e, l, l, o, \0
- Use printf to print strings
- printf(s,data)
- Can be accessed char by char
- data0 is first character
End of String Symbol
H
e
l
l
o
\0
0 1 2 3 4 5 6 7 8 9
data
62 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
9
8
7
6
5
48 49 50 51 52 53 54 55 56 57
\0
\n
0
10
63 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
64Exercise
- 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
65Solution
- int count_letters(char cdata)
-
- int i0
-
- while (cdatai ! '\0')
- i i 1
- return(i)
66Exercise
- 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
67Solution
- void print_reverse(char pdata)
-
- int size,position
- size count_letters(pdata)
- position size - 1
- while (position gt 0)
- printf("c",pdataposition)
- position position -1
-
- printf("\n")
- return
68String.h
- strlen(s) returns the number of
characters in s - strcpy(dst,src) copies string from src to
dst - strncpy(dst,src,n) copies n chars from src to dst
- strcat(dst,src) appends src to end of dst
- strncat(dst,src,n) appends n chars of src to end
of dst - strcmp(s1,s2) returns negative value if
s1lts2, positive value if s1gts2, and 0
if same - strncmp(s1,s2,n) similar to strcmp, but
compares n chars
69Implement strlen
- Null character not included
- Machineindustrial robot
- strlen(machine)???
70strcpy function
- Copies characters from source string to string
called the destination - void strcpy(char dst, char src)
- Useful for manipulating a copy of a string, or
making a string assignment - cannot use name Jane
- must use strcpy(name, Jane)
- Note the destination string must be declared
- char name10
71Implementing strcpy
- Array implementation
- void strcpy(char dst, char src)
-
- int i
- for (i0 srci!\0 i)
- dsti srci
-
- dsti \0
-
72strcmp function
- int strcmp(char s1, char s2)
- Returns 0 if strings same, positive value if
first string larger, negative otherwise - Statement if (strcmp(s1,s2)) executes body
of if when strings differ - To compare if two strings are the same, use if
(strcmp(s1,s2) ! 0)
73Exercise
- Write a function that compares 2 strings S1 and
S2 using lexicographic order. - Idea compare character by character
- Return
- a neg value if S1 lt S2,
- 0 if S1 S2
- a pos value if S1 gt S2
H
e
l
l
o
\0
H
e
l
o
o
\0
l lt o in lexicographic order
74Solution (incomplete)
- int compare(char cdata1, char cdata2)
-
- int i 0
- while (cdata1i cdata2i)
- i i 1
- return (cdata1i - cdata2i)
75Solution (complete)
- int compare(char cdata1, char cdata2)
-
- int i 0
- while (cdata1i ! \0 cdata2i ! \0
- cdata1i cdata2i)
- i i 1
- return (cdata1i - cdata2i)
-
76Arrays as Strings
- Load from keyboard
- one char at a time or as a string
- c
- for(ctr 0 namectr ! \n ctr)
- namectr getchar( )
- scanf(s, name)
- gets(name)
reads each character until the \n is encountered
you must insert the null at the end!
reads string from keyboard converts the \n to a
null, but will stop at first 'whitespace'
character!
reads string from keyboard, including any
whitespace converts \n to null
77 include ltstdio.hgt define STRING_LEN 10
int main(void) char deptSTRING_LEN
int course_num char
daysSTRING_LEN int time
printf("Enter department code, course number,
days and ") printf("time like this\ngt
COSC 2060 MWF 1410\ngt ")
scanf("sdsd", dept, course_num, days,
time) printf("s d meets s at d\n",
dept, course_num, days, time) return
(0) Enter department code, course
number, days and time like this gt MATH
1270 TR 800 gt MATH1270 TR 1800 gt
MATH,1270,TR,1800
78include ltstdio.hgt int main() char
name20 printf("Enter name ")
scanf("s",name) printf("Your name is s.",
name) return 0
Enter name Dennis Ritchie
include ltstdio.hgt int main() char name30,
ch int i0 printf("Enter name ")
while(ch!'\n') // terminates if user hit
enter chgetchar()
nameich i namei'\0'
// inserting null character at end
printf("Name s", name) return 0
Enter name Dennis Ritchie
79int main() char name30 printf("Enter
name ") gets(name) //Function to read
string from user. printf("Name ")
puts(name) //Function to display string.
return 0
Enter name Tom Hanks Name Tom Hanks
80Name Addr Content
Lecture
Lecture
815.6 Sorting an array
0
2
1
3
4
5
6
3
1
9
7
2
82Selection Sort (solution 1)
- void selection_sort(double x, int n)
-
- int k,j,m
- double temp
- for(k0 kltn-2 k)
- m k
- for(jm1 jltn-1 j)
- if(xj lt xm)
- m j
- temp xk
- xk xm
- xm temp
-
-
m find_min_pos(x, n, k)
swap(x, k, m)
83Selection Sort (solution 2)
- void selection_sort(double x, int n)
-
- int k, m
- for(k0 kltn-2 k)
- m find_min_pos(x, n, k)
- swap(x, k, m)
-
-
84Selection Sort contd
- int find_min_pos(double x, int n, int k)
-
- int j
- int mk
- for (jm1 iltn-1 j)
- if (xj lt xm)
- m j
- return(m)
-
85Selection Sort contd
void swap(double x, int k, int m) double
temp temp xk xk xm xm
temp return
86Reverse an array
0
2
1
3
4
5
6
3
1
9
7
2
2
7
9
1
3
6
87Reverse an Array
- void reverse(double x, int n)
-
- int i0, jn-1
- while (iltj)
- swap(x,i,j)
- i i 1
- j j - 1
-
- return
88Merge two sorted array
- Assume we have A and B arrays containing sorted
numbers - For example
- A 3, 5, 7, 9, 12
- B 4, 6, 10
- Merge these two arrays as a single sorted array
C, for example - C 3, 4, 5, 6, 7, 9, 10, 12
89Name Addr Content
Lecture
Lecture
905.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
91Unordered list linear search
- int search1(int x, int n, int value)
-
- int i
- for(i0 i lt n i)
- if (xi value)
- return i
-
- return(-1)
-
92Ordered list linear search
- int search2(int x, int n, int value)
-
- int i
- for(i0 i lt n i)
- if (xi value)
- return i
- else if (xi gt value)
- break
-
- return(-1)
93Linear Search - Tradeoffs
- Benefits
- Easy algorithm to understand
- Array can be in any order
- Disadvantages
- Inefficient (slow) for array of N elements,
examines N/2 elements on average for value in
array, N elements for value not in array
94Binary Search
- Requires array elements to be in order
- Divides the array into three sections
- middle element
- elements on one side of the middle element
- elements on the other side of the middle element
- If the middle element is the correct value, done.
Otherwise, go to step 1. using only the half of
the array that may contain the correct value. - Continue steps 1. and 2. until either the value
is found or there are no more elements to examine
95Binary Search - Example
- Array numlist2 contains
- Searching for the the value 11, binary search
examines 11 and stops - Searching for the the value 7, linear search
examines 11, 3, 5, and stops
2 3 5 11 17 23 29
96Binary Search
Set first index to 0. Set last index to the last
subscript in the array. Set found to false. Set
position to -1. While found is not true and first
is less than or equal to last Set middle to
the subscript half-way between arrayfirst and
arraylast. If arraymiddle equals the
desired value Set found to true.
Set position to middle. Else If
arraymiddle is greater than the desired value
Set last to middle - 1. Else
Set first to middle 1. End If. End
While. Return position.
97int binarySearch(int array, int size, int
value) int first 0, // First
array element last size - 1, //
Last array element middle,
// Mid point of search position -1
// Position of search value bool found
false // Flag while (!found first
lt last) middle (first last) / 2
// Calculate mid point if (arraymiddle
value) // If value is found at mid
found true position
middle else if (arraymiddle gt
value) // If value is in lower half
last middle - 1 else first
middle 1 // If value is in upper
half return position
98Binary Search - Tradeoffs
- Benefits
- Much more efficient than linear search. For
array of N elements, performs at most log2N
comparisons - Disadvantages
- Requires that array elements be sorted
99Intersection 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
3 6 9 1 7 2
4 5 8
100Use arrays to represent A and B Hand example
A
6
1
2
C
101Solution
int intersection(int A,int B,
int C, int n) int i0, j0, k0
for(i0 i lt n i) for(j0 j lt n j)
if (AiBj) CkAi
k break
return(k)
102Another Solution
int intersection(int A, int B,
int C, int n) int i0, k0, elem
while (i lt n) elem Ai
if(find_count(B,n,elem) 1) Ck
elem k k 1 i i 1
return(k)
103What if A and B were sorted?
- Will the previous solution work?
- Yes, but we could find intersection set faster!
- How?
- See next slide
104int sorted_intersection(int A,int B,
int C, int n) int i0, j0,
k0 while( i lt n j lt n ) if
(AiBj) CkAi
k i j else if (Ai lt Bj)
i else / Ai gt Bj
/ j return(k)
105Exercise union or difference
- As in previous example suppose two sets are given
as arrays. - Find union and difference
- For example
- A3,4,5 and B2,3,5,7
- A U B 2,3,4,5,7
- A B 4
- B A 2,7