lecture 11 of c++ by mehmood
DESCRIPTION
C++TRANSCRIPT
1
LECTURE 12
2
Array Arrays are data structures consisting of related data items
of the same type An array is used to process a collection of data
of the same type Examples: A list of names
A list of temperatures Arrays
are static entities (same size throughout program) Consecutive group of memory locations Same name and type (int, char, etc.)
Arrays can be of type Pointer based arrays (C-style) used in this chapter Arrays as objects (C++)
3
The Array Variables The variables making up the array are referred to as
Indexed variables Subscripted variables Elements of the array
The number of indexed variables in an array is the declared size, or size, of the array The largest index is one less than the size The first index value is zero
4
Declaring an Array When declaring arrays, programmer specify
Name Type of array
Any data type Number of elements (array size)
Format type arrayName[ arraySize ];
Example int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats Declaring multiple arrays of same type
Use comma separated list, like regular variablesint b[ 100 ], x[ 27 ];
5
Array Variable Types An array can have indexed variables of any type
All indexed variables in an array are of thesame type This is the base type of the array
An indexed variable can be used anywhere an ordinary variable of the base type is used
6
Using [ ] With Arrays In an array declaration, [ ]'s enclose the size
of the array such as this array of 5 integers: int score [5];
When referring to one of the indexed variables,the [ ]'s enclose a number identifying one of the indexed variables score[3] is one of the indexed variables The value in the [ ]'s can be any expression that
evaluates to one of the integers 0 to (size -1)
7
Array To refer to a particular location or an element in array
Specify array name and position number (index) Format
arrayname[ position number ] First element in every array is zeroth element
Consider N-element array c The elements are c[ 0 ], c[ 1 ] … c[ n - 1 ] Nth element as position N-1
Subscript The position number within square brackets Must be an integer o an integer expression (any integral type)
8
Array
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array (Note that all elements of this array have the same name, c)
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Position number of the element within array c
A 12-elementArray named c
9
Array Array elements like other variables
Assignment, printing for an integer array cc[ 0 ] = 3;
cout << c[ 0 ]; Performing division on array element
x = c[ 6 ] / 2; /*divide seventh element of array by 2 and assign the result to the variable x */
printing sum of first three array elements of array ccout << c[ 0 ] + c[ 1 ] + c[ 2 ];
Can perform operations inside subscriptc[ 5 – 2 ] same as c[3]
10
Loops And Arrays For loop
for-loops are commonly used to step through arrays Set each element
Example
for (i = 0; i < 5; i++) {
cout << score[i] << " off by " << (max - score[i]) << endl; }
could display the difference between each score and the maximum score stored in an array
First index is 0 Last index is (size – 1)
11
Initializing Arrays To initialize an array when it is declared
The values for the indexed variables are enclosedin braces and separated by commas
Example int children[3] = { 2, 12,
1 };
Is equivalent to: int children[3]; children[0] = 2; children[1] = 12;
children[2] = 1;
12
13
Initializing Arrays If too few values are listed in an initialization
statement The listed values are used to initialize the first of
the indexed variables The remaining indexed variables are initialized to
a zero of the base type Example: int a[10] = {5, 5};
initializes a[0] and a[1] to 5 and a[2] through a[9] to 0
If values listed in initialization statement are more than array elements, it causes a syntax error
14
Initializing Arrays To set every element to same value
int n[ 5 ] = { 0 };
If array size omitted, values listed in initialization statement determine size
int n[] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array
15
Example program
Initializing the elements of an array to zeroes Following program uses for repetition
structure to initialize the elements of a ten-element integer array n to zero and prints the array in a tabular form
16
C++ code1 // Fig. 4.3: fig04_03.cpp2 // Initializing an array.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 int main()13 {14 int n[ 10 ]; // n is an array of 10 integers15 16 // initialize elements of array n to 0 17 for ( int i = 0; i < 10; i++ ) 18 n[ i ] = 0; // set element at location i to 019 20 cout << "Element" << setw( 13 ) << "Value" << endl;21 22 // output contents of array n in tabular format 23 for ( int j = 0; j < 10; j++ ) 24 cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;25 return 0; // indicates successful termination26 27 } // end main
Declare a 10-element array of integers.
Initialize array to 0 using a for loop. Note that the array has elements n[0] to n[9].
setw specifies the field width in which the next value is to be output
17
Output
18
Example program
Initializing the elements of an array with declaration Following program initializes an integer array
with 10 values and prints the array in tabular format
19
C++ code1 // Fig. 4.4: fig04_04.cpp2 // Initializing an array with a declaration.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 int main()13 {14 // use initializer list to initialize array n 15 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };16 17 cout << "Element" << setw( 13 ) << "Value" << endl;18 19 // output contents of array n in tabular format20 for ( int i = 0; i < 10; i++ )21 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;22 23 return 0; // indicates successful termination24 25 } // end main
Note the use of the initializer list.
20
Output
21
Array size (constant variables) Array size Can be specified with constant variable (const)
const int size = 20; Also called named constants or read-only variables
Use constants to declare the size of an array Using a constant allows your code to be easily altered for use on a smaller or
larger set of data
Example
//Constants must be initialized when declared and can not be modified there afterconst int NUMBER_OF_STUDENTS = 50;int score[NUMBER_OF_STUDENTS];
…for ( i = 0; i < NUMBER_OF_STUDENTS; i++)
cout << score[i] << " off by “ << (max – score[i]) << endl;
Only the value of the constant can be changed to makethis code work for any number of students
22
Example program Generating values to be placed into an
element of array Following example initializes a 10-element
array s to the integers 2,4,6,…..20 and prints the array in tabular format.
These numbers are generated by multiplying each successive value of the loop counter by 2 and adding 2
23
C++ code1 // Fig. 4.5: fig04_05.cpp2 // Initialize array s to the even integers from 2 to 20.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 int main()13 {14 // constant variable can be used to specify array size15 const int arraySize = 10;16 17 int s[ arraySize ]; // array s has 10 elements18 19 for ( int i = 0; i < arraySize; i++ ) // set the values20 s[ i ] = 2 + 2 * i; 21 22 cout << "Element" << setw( 13 ) << "Value" << endl;23 24 // output contents of array s in tabular format25 for ( int j = 0; j < arraySize; j++ ) 26 cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;27 28 return 0; // indicates successful termination29 30 } // end main
Note use of const keyword. Only const variables can specify array sizes.
The program becomes more scalable when we set the array size using a const variable. We can change arraySize, and all the loops will still work (otherwise, we’d have to update every loop in the program).
24
Output
25
Reading assignment Book
C++ How to program by Deitel and Deitel 4th edition
Assignment
Fig 4.6 (correctly initializing and using a constant variable)
Fig 4.7( A constant object must be initialized) Study the programs in above figures and understand
using a properly initialized constant variable What will happen if constant variable is not correctly
initialized
26
Example program
Computing the sum of the elements of an array
Following program sums the values contained in a the 12-element integer array a
27
C++ code1 // Fig. 4.8: fig04_08.cpp2 // Compute the sum of the elements of the array.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 int main()9 {10 const int arraySize = 10;11 12 int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };13 14 int total = 0;15 16 // sum contents of array a 17 for ( int i = 0; i < arraySize; i++ )18 total += a[ i ]; 19 20 cout << "Total of array element values is " << total << endl;21 22 return 0; // indicates successful termination23 24 } // end main
28
Output
29
Passing Arrays to functions To pass an array to a function
Specify the name of Array without brackets For Example
int myArray[ 24 ];
myFunction( myArray, 24 ); Pass array myArray to function myFunction Array size is usually passed
Useful to iterate over all elements
C++ automatically passes arrays to functions using simulated call-by-reference
30
Passing Arrays to functions Arrays are passed by call-by-reference
Functions can modify original array data Value of name of array is address of first element of
array Function knows where the array is stored Can modify the actual array elements in their original
memory locations
Individual array elements passed by call-by-value Like regular simple variables Such simple pieces of data are called scalar or scalar
quantities square( myArray[3] );
31
Passing Arrays to functions Indexed variables can be arguments to functions
Example
If a program contains these declarations: int i, n, a[10];
void my_function(int n);
Variables a[0] through a[9] are of type int, making these calls legal
my_function( a[ 0 ] ) my_function( a[ 3 ] ); my_function( a[ i ] );
32
Passing Arrays to functions Functions taking arrays
For a function receiving array through function call, the function’s parameter list must specify that an array will be received
Function prototype void modifyArray( int b[], int arraySize ); void modifyArray( int [], int );
this prototype can also be written asvoid modifyArray(int anyArrayName[], int anyVariableName);
Names optional in prototype Both take an integer array and a single integer
33
Passing Arrays to functions An array parameter is indicated using
emptybrackets in the parameter list
For example void fill_up(int a[ ], int size);
No need for array size between brackets Ignored by compiler
34
Example of Function Calls With Arrays
If function fill_up is declared in this way: void fill_up(int a[ ], int size);
and array score is declared this way: int score[5], number_of_scores;
fill_up is called in this way: fill_up( score, number_of_scores );
35
Example program
Passing arrays and individual array elements to functions
Following program demonstrates the difference between passing an entire array and passing an array element.
36
C++ code1 // Fig. 4.14: fig04_14.cpp2 // Passing arrays and individual array elements to functions.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 void modifyArray( int [], int ); // appears strange13 void modifyElement( int ); 14 15 int main()16 {17 const int arraySize = 5; // size of array a18 int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a19 20 cout << "Effects of passing entire array by reference:" 21 << "\n\nThe values of the original array are:\n";22 23 // output original array24 for ( int i = 0; i < arraySize; i++ )25 cout << setw( 3 ) << a[ i ];
Syntax for accepting an array in parameter list.
37
C++ code26 27 cout << endl;28 29 // pass array a to modifyArray by reference30 modifyArray( a, arraySize ); 31 32 cout << "The values of the modified array are:\n";33 34 // output modified array35 for ( int j = 0; j < arraySize; j++ )36 cout << setw( 3 ) << a[ j ];37 38 // output value of a[ 3 ]39 cout << "\n\n\n"40 << "Effects of passing array element by value:"41 << "\n\nThe value of a[3] is " << a[ 3 ] << '\n';42 43 // pass array element a[ 3 ] by value44 modifyElement( a[ 3 ] ); 45 46 // output value of a[ 3 ]47 cout << "The value of a[3] is " << a[ 3 ] << endl;48 49 return 0; // indicates successful termination50 51 } // end main
Pass array name (a) and size to function. Arrays are passed-by-reference.
Pass a single array element by value; the original cannot be modified.
38
C++ code52 53 // in function modifyArray, "b" points to 54 // the original array "a" in memory 55 void modifyArray( int b[], int sizeOfArray )56 { 57 // multiply each array element by 2 58 for ( int k = 0; k < sizeOfArray; k++ ) 59 b[ k ] *= 2; 60 61 } // end function modifyArray 62 63 // in function modifyElement, "e" is a local copy of64 // array element a[ 3 ] passed from main 65 void modifyElement( int e ) 66 { 67 // multiply parameter by 2 68 cout << "Value in modifyElement is " 69 << ( e *= 2 ) << endl; 70 71 } // end function modifyElement
Although named b, the array points to the original array a. It can modify a’s data.
Individual array elements are passed by value, and the originals cannot be changed.
39
Output
40
Output description Program first prints 5 elements of integer array a
a and its size are passed to function modifyArray, where each of a’s elements is multiplied by 2
a is reprinted in main
Program prints the value of a[3] and passes it to function modifyElement
Function modifyElement multiplies its argument by 2 and prints the new value
Note that when a[3] is reprinted in main, it has not been modified, because individual array elements are passed by call-by-value
41
Const Modifier Array parameters allow a function to change the
values stored in the array argument If a function should not change the values of the
array argument, use the modifier const An array parameter modified with const is a constant array parameter
If declare array parameter as const Cannot be modified (compiler error)
Examples void show_the_world (const int a[ ], int size); void doNotModify( const int [] );
42
Using const with Arrays If const is used to modify an array parameter
const is used in both the function declaration and definition to modify the array parameter
The compiler will issue an error if you write codethat changes the values stored in the array parameter
43
Function Calls and const If a function with a constant array parameter
calls another function using the const arrayparameter as an argument…
The called function must use a constant array parameter as a placeholder for the array
The compiler will issue an error if a function is called that does not have a const array parameter toaccept the array argument
44
Const Parameters Example
double compute_average(int a[ ], int size); void show_difference(const int a[ ], int size) { double average = compute_average(a, size); … }
compute_average has no constant array parameter
This code generates an error message becausecompute_average could change the array parameter
45
Reading assignment c++ how to program by
Deitel and Deitel 3rd or 4th eddition
Figure 4.15 demonstrates the cont type qualifier
Study the program and find the errors in the program also find a way to rectify the errors
46
Returning An Array Recall that functions can return a value of
type int, double, char, …, or a class type
Functions cannot return arrays
We learn later how to return a pointer to an array
47
Sorting Arrays Sorting data
Important computing application Virtually every organization must sort some data
Massive amounts must be sorted
Bubble sort (sinking sort) Several passes through the array Successive pairs of elements are compared
If increasing order (or identical), no change If decreasing order, elements exchanged
Repeat these steps for every element
48
Sorting Arrays Example:
Go left to right, and exchange elements as necessary One pass for each element
Original: 3 4 2 7 6 Pass 1: 3 2 4 6 7 (elements exchanged) Pass 2: 2 3 4 6 7 Pass 3: 2 3 4 6 7 (no changes needed) Pass 4: 2 3 4 6 7 Pass 5: 2 3 4 6 7 Small elements "bubble" to the top (like 2 in this
example)
49
Sorting Arrays Swapping variables
int x = 3, y = 4;
y = x;
x = y;
What happened? Both x and y are 3! Need a temporary variable
Solutionint x = 3, y = 4, temp = 0;
temp = x; // temp gets 3
x = y; // x gets 4
y = temp; // y gets 3
50
Example program Sorting an array with bubble sort
Following program sorts the values of a 10-element array into ascending order using the bubble sort (sinking sort) technique as discussed earlier
51
C++ code1 // Fig. 4.16: fig04_16.cpp2 // This program sorts an array's values into ascending order.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 int main()13 {14 const int arraySize = 10; // size of array a15 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };16 int hold; // temporary location used to swap array elements17 18 cout << "Data items in original order\n";19 20 // output original array21 for ( int i = 0; i < arraySize; i++ )22 cout << setw( 4 ) << a[ i ];23 24 // bubble sort 25 // loop to control number of passes 26 for ( int pass = 0; pass < arraySize - 1; pass++ )
Do a pass for each element in the array.
52
C++ code 27 28 // loop to control number of comparisons per pass 29 for ( int j = 0; j < arraySize - 1; j++ ) 30 31 // compare side-by-side elements and swap them if32 // first element is greater than second element 33 if ( a[ j ] > a[ j + 1 ] ) { 34 hold = a[ j ]; 35 a[ j ] = a[ j + 1 ]; 36 a[ j + 1 ] = hold; 37 38 } // end if 39 40 cout << "\nData items in ascending order\n";41 42 // output sorted array43 for ( int k = 0; k < arraySize; k++ )44 cout << setw( 4 ) << a[ k ];45 46 cout << endl;47 48 return 0; // indicates successful termination49 50 } // end main
If the element on the left (index j) is larger than the element on the right (index j + 1), then we swap them. Remember the need of a temp variable.
53
Output
54
Sorting Arrays The chief virtue of bubble sort is
It is easy to program
The drawback is It runs slowly, this becomes apparent when
sorting large arrays