Title: Arrays
1Arrays
- Simple data types use a single memory
- cell to store a variable int x
- A data structure is a composite of
- related data items stored under a same
- name. Array is one of such data structures.
- For example it is easier to write a program that
processes exam scores for a class by using an
array because all scores can be stored in one
area of the memory and can be accessed together.
2Declaring and Referencing Arrays
- Both name of the array and its number of cells
should be defined - For example double x8 instructs the compiler
to associate eight adjacent memory cells of
double type with the name of x. - Array subscript is a value or expression enclosed
in the brackets after array name, that shows an
array element. For example x3 means element 3
of array x.
3Declaring and Referencing Arrays
- The range of array subscript is from zero to one
less than the number of memory cells in the
array. - array subscript always starts from 0
- x0 x1 x2 x3 x4 x5 x6
x7
16.0
12.0
28.0
26.0
2.5
12.0
14.0
-54.0
same type
4Parallel Arrays
- Two or more arrays with the same number of
elements for storing related information - int idNUM_STUDENTS
- double gpaNUM_STUDENTS
-
5503
2.71
id0
gpa0
4556
3.09
id1
gpa1
5More on Array Declaration
- One or more arrays can be declared in one single
type declaration - int factor12, n, pins6
- Array can be initialized in the time of
declaration - int prime_1t_5 2,3,5
- It is same as initializing a variable when we
declare it int sum0
6Array Subscript
- Array subscript (or index)
- Can be a constant, integer variable, or integer
expression - x0 2 xi 5 x2 3 x
7 - C does NO bound checking
- Result of exceeding bounds is system dependent!
- Sometimes a runtime error is printed - but
sometimes subscript error may cause the side
effect - Only the existing elements in the array should be
referenced
7- i 5
- printf(.1f, xi)
- printf(.1f, xi 1)
- printf(.1f, xi i)
- printf(.1f, xi 1)
- printf(.1f, xi 2)
- printf(.1f, x(int)x4)
- printf(.1f, xi)
- printf(.1f, x--i)
- xi 1 xi
- xi 1 xi
8Using for Loops for Sequential Access
- counter variable starts from 0 to lt size of array
- define SIZE 11
- int squareSIZE, i
- for (i 0 i lt SIZE i)
- squarei i i
9Storing Input Values into the Array elements
- The variable i is using as control loop variable
and array subscript - define MAX_ITEM 11
- int xMAX_ITEM, i
- for (i 0 i lt MAX_ITEM i)
- scanf("lf", xi)
-
- output
parameter -
10Printing the Values of Array Elements
- define MAX_ITEM 11
- double xMAX_ITEM
- int i
-
- for (i 0 i lt MAX_ITEM i)
-
- printf (The dth element of array is
lf\n, i, xi ) -
- input
parameter
11- /
- 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 of data / - 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)
12- / 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)
13- Enter 8 numbers separated by blanks
- gt 16 12 6 8 2.5 12 14 -54.5
- The mean is 2.00.
- The standard deviation is 21.75.
- Table of differences between data values and mean
- Index Item Difference
- 0 16.00 14.00
-
14Using Array Elements as Function Arguments
- The formal parameter is a simple variable
- The actual parameter is the array name followed
by the particular index in - Example
- function prototype
- void do_it(double a1, double a2p, double a3p)
- In the function body
- a2p.
- a3p.
- function call
- do_it(x0, x1, x2)
15Array Arguments
- The argument declaration of the array does not
indicate the - size of the array because compiler does not
need to know that. - Array name with no subscript is a pointer to the
initial array element - / 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
-
- function call fill_array(y, 10,
num) - fill_array(x, 5, 1)
16Array Arguments
- int list also also can be used instead of int
list in a formal parameter list
Calling function data area
function fill_array data area
list
0
1
2
3
4
17Arrays as Input Arguments
- / Returns the largest of the first n values in
the array / - int get_max(const int list, int n)
- const indicates
that array is input and can not be modified - int i,
- cur_large / largest value so
far / - / First array element is largest so
far. / - cur_large list0
- /Compare remaining element to cur_large,
save the larger/ - for (i 1 i lt n i)
- if (listi gt cur_large)
- cur_large listi
- return (cur_large)
-
18Returning an Array Result
- In C it is not legal for a function return type
to be an array, - therefore, array should be used as output
parameter. - For example
- void add_arrays(const double ar1, const double
ar2, - double arsum, int n)
-
- int i
- / Adds corresponding elements of ar1 and
ar2 / - for (i 0 i lt n i)
- arsumi ar1i ar2i
-
- Call this function add_arrays(x, y, x_plus_y,
5)
19Partially Filled Array
- function
- void fill( int max, double sentinel, double x,
int size) - ..
- status scanf( f , data)
- while (status 1 data ! sentinel i
lt max) - xi data
- i
- status scanf( f , data)
-
- .
- size i
- ..
- main program
- double y 1000
- int used
- ..
- fill(1000,-1, y, used)
-
20Searching in the Array
- Linear search
- int search (const in arr, int target, int n)
-
- int i, found0, where
- i0
- while ( !found iltn)
- if (arri target)
- found i
- else
- i
-
- if (found)
- where i
- else where -1
- return (where)
-
21Strings
- printf (Average .2f, avg)
- define ERROR error
- Strings are arrays of char,
- For example
- char str40 value
- Terminated by \0 at str5
- Null character marks the end of string
- Array size must be more than string length plus
\0 - All C string handling functions ignore whatever
is stored in the cells following the null
character
22String
- Individual elements are char
- char course6 math"
m
a
t
h
\0
char letter1 A
A
\n
23Strings
- Array of Strings
- char month1210 January, February,
March, April, May, June, July,
August, September, October, November,
December - Input/output
- printf(Topic s\n, string_var)
- Right justification printf(10s\n, president)
president - Left justification printf(-10s\n,president)
president - scanf(sdsd, dept, course_num,
- days, time)
24- 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 COSC 2060 MWF 1410
- gt MATH 1270 TR 1800 (scanf skips white space
characters such blank - MATH 1270 meets TR at 1800
newline and tab)
25- Here namesi is an array but agesi is int
- define NUM_NAMES 30
- define NAME_LEN 25
- ..
- char names NUM_NAMESNAME_LEN
- int ages NUM_NAMES output parameters
- for (i0 iltNUM_NAMES i)
- scanf(sd, namesi, agesi
- printf(-35s d\n, namesi, agesi)
-
-
input parameters
26String assignment
- char str20
- str test it is wrong, we can only use in
- string initialization
- For doing that
- include ltstring.hgt
- strcpy(str,test)
- after that
- strlen(str) returns 4
27- strcpy(destination, source)
- strcpy(one_str, Test string 1)
- Overwrites characters in destination with
characters from source - Stops at \0 in source
- strlen(string)
- len strlen(one_string)
- Returns the number of characters in string
- Does not include \0
28String Comparison
- a lt b is true because the numeric code of a
is less than - numeric
code of character b - But for strings it is not that easy, For example
- thrill lt throw is true because first
non-matching characters - at position three are
compared - joy lt joyous is true because the first one
is shorter, and all - 3 initial characters of two strings
match with each others - strcmp(string1, string2)
- Compares one string to another
- Returns
- lt 0 if string1 lt string2
- 0 if string1 string2
- gt 0 if string1 gt string2
29Sentinel-controlled loop for string input
- printf("Enter list of words on as many lines as
you like.\n") - printf("Separate words by at least one
blank.\n") - printf("When done, enter s to quit.\n", SENT)
- for (scanf("s", word)
- strcmp(word, SENT) ! 0
- scanf("s", word))
-
- / process word /
-
30Case Study
- Problem A genetic engineer is developing a
program to identify palindromes of a certain
length in strings representing the nucleotide
sequences of a portion of a DNA molecule. - A-T-C-G-C-A-T-G-C-G-T-A-G
- T-A-G-C-G-T-A-C-G-C-A-T-C
31Case Study
- Analysis
- Constant STRANDSIZ 100
- Inputs char strand1STRANDSIZ,
- char strand2STRANDSIZ
- int palin_len
- Outputs index and value of each palindromic
sequence of length palin_len
32Case Study
- Design
- Algorithm
- 1. Get input data complementary strands and
palindrome length - 2. For each starting subscript of a substring of
the desired length - 2.1 if substring from strand1 matches the
reverse of corresponding substring of strand2 - 2.1.1 Print the position and two substrings
33Dynamic Allocation of Arrays
- In addition to stack heap is a second allocation
storage area for specific requests while program
is running. For example a pointer variable in
stack that points to - double nums_list the start of dynamic array
in heap - determines array
size in runtime - num_lis (double ) calloc(lsize, sizeof
(double)) - creates array elements that are initialized to
zero - finds the
number of required bytes
34- include ltstdio.hgt
- include ltstdlib.hgt / gives access to calloc /
- int
- main(void)
-
- char string1
- int array_of_nums
- int str_siz, num_nums, i
- printf("Enter string length and stringgt ")
- scanf("d", str_siz)
- string1 (char )calloc(str_siz, sizeof
(char)) - scanf("s", string1)
- printf("\nHow many numbers?gt ")
- scanf("d", num_nums)
- array_of_nums (int )calloc(num_nums,
sizeof (int)) - array_of_nums0 5
- for (i 1 i lt num_nums i)
- array_of_numsi array_of_numsi -
1 i - . . .
35Common Programming Errors
- Subscript range error with arrays
- Applying to the array name when array is used
as an argument of a function is wrong even if
array is output parameter but for using array
elements as output parameters is required - Note that int z as formal parameter can be used
both for array or an output int parameters - Overflow with strings in strcpy and scanf
- Not considering the null character in string size
- Intention to use dynamic array but forgetting
calloc function