Вы находитесь на странице: 1из 50

Arrays and Records

Overview
• To solve many programming problems, it is more
efficient to group data items together in main memory
than to allocate an individual memory cell for each
variable.
• C allows a programmer to group such related data items
together into a single composite data structure.
• In this chapter, we look at one such data structure: the
array, which is a collection of data items of the same
type.
INTRODUCTION TO ARRAYS, SEQUENTIAL
ACCESS, AND ARRAY ARGUMENTS
(CHAPTER 7.1-7.5)
Declaring and Referencing Arrays
• An array is a collection of two or more adjacent memory cells,
called array elements.
• Declaration
double x[8];
– instructs the compiler to associate eight memory cells with
the name x
– these memory cells will be adjacent to each other in
memory
– each element of array x may contain a single type double
value
– so, eight double number may be stored and referenced
using the array name x
Declaring and Referencing Arrays
• To process the data stored in an array, we reference each
individual element by specifying the array name and
identifying the element desired (e.g. element 3 of array x).

• Subscripted variable
x[n];
may be used to reference the n-th element of array x.

• Array subscript is the integer enclosed in brackets after the


array name, specifying which array element to access.
Declaring and Referencing Arrays
• To process the data stored in an array, we reference each
individual element by specifying the array name and
identifying the element desired (e.g. element 3 of array x).

• Subscripted variable
x[n];
may be used to reference the n-th element of array x.

• Array subscript is the integer enclosed in brackets after the


array name, specifying which array element to access.
Example 7.1
double x[8];
Array x

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]


16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5

Statements that manipulate array x

printf(“%.lf”, x[0]);
x[3] = 25.0;
sum = x[0] + x[1];
sum += x[2];
x[3] += 1.0;
x[2] = x[0] + x[1];
Example 7.1
double x[8];
Array x

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]


16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5

Statements that manipulate array x

printf(“%.lf”, x[0]); // Display the value of x[0], which is 16.0


x[3] = 25.0;
sum = x[0] + x[1];
sum += x[2];
x[3] += 1.0;
x[2] = x[0] + x[1];
Example 7.1
double x[8];
Array x

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]


16.0 12.0 6.0 25.0 2.5 12.0 14.0 -54.5

Statements that manipulate array x

printf(“%.lf”, x[0]);
x[3] = 25.0; // Stores the value 25.0 in x[3]
sum = x[0] + x[1];
sum += x[2];
x[3] += 1.0;
x[2] = x[0] + x[1];
Example 7.1
double x[8];
Array x

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]


16.0 12.0 6.0 25.0 2.5 12.0 14.0 -54.5

Statements that manipulate array x

printf(“%.lf”, x[0]);
x[3] = 25.0;
sum = x[0] + x[1]; // Stores x[0] + x[1], 28.0, in variable sum
sum += x[2];
x[3] += 1.0;
x[2] = x[0] + x[1];
Example 7.1
double x[8];
Array x

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]


16.0 12.0 6.0 25.0 2.5 12.0 14.0 -54.5

Statements that manipulate array x

printf(“%.lf”, x[0]);
x[3] = 25.0;
sum = x[0] + x[1];
sum += x[2]; // Adds x[2] to sum, 28.0 + 6.0 = 34.0
x[3] += 1.0;
x[2] = x[0] + x[1];
Example 7.1
double x[8];
Array x

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]


16.0 12.0 6.0 26.0 2.5 12.0 14.0 -54.5

Statements that manipulate array x

printf(“%.lf”, x[0]);
x[3] = 25.0;
sum = x[0] + x[1];
sum += x[2];
x[3] += 1.0; // Adds 1.0 to x[3], 25.0 + 1.0 = 26.0
x[2] = x[0] + x[1];
Example 7.1
double x[8];
Array x

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]


16.0 12.0 28.0 26.0 2.5 12.0 14.0 -54.5

Statements that manipulate array x

printf(“%.lf”, x[0]);
x[3] = 25.0;
sum = x[0] + x[1];
sum += x[2];
x[3] += 1.0;
x[2] = x[0] + x[1]; // Stores x[0] + x[1], 16.0 + 12.0 = 28.0 in
x[2]
Array Initialization
• In the following statement, we initialize a 25-element
array with the prime numbers less than 100.
int prime_lt_100[] = {2, 3, 5, 7, 11, 13, 17,
19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97};

• Array element prime_lt_100[24] is 97


Storing a String in an Array of
Characters
• If the list is long, you can use string instead of an
initialization list
char vowels[] = “This is a long string”;

• In this case, vowels[0] stores ‘T’, vowels[1]


stores ‘h’, and so on.
Array Subscripts
• Array subscript is used to differentiate between the
individual array elements and to specify which array
element is to be manipulated.
• The value of this subscript must be an integer
between 0 and one less than the declared size of the
array.
• Example:
x[0] x[1] x[2] x[3] x[4] x[5] x[6]
Array Subscripts
• Example: Array x
x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]

16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5

Statement Explanation
i = 5;
printf(“%d %.lf”, 4, x[4]); Displays 4 and 2.5 (value of x[4])
printf(“%.lf”, x[i] + 1) Display 13.0 (value of x[5] plus 1)
printf(“%.lf”, x[i +1]) Display 14.0 (value of x[6])
printf(“%.lf”, x[i] + i) Display 17.0 (value of x[5] plus 5)
printf(“%.lf”, x[2*i - 3]) Display -54.5 (value of x[7])
Array Subscripts
• Example: Array x
x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]

16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5

Statement Explanation
i = 5;
printf(“%d %.lf”, x[(int)x[4]]); Displays 6.0 (value of x[2])
printf(“%.lf”, x[i++]) Display 12.0 (value of x[5]) then
assign 6 to i
printf(“%.lf”, x[--i]) Assign 5 (6-1) to i and then display
12.0 (value of x[5])
Using for Loops for Sequential Access
• In C, we can process the elements of an array in
sequence using an indexed for loop, a counting loop
whose loop control variable runs from 0 to one less
than the array size.
• Example: (assume SIZE has been defined to be 11)
int square[SIZE], i;
for (i=0; i < SIZE; i++)
square[i] = i * i;

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

0 1 4 9 16 25 36 49 64 81 100
Using for Loops for Sequential Access
• Statistical Computations Using Arrays
One common use of arrays is for storage of a
collection of related data values, which are used to
perform some simple statistical computations.
Example:

sum = 0;
for (i = 0; i < MAX_ITEM; i++){
sum += x[i];
}
Using for Loops for Sequential Access

sum_sqr = 0;
for (i = 0; i < MAX_ITEM; i++){
sum_sqr += x[i] * x[i];
}

st_dev = sqrt(sum_sqr / MAX_ITEM – mean * mean);


Using Array Elements as Function
Arguments
• The call
printf(“%3d%4c%9.2f%5c%9.2f\n”, i, ‘ ‘,
x[i], ‘ ‘, x[i] - mean);
uses array element x[i] as an input argument to
function printf.

• The call
scanf(“%lf”, &x[i]);
uses array element x[i] as an output argument to
function scanf.
Using Array Elements as Function
Arguments
• Example:
The function prototype below shows one type double input
parameter (arg_1) and two type double * output parameters
(arg2_p and arg3_p)

do_it(double arg_1, double *arg2_p, double *arg3_p);

If x is declared as an array of type double elements in the


calling module, the statement
do_it(x[0], &x[1], &x[2]);
uses the first three elements of array x as actual arguments.
Array Arguments
• Besides passing individual array elements to functions, we can
write functions that have arrays as arguments.

• Formal Array Parameters


The parameter declaration does not indicate how many
elements are in the array. Thus, we have the flexibility to pass
to the function an array of any number of integers.

void fill_array(int list[], int n, int val)


{
...
}
Array Arguments
• Argument Correspondence for Array Parameters
To call function fill_array, you must specify the actual
array argument, the number of array elements, and the value
to be stored in the array.

If y is an array with ten type int elements, the function call

fill_array(y, 10, num);

stores the value of num in the ten elements of array y.


Array Arguments
• Argument Correspondence for Array Parameters
The call below

fill_array(x, 5, 1);

would execute exactly like the call below.

fill_array(&x[0], 5, 1);
Array Arguments
• Argument Correspondence for Array Parameters
In the declaration for function fill_array, we can use
either parameter declaration:

int list[]
int *list

The first tells us that the actual argument is an array.


However, the second declaration would be equally valid for
an integer array parameter as C passes an array argument py
passing the address of its initial element.
Array Arguments
• Arrays as Input Arguments
ANSI C provides a qualifier that we can include in the
declaration of the array formal parameter in order to notify
the C compiler that the array is only an input to the function
and that the function does not intend to modify the array.

Example:
If x is a five-element array type int values, statement
x_large = get_max(x,5)
causes function get_max to search array x for its largest
element; this value is returned and stored in x_large.
Array Arguments
• Returning an Array Result
In C, defining a function of the variety modeled in the figure
below requires use of an output parameter to send the result
array back to the calling module.

input array (output


parameters function
result parameter)

When we use simple output parameters, the calling function


must declare variables into which the function subprogram
will store its results.
Array Arguments
• Returning an Array Result
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<n; i++)


arsum[i] = ar1[i] + ar2[i];
}
Array Arguments
• Partially Filled Arrays
To reuse an array for processing more than one data set, the
programmer often declares an array large enough to hold the largest data
set anticipated.
int main(void) {
double arr[A_SIZE];
int in_use, i;

fill_to_sentinel(A_SIZE, SENT, arr, &in_use);


printf(“List of data values\n”);
for (i=0; i<in_use; i++)
printf(“%l3.3f\n”, arr[i]);
return (0);
}
SEARCHING AND SORTING AN
ARRAY (CHAPTER 7.6)
Array Search
• To search an array, we need to know the search target and search by
examining in turn each array element using a loop and by testing whether
the element matches the target.
• Algorithm
o Assume the target has not been found.
o Start with the initial array element.
o repeat while the target is not found and there are more array elements.
✔ if the current element matches the target
❖ Set a flag to indicate that the target has been found.
else
❖ Advance to the next array element.
o if the target was found
✔ Return the target index as the search result.
else
✔ Return -1 as the search result.
Array Search
• Example
int search(const int arr[], int target, int n){
int i, found = 0, where;

i=0;
while (!found && i < n){
if (arr[i] == target)
found = 1;
else
++i;
}
if (found)
where = i;
else
where = NOT_FOUND;
return (where);
}
Sorting an Array
• Algorithm
o for each value of fill from 0 to n-2
✔ Find index_of_min, the index of the
smallest element in the unsorted
subarray list[fill] through list[n-1].
✔ If fill is not the position of the smallest
element (index_of_min)
❖ Exchange the smallest element with
the one at position fill.
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


74 45 83 16

fill is 0.
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


74 45 83 16

fill is 0.
Find the smallest element in subarray
list[1] through list[3] and swap it with
list[0].
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


74 45 83 16

fill is 0.
Find the smallest element in subarray
list[1] through list[3] and swap it with
list[0].
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


16 45 83 74

fill is 0.
Find the smallest element in subarray
list[1] through list[3] and swap it with
list[0].
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


16 45 83 74

fill is 1.
Find the smallest element in subarray
list[1] through list[3] and swap it with
list[1].
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


16 45 83 74

fill is 1.
Find the smallest element in subarray
list[1] through list[3] and swap it with
list[1].
No exchange needed.
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


16 45 83 74

fill is 2.
Find the smallest element in subarray
list[2] through list[3] and swap it with
list[2].
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


16 45 83 74

fill is 2.
Find the smallest element in subarray
list[2] through list[3] and swap it with
list[2].
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


16 45 74 83

fill is 2.
Find the smallest element in subarray
list[2] through list[3] and swap it with
list[2].
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


16 45 74 83

fill is 2.
Find the smallest element in subarray
list[2] through list[3] and swap it with
list[2].
Sorting an Array
• Trace of Selection Sort

[0] [1] [2] [3]


16 45 74 83
Sorting an Array
• Example

void select_sort(int list[], int n)


{
int fill, temp, index_of_min;

for (fill=0; fill<n-1; ++fill){


index_of_min = get_min_range(list, fill, n-1);

if (fill != index_of_min){
temp = list[index_of_min];
list[index_of_min] = list[fill];
list[fill] = temp;
}
}
}
PARALLEL ARRAYS, ENUMERATED
TYPES, AND MULTIDIMENSIONAL
ARRAYS (CHAPTER 7.7 & 7.8)
Parallel Arrays and Enumerated Types
• Parallel arrays are two or more arrays with
the same number of elements used for storing
related information about a collection of data
objects.
• Enumerated type is a data type whose list of
values is specified by the programmer in a
type declaration.
Multidimensional Arrays
• Multidimensional array is an array with two or more
dimensions.
• We will use two-dimensional arrays to represent
tables of data, matrices, and other two-dimensional
objects.
• A two-dimensional object that many are familiar
with is a tic-tac-toe board. The array declaration
char tictac[3][3];
allocates storage for a two-dimensional array
(tictac) with three rows and three columns.

Вам также может понравиться