Arrays

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 49

4.

1 Arrays

Introduction

Structures of related data items Static entity (same size throughout program)

A few types
Pointer-based arrays (C-like) Arrays as objects (C++)

4.2 Array

Arrays

Consecutive group of memory locations Same name and type (int, char, etc.)

To refer to an element
Specify array name and position number (index) Format: arrayname[ position number ] First element at position 0

N-element array c
c[ 0 ], c[ 1 ] c[ n - 1 ]

Nth element as position N-1

4.2

Arrays

Array elements like other variables


Assignment, printing for an integer array c
c[ 0 ] = 3; cout << c[ 0 ];

Can perform operations inside subscript


c[ 5 2 ] same as c[3]

4.2
Name that this same c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11]

Arrays

of array (Note all elements of array have the name, c) -45 6 0 72 1543 -89 0 62 -3 1 6453 78

Position number of the element within array c

4.3

Declaring Arrays

When declaring arrays, specify


Name Type of array
Any data type

Number of elements type arrayName[ arraySize ];


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 variables
int b[ 100 ], x[ 27 ];

4.4

Examples Using Arrays

Initializing arrays
For loop
Set each element

Initializer list
Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; If not enough initializers, rightmost elements 0 If too many, syntax error

To set every element to same value 0


int n[ 5 ] = { };

If array size omitted, initializers determine size


int n[] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array

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

// Fig. 4.3: fig04_03.cpp // Initializing an array. #include <iostream> using std::cout; using std::endl; #include <iomanip>

fig04_03.cpp (1 of 2)

using std::setw;
int main() { int n[ 10 ];

Declare a 10-element array of integers.


// n is an array of Initialize array 10 integers

// initialize elements of array for ( int i = 0; i < 10; i++ ) n[ i ] = 0; // set element at location i to 0

to 0 using a for loop. Note that the array nhas elements n[0] to n[9]. to 0

cout << "Element" << setw( 13 ) << "Value" << endl; // output contents of array n in tabular format for ( int j = 0; j < 10; j++ ) cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;

26 27 28

return 0; } // end main

// indicates successful termination

Element 0 1 2 3 4 5 6 7 8 9

Value 0 0 0 0 0 0 0 0 0 0

fig04_03.cpp (2 of 2) fig04_03.cpp output (1 of 1)

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

// Fig. 4.4: fig04_04.cpp // Initializing an array with a declaration. #include <iostream> using std::cout; using std::endl; #include <iomanip>

fig04_04.cpp (1 of 1)

using std::setw;

Note the use of the initializer int main() list. { // use initializer list to initialize array n int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
cout << "Element" << setw( 13 ) << "Value" << endl; // output contents of array n in tabular format for ( int i = 0; i < 10; i++ ) cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;

return 0;
} // end main

// indicates successful termination

Element 0 1 2 3 4 5 6 7 8 9

Value 32 27 64 18 95 14 90 70 60 37

fig04_04.cpp output (1 of 1)

4.4 Array size

Examples Using Arrays

Can be specified with constant variable (const)


const int size = 20;

Constants cannot be changed Constants must be initialized when declared Also called named constants or read-only variables

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

// Fig. 4.5: fig04_05.cpp // Initialize array s to the even integers from 2 to 20. #include <iostream> using std::cout; using std::endl; #include <iomanip>

fig04_05.cpp (1 of 2)

using std::setw;
int main() Only const variables { // constant variable can be used to specify array sizes. specify array size const int arraySize = 10; int s[ arraySize ]; // array s

Note use of const keyword. can

for ( int i = 0; i < arraySize; s[ i ] = 2 + 2 * i; cout << "Element" << setw( 13 )

The program becomes more scalable has 10 elements when we set the array size using a const variable. i++ ) // We can change arraySize, set the values and all the loops will still work (otherwise, wed have << "Value" << endl; to update every loop in the program).

24 25 26 27 28 29 30

// output contents of array s in tabular format for ( int j = 0; j < arraySize; j++ ) cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; return 0; } // end main Value 2 4 6 8 10 12 14 16 18 20 // indicates successful termination

fig04_05.cpp (2 of 2) fig04_05.cpp output (1 of 1)

Element 0 1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

// Fig. 4.6: fig04_06.cpp // Using a properly initialized constant variable. #include <iostream> using std::cout; using std::endl; int main() { const int x = 7;

fig04_06.cpp (1 of 1) Proper initialization of const variable.


// initialized constant variable

fig04_06.cpp output (1 of 1)

cout << "The value of constant variable x is: " << x << endl; return 0; } // end main // indicates successful termination

The value of constant variable x is: 7

1 2 3 4 5 6 7 8 9 10 11 12

// Fig. 4.7: fig04_07.cpp // A const object must be initialized. int main() { const int x; x = 7;

// Error: x

Uninitialized const results in a syntax error. Attempting to modify the const is must be initialized another error.

fig04_07.cpp (1 of 1) fig04_07.cpp output (1 of 1)

// Error: cannot modify a const variable

return 0;
} // end main

// indicates successful termination

d:\cpphtp4_examples\ch04\Fig04_07.cpp(6) : error C2734: 'x' : const object must be initialized if not extern d:\cpphtp4_examples\ch04\Fig04_07.cpp(8) : error C2166: l-value specifies const object

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

// Fig. 4.8: fig04_08.cpp // Compute the sum of the elements of the array. #include <iostream> using std::cout; using std::endl; int main() { const int arraySize = 10; int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int total = 0; // sum contents of array a for ( int i = 0; i < arraySize; i++ ) total += a[ i ]; cout << "Total of array element values is " << total << endl; return 0; } // end main // indicates successful termination

fig04_08.cpp (1 of 1) fig04_08.cpp output (1 of 1)

Total of array element values is 55

Compute the sum of the elements of the array.

Print out a histogram Given an array of integers print out a histogram, with the index number, the amount, and stars:

Index Number 0 1 2 3

Number in array 7

Stars ********

Print out stars

For each element in the array print out index, print out value at index print out stars

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

// Fig. 4.9: fig04_09.cpp // Histogram printing program. #include <iostream> using std::cout; using std::endl; #include <iomanip>

fig04_09.cpp (1 of 2)

using std::setw;
int main() { const int arraySize = 10; int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; cout << "Element" << setw( 13 ) << "Value" << setw( 17 ) << "Histogram" << endl; // for each element of array n, output a bar in histogram for ( int i = 0; i < arraySize; i++ ) { Prints asterisks corresponding cout << setw( 7 ) << i << setw( 13 ) to size of array element, << n[ i ] << setw( 9 );

n[i].

for ( int j = 0; j < n[ i ]; j++ ) cout << '*';

// print one bar

27 28 29 30 31 32 33 34

cout << endl;

// start next line of output

} // end outer for structure return 0; } // end main Value 19 3 15 7 11 9 13 5 17 1 Histogram ******************* *** *************** ******* *********** ********* ************* ***** ***************** * // indicates successful termination

fig04_09.cpp (2 of 2) fig04_09.cpp output (1 of 1)

Element 0 1 2 3 4 5 6 7 8 9

In Class Assignment The Rutgers Student Council (RSC) is conducting a poll of who should be the next apprentice. There are 10 candidates to choose from. The RSC has polled 1000 students on campus.

You are to write a program that tallies up the number of votes each candidate received and pronounces a winner.

Recording the votes Every time a person votes, the votes are recorded

Hints How should the votes be stored?


int votes[1000];

What is stored in array votes?


A number between 1-10 which represents a candidate..

Outline of Program 1. Input votes that were collected and store in array votes 2. Tally up frequency of votes for each candidate. 3. Determine which candidate has the most number of votes. 4. Print out the winner

Step 1: Input votes that were collected and store in array. Have to have this to have a record of the votes (just in case).
for(I = 0; I < 1000; i++) cin >> votes[i];

Step 2: Tally up frequency of votes for each candidate


Can use variables for each candidate: int candidate1, candidate2, candidate3, candidate4, candidate5, etc.

CUMBERSOME!!!!
And not scalable!!

Use an array called frequency which contains 10 elements one for each candidate: int frequency[XX];

In order to use frequency 1-10, need to allocate

Votes: 1 5 10 10 10 5 6 7 6 7 6 7 6 7 10 10 10 10 10 1 Etc..

int frequency[11];
Frequency

1 2 3 4 5 6 7 8 9 10

2 0 0 0 2 4 4 0 0 8

for(i =0; i < 1000; i++) if (votes[i] == 1) frequency[1]++; else if (votes[i] == 2) frequency[2]++; else if (votes[i] == 3) frequency[3]++; IS THERE A BETTER WAY?

YES!!!!

++frequency[ votes[ i ] ]

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

// Fig. 4.11: fig04_11.cpp // Student poll program. #include <iostream> using std::cout; using std::endl; #include <iomanip>

fig04_11.cpp (1 of 2)

using std::setw;
int main() { // define array sizes

const int responseSize = 1000; int vote[responseSize]; // size of array responses 16 const int frequencySize = 11; // size of array frequency 17 18 // place survey responses in the array votes 19 For (int i = 0; i < 1000; i++){ cout <<Please enter the next vote << endl; cin >> vote[i]; } // initialize frequency counters to 0 int frequency[ frequencySize ] = { 0 };

22 23 24 25

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

// for each answer, select value of an element of array // responses and use that value as subscript in array // frequency to determine element to increment for ( int answer = 0; answer < responseSize; answer++ ) ++frequency[ votes[answer] ]; // display results cout << "Rating" << setw( 17 ) << "Frequency" << endl;

// output frequencies in tabular format for ( int rating = 1; rating < frequencySize; rating++ ) cout << setw( 6 ) << rating << setw( 17 ) << frequency[ rating ] << endl;
return 0; // indicates successful termination printmax(frequency); } // end main

fig04_11.cpp (2 of 2) responses[answer] is the rating (from 1 to 10). This determines the index in frequency[] to increment.

Rating 1 2 3 4 5 6 7 8 9 10

Frequency 991 1 1 1 1 1 1 1 1 1

fig04_11.cpp output (1 of 1)

Find winner int printmax(int frequency[], frequencysize) { int max = 0, winner = 0; for (int i = 0; i < frequencysize; i++) if (frequency[i] > max) { max = frequency[i]; Need to store the actual winner not just the number winner = i; of votes the winner has!!! } cout << and the next apprentice is << i <<endl;

4.4

Examples Using Arrays

Strings (more in ch. 5)


Arrays of characters All strings end with null ('\0') Examples
char string1[] = "hello";
Null character implicitly added string1 has 6 elements

char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0 };

Subscripting is the same


String1[ 0 ] is 'h' string1[ 2 ] is 'l'

4.4

Examples Using Arrays

Input from keyboard


char string2[ 10 ]; cin >> string2;

Puts user input in string


Stops at first whitespace character Adds null character

If too much text entered, data written beyond array


We want to avoid this (section 5.12 explains how)

Printing strings
cout << string2 << endl;
Does not work for other array types

Characters printed until null found

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

// Fig. 4_12: fig04_12.cpp // Treating character arrays as strings. #include <iostream> using std::cout; using std::cin; using std::endl; int main() { char string1[ 20 ], char string2[] = "string literal"; // reserves 15 characters // read string cout << "Enter cin >> string1;

fig04_12.cpp (1 of 2) Two different ways to declare strings. string2 is initialized, and its size // reserves 20 characters determined automatically .

Examples of reading strings from user into array string2 from the keyboard and the string \"hello there\": ";out. printing them
// reads "hello" [space terminates input]

// output strings cout << "string1 is: " << string1 << "\nstring2 is: " << string2; cout << "\nstring1 with spaces between characters is:\n";

24 25 26 27 28 29 30 31 32 33

// output characters until null character is reached for ( int i = 0; string1[ i ] != '\0'; i++ ) cout << string1[ i ] << ' '; cin >> string1; // reads "there" string cout << "\nstring1 is: " << string1 << endl; return 0; // indicates successful

Can access the characters in a fig04_12.cpp using array notation. (2 of 2) The loop ends when the null character is found. fig04_12.cpp termination output (1 of 1)

} // end main

Enter the string "hello there": hello there string1 is: hello string2 is: string literal string1 with spaces between characters is: h e l l o string1 is: there

4.4

Examples Using Arrays

Recall static storage (chapter 3)


If static, local variables save values between function calls Visible only in function body Can declare local arrays to be static
Initialized to zero static int array[3];

If not static
Created (and destroyed) in every function call

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

// Fig. 4.13: fig04_13.cpp // Static arrays are initialized to zero. #include <iostream> using std::cout; using std::endl; void staticArrayInit( void ); void automaticArrayInit( void ); // function prototype // function prototype

fig04_13.cpp (1 of 3)

int main() { cout << "First call to each function:\n"; staticArrayInit(); automaticArrayInit(); cout << "\n\nSecond call to each function:\n"; staticArrayInit(); automaticArrayInit(); cout << endl; return 0; } // end main // indicates successful termination

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

// function to demonstrate a static local array Static array, initialized to zero void staticArrayInit( void ) on first function call. { // initializes elements to 0 first time function is called static int array1[ 3 ]; cout << "\nValues on entering staticArrayInit:\n"; // output contents of array1 for ( int i = 0; i < 3; i++ ) cout << "array1[" << i << "] = " << array1[ i ] << " cout << "\nValues on exiting staticArrayInit:\n"; // modify and output for ( int j = 0; j < cout << "array1[" << ( array1[ contents of array1 3; j++ ) << j << "] = " j ] += 5 ) << " ";

fig04_13.cpp (2 of 3)

";

Array data is changed; the modified values stay.

} // end function staticArrayInit

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

// function to demonstrate an automatic local array void automaticArrayInit( void ) Automatic { with every // initializes elements each time function is called int array2[ 3 ] = { 1, 2, 3 }; cout << "\n\nValues on entering automaticArrayInit:\n"; // output contents of array2 for ( int i = 0; i < 3; i++ ) cout << "array2[" << i << "] = " << array2[ i ] << " cout << "\nValues on exiting automaticArrayInit:\n"; // modify and output for ( int j = 0; j < cout << "array2[" << ( array2[ contents of array2 3; j++ ) << j << "] = " j ] += 5 ) << " ";

array, recreated function call. fig04_13.cpp (3 of 3)

";

Although the array is changed, it will be destroyed when the function exits and the changes will be lost.

} // end function automaticArrayInit

First call to each function: Values on array1[0] Values on array1[0] Values on array2[0] Values on array2[0] entering staticArrayInit: = 0 array1[1] = 0 array1[2] = 0 exiting staticArrayInit: = 5 array1[1] = 5 array1[2] = 5 entering automaticArrayInit: = 1 array2[1] = 2 array2[2] = 3 exiting automaticArrayInit: = 6 array2[1] = 7 array2[2] = 8

fig04_13.cpp output (1 of 1)

Second call to each function: Values on array1[0] Values on array1[0] Values on array2[0] Values on array2[0] entering staticArrayInit: = 5 array1[1] = 5 array1[2] = 5 exiting staticArrayInit: = 10 array1[1] = 10 array1[2] = 10 entering automaticArrayInit: = 1 array2[1] = 2 array2[2] = 3 exiting automaticArrayInit: = 6 array2[1] = 7 array2[2] = 8

4.5

Passing Arrays to Functions

Specify name without brackets


To pass array myArray to myFunction
int myArray[ 24 ]; myFunction( myArray, 24 );

Array size usually passed, but not required


Useful to iterate over all elements

4.5

Passing Arrays to Functions

Arrays passed-by-reference
Functions can modify original array data Value of name of array is address of first element
Function knows where the array is stored Can change original memory locations

Individual array elements passed-by-value


Like regular variables square( myArray[3] );

4.5

Passing Arrays to Functions

Functions taking arrays


Function prototype
void modifyArray( int b[], int arraySize ); void modifyArray( int [], int );
Names optional in prototype Both take an integer array and a single integer

No need for array size between brackets


Ignored by compiler

If declare array parameter as const


Cannot be modified (compiler error) void doNotModify( const int [] );

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

// Fig. 4.14: fig04_14.cpp // Passing arrays and individual array elements to functions. #include <iostream> using std::cout; using std::endl; #include <iomanip>

fig04_14.cpp (1 of 3) Syntax for accepting an array in parameter list.


// appears strange

using std::setw;
void modifyArray( int [], int ); void modifyElement( int );

int main() { const int arraySize = 5; int a[ arraySize ] = { 0, 1, 2, 3, 4 };

// size of array a // initialize a

cout << "Effects of passing entire array by reference:" << "\n\nThe values of the original array are:\n";

// output original array for ( int i = 0; i < arraySize; i++ ) cout << setw( 3 ) << a[ i ];

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

cout << endl; // pass array a to modifyArray modifyArray( a, arraySize );

Pass array name (a) and size to function. Arrays are by reference passed-by-reference.

fig04_14.cpp (2 of 3)

cout << "The values of the modified array are:\n"; // output modified array for ( int j = 0; j < arraySize; j++ ) cout << setw( 3 ) << a[ j ]; // output value of a[ 3 ] cout << "\n\n\n" << "Effects of passing array element by value:" << "\n\nThe value of a[3] is " Pass a single array element << a[ 3 ] << '\n'; // pass array element a[ 3 ] by modifyElement( a[ 3 ] );

by value; the original cannot be modified. value

// output value of a[ 3 ] cout << "The value of a[3] is " << a[ 3 ] << endl; return 0; } // end main // indicates successful termination

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

// in function modifyArray, "b" points to // the original array "a" in memory void modifyArray( int b[], int sizeOfArray ) { // multiply each array element by 2 for ( int k = 0; k < sizeOfArray; k++ ) b[ k ] *= 2;

Although named b, the array points to the original array a. It can modify as data. fig04_14.cpp (3 of 3)

} // end function modifyArray


// // void modifyElement( int e ) { // multiply parameter by 2 cout << "Value in modifyElement is " << ( e *= 2 ) << endl; } // end function modifyElement

Individual array elements are passed by value, and the in function modifyElement, "e" is a local copy of array element a[ 3 ] passed from main originals cannot be changed.

Effects of passing entire array by reference: The values of 0 1 2 3 The values of 0 2 4 6 the original array are: 4 the modified array are: 8

fig04_14.cpp output (1 of 1)

Effects of passing array element by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

// Fig. 4.15: fig04_15.cpp // Demonstrating the const type qualifier. #include <iostream> using std::cout; using std::endl; void tryToModifyArray( const int [] ); //

Array parameter declared as const. Array cannot be modified, even though it is passed by reference. function prototype

fig04_15.cpp (1 of 2)

int main() { int a[] = { 10, 20, 30 };


tryToModifyArray( a ); cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << '\n'; return 0; } // end main // indicates successful termination

22 23 24 25 26 27 28 29 30

// In function tryToModifyArray, "b" cannot be used // to modify the original array "a" in main. void tryToModifyArray( const int b[] ) { b[ 0 ] /= 2; // error b[ 1 ] /= 2; // error b[ 2 ] /= 2; // error } // end function tryToModifyArray

fig04_15.cpp (2 of 2) fig04_15.cpp output (1 of 1)

d:\cpphtp4_examples\ch04\Fig04_15.cpp(26) : error C2166: l-value specifies const object d:\cpphtp4_examples\ch04\Fig04_15.cpp(27) : error C2166: l-value specifies const object d:\cpphtp4_examples\ch04\Fig04_15.cpp(28) : error C2166: l-value specifies const object

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy