View
218
Download
0
Category
Preview:
Citation preview
8/14/2019 an Array is a Collection of Data Elements Of
1/51
ARRAYS
8/14/2019 an Array is a Collection of Data Elements Of
2/51
Arrays
An array is a collection of data elements of same typein contiguous memory e.g. list of names, list of scores
Easier way to compare and use data than havingseparate variables for data elements
data_type identifier[size] int arr[3]
declares a one-dimensional array named arrwith spacefor 3 integer variables
Variables contiguous in memory; lowest address hasfirst value, next address has second variable value,and so on
8/14/2019 an Array is a Collection of Data Elements Of
3/51
Arrays
An individual variable within an array is called anelementof the array
The elements of an array are not named, and are
accessed by the arrays name and their position in thearray (indexingorsubcripting)
Index of first element is zero, index of lastelementissize-1 e.g. intarr[3] has variables arr[0],
arr[1] and arr[2] size has to be a positive constant (not variable)
i.e. cant do: int x = 3; int arr[x];
butcan do: int arr[3 * 2];
Number of bytes reserved with int arr[3]; ?
8/14/2019 an Array is a Collection of Data Elements Of
4/51
Arrays
An array is an indexed data structure
An array stores a collection of variables
All variables stored in an array are of the same
data type An individual variable within an array is called an
elementof the array
An element of an array is accessed using the arrayname and an index
The name of the array is the address of the first
element. The index is the offset
8/14/2019 an Array is a Collection of Data Elements Of
5/51
Declaring an array
data_typearray_name[size];
allocates memory forsize variables
index of first element is 0index of last element is size-1
size must be a constant
8/14/2019 an Array is a Collection of Data Elements Of
6/51
Declaring an Array
Example: int list[10]; allocates memory for 10 integer variables index of first element is 0 index of last element is 9
C++ does not perform any bounds checking on arrayslist[0]
list[1]
list[9]
8/14/2019 an Array is a Collection of Data Elements Of
7/51
Arrays
Arrays offer convenient means ofgrouping
together several related variables
One- dimensional arrays
type var_name[size]
int sample[10];
double d[30];
char ch[100];
8/14/2019 an Array is a Collection of Data Elements Of
8/51
Initializing Arrays
Arrays can be initialized at the time they are
declared.
Examples:double taxrate[3] = {0.15, 0.25, 0.3};
char word[] = hello; //word has size 6
char list[5] = {h,e,l,l,o};
//list of characters, not a string
double vector[100] = {0.0}; //assigns zero to all 100 elements
8/14/2019 an Array is a Collection of Data Elements Of
9/51
Initializing Arrays float f[5]={0.0, 1.0, 2.0, 3.0, 4.0};
//initializes f[0] to 0.0, f[1] to 1.0f[4] to 4.0 Or
float f[5]; f[0]=0.0; f[1]=1.0;
int a[10]={2}; //rest initialized to zero
cout
8/14/2019 an Array is a Collection of Data Elements Of
10/51
Initializing Arrays forloops used to initialize arrays
#include
int main(){int t, sample[10]; // this reserves 10 integer
elements
// load the arrayfor(t=0; t
8/14/2019 an Array is a Collection of Data Elements Of
11/51
Initializing Arraysint a[5];
Now an indexed variable like a[1] can be used anywhere that a variable of typeint can be used
int a[5];
cin >> a[4] >> a[2];
cout a[0];int max; max = a[3] + a[0]; cout next;
a[1]= next; cout
8/14/2019 an Array is a Collection of Data Elements Of
12/51
//Reads in 5 scores, displays max_score and shows//how much each score differs from max_score
int main()
{
const int SIZE = 5;
int i, score[SIZE], max_score;
cout score[i];
if (score[i] > max_score)
max_score=score[i];
}
cout
8/14/2019 an Array is a Collection of Data Elements Of
13/51
Initializing Arrays
Useful to give a constantname to thesize of array
/*const type modifier*/
const int NUM_EMPLOYEES = 10;
int salaries[NUM_EMPLOYEES];
for (int i=0; i < NUM_EMPLOYEES; i++)
cin >> salaries[i];
Advantage? Why not use a variable name?
Another way:
# define NUM_EMPLOYEES 10
And yes, sizeof(salaries); gives what?
8/14/2019 an Array is a Collection of Data Elements Of
14/51
Arrays Total size of an array in bytes?
Total bytes =
number of bytes in type * number of elements
e.g. int sample[10];
Has size in bytes = 10 * sizeof(int)
8/14/2019 an Array is a Collection of Data Elements Of
15/51
Initializing Arrays What is wrong with the following?
int num=10;
int iarray[num];
int size;
cin >> size;
int myarray[size];
double darray[5]={3.2, 4.5, 6.7, 324.0, 45.8, 23.1, 34.9}
8/14/2019 an Array is a Collection of Data Elements Of
16/51
Assigning One Array to Another
int a[10], b[10];
// ...
a = b; // error -- illegal
/*So how do we make the contents of one array
same as the other?*/
8/14/2019 an Array is a Collection of Data Elements Of
17/51
Assigning One Array to Another
int a[5], b[5];// ...a = b; // error illegal
Cannot assign one array to another; each element must becopied individually
const int ARRAY_SIZE = 5;int a[] = {10, 11, 12, 13, 14};
int main(){
int b[ARRAY_SIZE];for (int i=0; i < ARRAY_SIZE; ++i)
b[i] = a[i];
return 0;}
8/14/2019 an Array is a Collection of Data Elements Of
18/51
Assigning Values to an Array
Example
int list[10];
int count;
cin >> count;
for(int i=0; i> list[i];
What if count >9?
8/14/2019 an Array is a Collection of Data Elements Of
19/51
Summarize Arrays In C++ all arrays are stored in contiguous memory
locations
An individual element is accessed by use of an index.
An index describes theposition of an element within
an array.
In C++ all arrays have zeroas the index of their first
element.
8/14/2019 an Array is a Collection of Data Elements Of
20/51
Arrays: Min Max
int main()
{
const int SIZE = 10;
int i, min_value, max_value;
int list[SIZE];
for(i=0; i
8/14/2019 an Array is a Collection of Data Elements Of
21/51
Arrays
// find minimum value
min_value = list[0];
for(i=0; ilist[i])
{
min_value = list[i];}
}
cout
8/14/2019 an Array is a Collection of Data Elements Of
22/51
Arrays// find maximum value
max_value = list[0];
for(i=0; i
8/14/2019 an Array is a Collection of Data Elements Of
23/51
Arrays - No Bounds Checking
// An incorrect program. Do Not Execute!
int main()
{
int crash[10], i;
for(i=0; i
8/14/2019 an Array is a Collection of Data Elements Of
24/51
What is wrong with the following?
char name[5]=class";
int myarray[];
8/14/2019 an Array is a Collection of Data Elements Of
25/51
Arrays
int a[10] = {1,2,3,4,0,3,4,6,7,8};
int x=3; y=1;
cout
8/14/2019 an Array is a Collection of Data Elements Of
26/51
Sorting an Array
Lots of applications require sorting
Algorithm for sorting
S ti
8/14/2019 an Array is a Collection of Data Elements Of
27/51
Sorting an
Array
int main(void)
{
const int SIZE = 10;
double darray[SIZE] = {34, 5.6, 0.9, 345.7, 54.1, 23.5, 2.5, 6.78, 12.4, 13.9};
int i, j;
for (i=0; idarray[j])
{
double temp;
temp = darray[i];darray[i] = darray[j];darray[j] = temp;
}}
} //inplace sorting ?
return 0;}
8/14/2019 an Array is a Collection of Data Elements Of
28/51
Sorting an Array
// Using the bubble sort to order an array.
int main()
{
const int SIZE = 10;
int nums[SIZE];
int a, b, t;
// give the array some random initial values
for(t=0; t
8/14/2019 an Array is a Collection of Data Elements Of
29/51
Sorting an Array// This is the bubble sort.
for(a=1; a=a; b--)
{
if (nums[b-1] > nums[b]){ // if out of order exchange elements
t = nums[b-1];
nums[b-1] = nums[b];
nums[b] = t;
}
}
} // This is the end of the bubble sort.
} // end of main program
8/14/2019 an Array is a Collection of Data Elements Of
30/51
Searching
Another Example -
Sequential Search
Binary Search
8/14/2019 an Array is a Collection of Data Elements Of
31/51
Two Dimensional Arrays
C++ supports multi-dimensional array
data_type array_name[ROW_SIZE][COLUMN_SIZE]
int matrix[3][4];
row[0]
row[1]
row[2]
row1 row2 row3
in memory
8/14/2019 an Array is a Collection of Data Elements Of
32/51
Two-D ArraysRow Major, Col Major
Row Major Storagerow[0]
row[1]
row[2]
row3
row2
row1
in memory
Col Major Storage
c[0] c[1] c[2] c[3]
c3
c2
c1
in memory
c3
8/14/2019 an Array is a Collection of Data Elements Of
33/51
Accessing Array Elements
int matrix[3][4];
matrix has 12 integer elements
matrix[0][0] element in first row, first columnmatrix[2][3] element in last row, last column
8/14/2019 an Array is a Collection of Data Elements Of
34/51
int main()
{
const int ROWS = 3;
const int COLS = 4;
int i, j, num[ROWS][COLS];
for(i=0; i
8/14/2019 an Array is a Collection of Data Elements Of
35/51
Output:
1 2 3 45 6 7 8
9 10 11 12
Two Dimensional Arrays
8/14/2019 an Array is a Collection of Data Elements Of
36/51
int main()
{
const int ROWS = 3;
const int COLS = 4;
int i, j, num[ROWS][COLS];
for(i=0; i
8/14/2019 an Array is a Collection of Data Elements Of
37/51
Output:
1 2 3 4 5 6
7 8 9 10 11 12
8/14/2019 an Array is a Collection of Data Elements Of
38/51
Two dimensional arrays
int E[][2]={1,2,
3,4};
Matrix Multiplication
8/14/2019 an Array is a Collection of Data Elements Of
39/51
type name[size1][size2] . . . [sizeN];
int multidim[4][10][3];
when multidimensional arrays are used,large amounts of memory are consumed.
Multidimentional Arrays
i i i A i i i i
8/14/2019 an Array is a Collection of Data Elements Of
40/51
int sqrs[10][2] = {
1, 1,
2, 4,
3, 9,
4, 16,
5, 25,6, 36,
7, 49,
8, 64,
9, 81,
10, 100
};
Multidimensional Array Initialization
M l idi i l A
8/14/2019 an Array is a Collection of Data Elements Of
41/51
int main(void)
{
const int ALPHABETS = 26;
char code[ALPHABETS][2] =
{
{'a', 'f'}, {'b', 'w'}, {'c', 'x'},
{'d', 'v'}, {'e', 's'}, {'f', 'r'},{'g', 'q'}, {'h', 'c'}, {'i', 'g'},
{'j', 'h'}, {'k', 'e'}, {'l', 'u'},
{'m', 'b'}, {'n', 'j'}, {'o', 'd'},
{'p', 'k'}, {'q', 't'}, {'r', 'l'},{'s', 'm'}, {'t', 'n'}, {'u', 'a'},
{'v', 'o'}, {'w', 'p'}, {'x', 'z'},
{'y', 'i'}, {'z', 'y'}
};
Multidimensional Arrays
M ltidi i l A
8/14/2019 an Array is a Collection of Data Elements Of
42/51
int i;
char alpha;
cout > alpha;
for(i=0; i< ALPHABETS; i++)
{if(code[i][0]==alpha)
{
cout
8/14/2019 an Array is a Collection of Data Elements Of
43/51
Reference
Dietel & Dietel
8/14/2019 an Array is a Collection of Data Elements Of
44/51
Case Study:
Computing Mean, Median and Mode Using Arrays
MeanAverage
MedianNumber in middle of sorted list
1, 2, 3, 4, 5 (3 is median)
ModeNumber that occurs most often1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)
1 // Fig. 4.17: fig04_17.cpp
2 // This program introduces the topic of survey data analysis
8/14/2019 an Array is a Collection of Data Elements Of
45/51
2 // This program introduces the topic of survey data analysis.
3 // It computes the mean, median, and mode of the data.
4 #include
5
6 using std::cout;
7 using std::endl;
8 using std::ios;9
10 #include
11
12 using std::setw;
13 using std::setiosflags;
14 using std::setprecision;
15
16voidmean( const int [], int );17voidmedian( int [], int );
18voidmode( int [], int [], int );
19voidbubbleSort( int[], int );
20voidprintArray( const int[], int );
21
22 int main()
23 {
24 const int responseSize = 99;25 int frequency[ 10 ] = { 0 },
26 response[ responseSize ] =
27 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9,
28 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,
29 6, 7, 8, 9, 3, 9, 8, 7, 8, 7,
30 7, 8, 9, 8, 9, 8, 9, 7, 8, 9,
31 6, 7, 8, 7, 8, 7, 9, 8, 9, 2,
32 7, 8, 9, 8, 9, 8, 9, 7, 5, 3,
33 5 6 7 2 5 3 9 4 6 4
34 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
35 7 4 4 2 5 3 8 7 5 6
8/14/2019 an Array is a Collection of Data Elements Of
46/51
35 7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
36 4, 5, 6, 1, 6, 5, 7, 8, 7 };
37
38 mean( response, responseSize );
39 median( response, responseSize );
40 mode( frequency, response, responseSize );
41
42 return 0;
43 }
44
45voidmean( const int answer[], int arraySize )
46 {
47 int total = 0;
48
49 cout
8/14/2019 an Array is a Collection of Data Elements Of
47/51
69
70 printArray( answer, size );
71 bubbleSort( answer, size );
72 cout
8/14/2019 an Array is a Collection of Data Elements Of
48/51
97 for ( rating = 1; rating
8/14/2019 an Array is a Collection of Data Elements Of
49/51
122
123 for ( int j = 0; j < size - 1; j++ )
124
125 if ( a[ j ] > a[ j + 1 ] ) {
126 hold = a[ j ];
127 a[ j ] = a[ j + 1 ];
128 a[ j + 1 ] = hold;
129 }
130}
131
132voidprintArray( const int a[], int size )
133{
134 for ( int j = 0; j < size; j++ ) {
135
136 if ( j % 20 == 0 )
137 cout
8/14/2019 an Array is a Collection of Data Elements Of
50/51
4. Program Output
********The mean is the average value of the dataitems. The mean is equal to the total ofall the data items divided by the numberof data items (99). The mean value forthis run is: 681 / 99 = 6.8788
********Median********The unsorted array of responses is6 7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 86 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 96 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 87 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7
The sorted array is1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 55 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 77 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 88 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 89 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
The median is element 49 ofthe sorted 99 element array.For this run the median is 7
********Mode
8/14/2019 an Array is a Collection of Data Elements Of
51/51
Program Output
********Response Frequency Histogram
1 1 2 25 0 5 0 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.
Recommended