Title: Arrays
1Arrays
- A data structure (vector) with many elements of
the same type - A common name where individual elements are
accessed by an index inside - Declartion
- int list25, a10 / 10 elements in a
referenced by - a0,
a1,., a9 / - double x20
2example
/ Example of a simple list of integers
/ include ltstdio.hgt int main(void) int
res10 / Note! index 0..9 / int i for
(i0ilt9i) resi 10-i
printf("resdd\n",i,resi) return 0
3Initialization
- The elements can be initialized at declaration
- int res1010,9,8,7,6,5,4,3,2,1
- If the initializing list is shorter, the rest of
the elements are 0 int res100 / all
elements are initialized to 0 / - The number of elements can be omitted if all
elements in the array are initialized at
declaration - int res10,9,8,7 / 4 elements with index
0..3 /
4Indexing
- arraynameintegral expression
- Where integral expression is evaluated to an
integer value (int or char) - Important to keep the integral expression inside
the range of the indeces ( see Table 7.2 on page
310) - An array element can be used wherever it is legal
to use a variable of the data type in question - Ex. 1 double x10
- int n
- printf(How many elements should you type
(lt11) ) - scanf(d, n) / should be validated! /
- for (i0 iltn i)
- scanf(lf, xi)
5Figure 7.2 Program to Print a Table of
Differences / Computes the mean and standard
deviation of an array of data and displays
the difference between each value and the mean.
/ include ltstdio.hgt include ltmath.hgt define
MAX_ITEM 8 / maximum number of items in list
/ int main(void) double xMAX_ITEM, / data
list / mean, / mean (average) of
the data / st_dev, / standard
deviation of the data / sum, /
sum of the data / sum_sqr / sum of
the squares of the data / int i /
Gets the data / printf("Enter d numbers
separated by blanks\ngt ", MAX_ITEM) for
(i 0 i lt MAX_ITEM i)
scanf("lf", xi)
6 / Computes the sum and the sum of the squares
of all data / sum 0 sum_sqr 0
for (i 0 i lt MAX_ITEM i)
sum xi sum_sqr xi
xi / Computes and prints the
mean and standard deviation / mean sum /
MAX_ITEM st_dev sqrt(sum_sqr / MAX_ITEM
- mean mean) printf("The mean is
.2f.\n", mean) printf("The standard
deviation is .2f.\n", st_dev) /
Displays the difference between each item and the
mean / printf("\nTable of differences
between data values and mean\n")
printf("Index Item Difference\n")
for (i 0 i lt MAX_ITEM i)
printf("3d4c9.2f5c9.2f\n", i, ' ', xi, '
', xi - mean) return
(0)
7Array names as formal parameters in functions
Single subscripted arrays as formal parameters
to a function are declared as in Fig. 7.4 (HOW
TO CALL IT?)
Figure 7.4 Function fill_array / Sets all
elements of its array parameter to in_value.
/ void fill_array (int list, / output -
list of n integers / int n,
/ input - number of list elements /
int in_value) / input - initial value /
int i / array subscript and loop
control / for (i 0 i lt n i)
listi in_value Introduce the concept
of int list
8Returning an Array Result
- A function cant return a complete array but it
can return a pointer to an array - Another solution is to use an array name as
output parameter (see Fig. 7.8)
Figure 7.8 Function to Add Two Arrays / Adds
corresponding elements of arrays ar1 and ar2,
storing the result in arsum. Processes first
n elements only. / void add_arrays(const double
ar1, / input - / const double
ar2, / arrays being added /
double arsum, / output - sum of
corresponding
elements of ar1 and ar2 / int n)
/ input-number of element pairs summed /
int i / Adds corresponding elements of
ar1 and ar2 / for (i 0 i lt n i)
arsumi ar1i ar2i
9Dynamic allocation of arrays
- We can allocate space (memory cells) for an array
by using calloc() - Syntax double num_list
-
- num_list (double ) calloc(list_size, sizeof
(double)) - Calloc() returns a pointer to void that value
should be cast to a pointer which points to the
data type in question - Normally the allocated space should be freed
before the program is ended. Use function
free(pointername) - Include ltstdlib.hgt to get access to calloc() and
free() - Ex. 1 write function add_arrays() such that it
returns a pointer to the new array that contains
the sum of the two arrays which are pointed to by
the two input parameters
10Figure 7.8 revised Function to Add Two
Arrays / Adds corresponding elements of
arrays ar1 and ar2, storing the result in
ar_sum. Processes first n elements only.
/ include ltstdlib.hgt double add_arrays2(const
double ar1, / input - / const
double ar2, / arrays being added /
int n) / input-number of element pairs
summed / int i double ar_sum ar_sum
(double ) calloc(n, sizeof(double)) /
Adds corresponding elements of ar1 and ar2 /
for (i 0 i lt n i) ar_sumi
ar1i ar2i return (ar_sum)
11How to call add_array() and add_arrays2()
void add_arrays(const double ar1,const double
ar2, double arsum, int n) double
add_arrays2(const double ar1,const double
ar2,int n) include ltmath.hgt include
ltstdlib.hgt int main(void) double list120,
list220, add_lists20, sum_lists int n5,
i / generate 10 random numbers, 5 in each
array list1 and list2 / for (i0 ilt5 i)
list1i (double) rand()/(double)RAND_MAX10
list2i rand()/(double)RAND_MAX10
add_arrays(list1, list2, add_lists, n)
sum_lists add_arrays2(list1, list2, n)
printf(\nLIST1 LIST2 ADD_ARRAYS
ADD_ARRAYS2\n) for (i0 ilt5 i)
printf(8.4f8.4f12.4f15.4f\n,
list1i,list2i,(add_listsi),sum_listsi)
free(sum_lists) return 0
12Result from run
LIST1 LIST2 ADD_ARRAYS
ADD_ARRAYS2 5.1387 1.7573 6.8960
6.8960 3.0863 5.3453 8.4317
8.4317 9.4763 1.7173 11.1936
11.1936 7.0223 2.2642 9.2865
9.2865 4.9477 1.2470 6.1946
6.1946
13Sorting
- A list of n integers list1, list2, list3, ,
listn . The elements should be ordered such that
listi lt listi1 i1,2,n-1 - Algoritm BubbelSort(lista,n) /Lightest value
bubbles to top/ - bytt true
- last n
- repeat
- for i1 to last-1 do / push the heaviest
value to the bottom / - begin
- if list i gt listai1
- then begin
- exchange values
- bytt true
- end
- end
- last last - 1
- until not bytt
14Code
void bubble_sort(int list, int n) int i,
last, bytt, temp do bytt 0 / logical
false / for (i0 i lt last-1 i)
if (listi gt listi1) temp
listi listi listi1
listi1 temp bytt 1 / logical
true / / end of if / / end of
for / last last - 1 while (bytt)
15Strings
- An array of characters (char)
- Simple initialization char course_name
Programmeringsteknik the same as char
course_name P,r,o,g,r,a,m,m,e
,r,i,n,g,s,t,e,k,n,i,k,\0
- Note \0 is automatically stored in the first
form
16Strings
- void main(void)
-
- char strng10 / Note! indeces 0..9 /
- int i
- printf("--------- example 1 ---------\n\n")
- printf("Type a string ")
- scanf("s", strng) fflush(stdin)
- printf("--gtslt--\n\n", strng)
- printf("Type another string ")
- gets(strng)
- printf("--gtslt--\n", strng)
-
17Run
----------- example 1 ----------- Type a string
like this --gtlikelt-- Type a string like
this --gtlike thislt--
What will happen if we type more than 10
charcters? In the second scanf()?
18String functions
- include ltstring.hgt
- strcat(string1, string2) concatenates two
strings, resulting string is returned (also in
string1) - strcmp(string1, string2) compares string1 to
string2, value (-,0,) is returned if string1 is
lexiographically lt, , gt string2 - strcpy(string1, string2) copies string2 to
string1 , a pointer to string1 is returned - strlen(string) number of characters before \0 is
returned
19strcat
- include ltstring.hgt
- void main(void)
-
- char str1 "First string"
- char str2 "Second!"
- char str3 "Third"
- printf("--------- example 2 ---------\n\n")
- printf("--gtslt--\n",strcat(str1,str2))
- printf("--gtslt--\n",str1)
- printf("--gtslt--\n",strcat(str3,str1))
- printf("--gtslt--\n",str3)
- printf("------- concatenating -------\n\n")
-
20Run
----------- example 2 ----------- --gtFirst
stringSecond!lt-- --gtFirst stringSecond!lt-- --gtThir
dFirst stringSecond!lt-- --gtThirdFirst
stringSecond!lt-- --------- concatenating
---------