Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Chapter 6 - Arrays
6.1
Introduction
Arrays
Structures of related data items
Static entity same size throughout program
Dynamic data structures discussed in Chapter 12
6.2
Arrays
Array
Group of consecutive memory locations
Same name and type
Format:
arrayname[ position number ]
Name of array
(Note that all
elements of this
array have the
same name, c)
c[0]
-45
c[1]
c[2]
c[3]
72
c[4]
1543
c[5]
-89
c[6]
c[7]
62
c[8]
-3
c[9]
c[10]
6453
c[11]
78
c[ 0 ], c[ 1 ]...c[ n 1 ]
Position number
of the element
2000 Prentice
within array
c Hall, Inc.
All rights reserved.
6.2
Arrays
6.3
Declaring Arrays
Examples:
int c[ 10 ];
float myArray[ 3284 ];
6.4
Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
1
2
3
4
5
6
7
#define SIZE 10
Outline
1. Initialize array
int main()
{
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 }
2. Loop
3. Print
printf( "\n" );
}
return 0;
Element
0
1
2
3
4
5
6
7
8
9
Value
19
3
15
7
11
9
13
5
17
1
Histogram
*******************
***
***************
*******
***********
*********
*************
*****
*****************
*
Outline
Program Output
6.4
Character arrays
String first is really a static array of characters
Character arrays can be initialized using string literals
char string1[] = "first";
Null character '\0' terminates strings
string1 actually has 6 elements
It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
2
3
Outline
4
5
int main()
10
1. Initialize strings
2. Print strings
int i;
10
11
12
13
14
string1, string2 );
15
16
17
3. Print string
18
19
printf( "\n" );
20
return 0;
21 }
Enter a
string1
string2
string1
H e l l
Program Output
11
6.5
Passing arrays
To pass an array argument to a function, specify the name of
the array without any brackets
int myArray[ 24 ];
myFunction( myArray, 24 );
Array size usually passed to function
12
6.5
Function prototype
void modifyArray( int b[], int arraySize );
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Outline
13
1. Function definitions
/* appears strange */
2. Pass array to a
function
int main()
{
int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i;
printf( "Effects of passing entire array call "
"by reference:\n\nThe values of the "
"original array are:\n" );
for ( i = 0; i <= SIZE - 1; i++ )
printf( "%3d", a[ i ] );
printf( "\n" );
modifyArray( a, SIZE ); /* passed call by reference */
printf( "The values of the modified array are:\n" );
for ( i = 0; i <= SIZE - 1; i++ )
printf( "%3d", a[ i ] );
33
Outline
14
int j;
37
38
39
40 }
41
42 void modifyElement( int e )
43 {
44
45 }
Effects of passing entire array call by reference:
The values of
0 1 2 3
The values of
0 2 4 6
Program Output
15
6.6
Sorting Arrays
Sorting data
Important computing application
Virtually every organization must sort some data
Repeat
Example:
original: 3 4 2 6 7
pass 1:
3 2 4 6 7
pass 2:
2 3 4 6 7
Small elements "bubble" to the top/ large elements at the last
6,
Second Pass
2,
Third Pass
2,
Fourth Pass
2,
Fifth Pass
2,
Sixth Pass
2,
2,
6,
6,
6,
3,
3,
9,
9,
9,
3,
6,
6,
11, 9, 3, 7,
9, 3, 7, 11,
3, 7, 9, 11,
7, 9, 9, 11,
7, 9, 9, 11,
7, 9, 9, 11,
12
12
12
12
12
12
This
Thispass
passno
noexchanges
exchangesare
aremade
madeso
sothe
thealgorithm
algorithmknows
knowsthe
thelist
listisis
sorted.
sorted. ItItcan
cantherefore
thereforesave
savetime
timeby
bynot
notdoing
doingthe
thefinal
finalpass.
pass. With
With
other
otherlists
liststhis
thischeck
checkcould
couldsave
savemuch
muchmore
morework.
work.
6.7
17
1, 2, 3, 4, 5
3 is the median
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int main()
{
int frequency[ 10 ] = { 0
int response[ SIZE ] =
{ 6, 7, 8, 9, 8, 7, 8,
7, 8, 9, 5, 9, 8, 7,
6, 7, 8, 9, 3, 9, 8,
7, 8, 9, 8, 9, 8, 9,
6, 7, 8, 7, 8, 7, 9,
7, 8, 9, 8, 9, 8, 9,
5, 6, 7, 2, 5, 3, 9,
7, 8, 9, 6, 8, 7, 8,
7, 4, 4, 2, 5, 3, 8,
4, 5, 6, 1, 6, 5, 7,
1. Function prototypes
1.1 Initialize array
2. Call functions mean,
median, and mode
};
9,
8,
7,
7,
8,
7,
4,
9,
7,
8,
mean( response );
median( response );
mode( frequency, response );
return 0;
}
Outline
18
8, 9,
7, 8,
8, 7,
8, 9,
9, 2,
5, 3,
6, 4,
7, 8,
5, 6,
7 };
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Outline
Mean", "********" );
19
3. Define function
mean
3.1 Define function
median
3.1.1 Sort Array
3.1.2 Print middle
element
65 }
66
67 void mode( int freq[], const int answer[] )
68 {
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
Outline
3.2 Define function
mode
3.2.1 Increase
frequency[]
depending on
response[]
printf( "\n%s\n%s\n%s\n",
"********", "
Mode", "********" );
20
printf( "%s%11s%19s\n\n%54s\n%54s\n\n",
"Response", "Frequency", "Histogram",
"1
1
2
2", "5
0
5
0
5" );
95
printf( "\n" );
96
}
97
98
printf( "The mode is the most frequent value.\n"
99
"For this run the mode is %d which occurred"
100
" %d times.\n", modeValue, largest );
101 }
102
103 void bubbleSort( int a[] )
104 {
105
int pass, j, hold;
106
107
for ( pass = 1; pass <= SIZE - 1; pass++ )
108
109
for ( j = 0; j <= SIZE - 2; j++ )
110
111
if ( a[ j ] > a[ j + 1 ] ) {
112
hold = a[ j ];
Bubble sort:
113
a[ j ] = a[ j + 1 ];
swap them.
114
a[ j + 1 ] = hold;
115
}
116 }
117
118 void printArray( const int a[] )
119 {
120
int j;
121
122
for ( j = 0; j <= SIZE - 1; j++ ) {
123
124
if ( j % 20 == 0 )
125
printf( "\n" );
Outline
21
126
127
128
Outline
printf( "%2d", a[ j ] );
22
129 }
********
Mean
********
The mean is the average value of the data
items. The mean is equal to the total of
all the data items divided by the number
of data items (99). The mean value for
this run is: 681 / 99 = 6.8788
Program Output
********
Median
********
The unsorted array of responses is
7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8
6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9
6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3
5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8
7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7
The sorted
1 2 2 2 3
5 6 6 6 6
7 7 7 7 7
8 8 8 8 8
9 9 9 9 9
array
3 3 3
6 6 6
7 7 7
8 8 8
9 9 9
is
4 4
6 6
7 7
8 8
9 9
4
7
7
8
9
4
7
7
8
9
4
7
7
8
9
5
7
8
8
9
5
7
8
8
9
5
7
8
8
9
5
7
8
8
9
5
7
8
8
9
5
7
8
8
9
5
7
8
8
********
Mode
********
Response
Outline
Frequency
Program Output
Histogram
5
23
1
0
1
5
2
0
2
5
1
1
*
2
3
***
3
4
****
4
5
*****
5
8
********
6
9
*********
7
23
***********************
8
27
***************************
9
19
*******************
The mode is the most frequent value.
For this run the mode is 8 which occurred 27 times.
6.8
24
Simple
Compare each element of array with key value
Useful for small and unsorted arrays
6.8
25
10 11 45
key < 50
50 59 60 66 69 70 79
mid
10 11 45
mid
[3] [4] [5]
10 11 45
key = 11
mid
27
CSE202: Lecture 16
CSE202: Lecture 16
Two-dimensional Arrays
A two-dimensional array consists of both rows and
columns of elements. It is essentially a matrix.
To declare a two-dimensional array, we merely use
two sets of square brackets.
The first contains the number of rows
The second contains the number of columns
//Creates a 2D array with 3 rows and 4 columns
int vals[3][4];
29
Indices in 2D arrays
Assume that the two dimensional array called val is
declared and looks like the following:
val
Row 0
16
52
Row 1
15
27
Row 2
14
25
10
CSE202: Lecture 16
Using 2D arrays
Just like 1D arrays, once you have specified the
index, you are just working with a single variable
of the given data type.
Assignments and usage is still the same:
sumRow0 = val[0][0] + val[0][1] + val[0][2] +
val[0][3];
//assigns 72 to cell at row 2, column 3
val[2][3] = 72;
Initializing 2D arrays
You can use additional braces to indicate when rows start
and end, but you dont have to do that.
int val[3][4] = { {8,16,9,52},
{3,15,27,6},
{14,25,2,10}
};
Or
int val[3][4] = {8,16,9,52,
3,15,27,6,
14,25,2,10};
More on 2D arrays
Initialization of 2D arrays is done in row order.
2D arrays work well with (for) loops like 1D
arrays. However, to access all elements, typically
you will need nested loops for 2D arrays. Can you
see why?
Example Program
...
int main()
{
const int NUM_ROW(3);
const int NUM_COL(4);
int vals[NUM_ROW][NUM_COL] = { {11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34} };
// output the array
for (int row = 0; row < NUM_ROW; row++)
{
for (int col = 0; col < NUM_COL; col++)
{
cout << vals[row][col] << " ";
}
cout << endl;
}
...
The Ohio State University
Example Program
...
int vals[NUM_ROW][NUM_COL] = { {11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34} };
// output the array
for (int row = 0; row < NUM_ROW; row++)
{
for (int col = 0; col < NUM_COL; col++)
{
cout << vals[row][col] << " ";
}
cout << endl;
}
...
> array2DExample.exe
11 12 13 14
21 22 23 24
31 32 33 34
matrixAdd.cpp
...
int main()
{
const int NUM_ROWS(3);
const int NUM_COLS(2);
matrixAdd.cpp (2)
...
// display A
cout << "A =" << endl;
for (int i=0; i<NUM_ROWS; i++)
{
for (int j=0; j<NUM_COLS; j++)
{
cout << "
" << A[i][j] << " ";
}
cout << endl;
}
cout << endl;
...
6.9
Multiple-Subscripted Arrays
a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array
name Row subscript
6.9
Multiple-Subscripted Arrays
Initialization
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
Initializers grouped by row in braces
If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Referencing elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Outline
41
1. Initialize variables
1.1 Define functions to
take double scripted
arrays
Each row is a particular student,
each column is the grades on the
1.2 Initialize
exam.
studentgrades[][]
2. Call functions
minimum, maximum,
and average
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Outline
42
3. Define functions
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
int i, total = 0;
Outline
43
3. Define functions
[0]
[1]
[2]
[3]" );
Outline
[1]
68
87
90
[2]
86
89
86
[3]
73
78
81
44
Program Output
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75
45
Programs to try
Find the maximum element in an array.
Count the no. of vowels, consonants, spaces in the
given text.
Find the row sum , column sum in the given
matrix.
Find the addition, subtraction, Multiplication of
two matrices
Write the function extract a substring from a
string.
Convert an integer to binary value
46
read student scores (int) from the keyboard, get the best score, and then assign grades
based on the following scheme:
Grade is A if score is >= best10;
Grade is B if score is >= best20;
Grade is C if score is >= best30;
Grade is D if score is >= best40;
Grade is F otherwise.
Strings
48
49
50
51
DECLARATION - VOLATILE
Declaring volatile variable. For example, volatile integer.
volatile int Vint;
int volatile Vint;
Declaring pointers to volatile variables.
volatile int * Vintptr; // pointer to volatile integer.
int volatile * Vintptr;
Declaring volatile pointer to non volatile variables.
int * volatile Vptr; // volatile pointer to integer.
Declaring volatile pointer to a volatile variable.
int volatile * volatile Vptr; // volatile pointer to volatile integer.
Using typedef example.
typedef volatile int Vint
52
const int *p
p is a pointer to an int and where that pointer points
can not be changed by the programmer whereas
Volatile int *q
q is a pointer to an int and where that pointer points could
be changed by someone other than the programmer so the
compiler makes no assumptions about that pointer.
53
Preprocessor directives
Difference between
# define n 10
no symbol in symbol table , macro
const int n 10
an identifier in symbol table