33
1 Arrays & Functions CSC 211 Intermediate Programming CSC 211 Intermediate Programming

Arrays & Functions - City University of New Yorknatacha/.../CSC211/.../Arrays.pdf · Arrays & Functions CSC 211 Intermediate Programming. 2 ... The general form for declaring an array

Embed Size (px)

Citation preview

1

Arrays & Functions

CSC 211 Intermediate ProgrammingCSC 211 Intermediate Programming

2

DefinitionDefinition

An array – a consecutive group of memory locations that all have the same name and the same type.

To create an array we use a declaration statement. It should indicate three things:The type of the value to be stored in each elementThe name of the arrayThe number of elements in the array

Examples:int c[12] ;int b[100], x[27] ;

3

The general form for declaring an array is:The general form for declaring an array is:

typename arrayName[arraySize] ;

The expression arraySize, which is the number of elements, must be a constant, or a constant variable, or a constant expression. Constant variables must be initialized when they are declared and can not be modified thereafter. Using constant variables to specify the array size makes program more scalable.

4

Example Example –– OneOne--Dimensional ArrayDimensional Array

Supposeconst int N = 20;const int M = 40;const int MaxStringSize = 80;const int MaxListSize = 1000;

Then the following are all legal array definitions.int A[10]; // array of 10 intschar B[MaxStringSize]; // array of 80 charsdouble C[M*N]; // array of 800 doublesint Values[MaxListSize];// array of 1000 ints

5

Array Array DeclarationDeclaration

Syntax: <type> <arrayName>[<dimension>]

6

Array InitializationArray Initialization

7

DiscussionsDiscussions

If there are fewer initializer than elements in the array, the remaining elements are automatically initialized to zero.int n[10] = { 0 } ;explicitly initializes the first element to zero and implicitly initializes the remaining nine elements to zero.Automatic arrays are not implicitly initialized to zero. The programmer must at least initialize the first element to zero for the remaining elements to be automatically zeroed. The following array declarationint n[5] = {32, 27, 64, 18, 95, 14} ;would cause a syntax error because there are 6 initilizers and only 5 array elements.If the array size is omitted from a declaration with an initializer list, the number of elements in the array will be the number of elements in the initializer list.int n[ ] = { 1, 2, 3, 4, 5 } ;

8

Example Example -- Initializing an ArrayInitializing an Array

// initializing an array#include <iostream.h>#include <iomanip.h>int main(){

int i, n[ 10 ];for ( i = 0; i < 10; i++ ) // initialize array

n[ i ] = 0;cout << "Element" << setw( 13 ) << "Value" << endl;for ( i = 0; i < 10; i++ ) // print array

cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;return 0;

}Remember that setw specifies the field width in which the next value is to

be output.

9

Initializing an Array with a DeclarationInitializing an Array with a Declaration

// Initializing an array with a declaration#include <iostream.h>#include <iomanip.h>int main(){

int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

cout << "Element" << setw( 13 ) << "Value" << endl;for ( int i = 0; i < 10; i++ )

cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;return 0;

}

10

// arrayone.cpp#include <iostream>using namespace std ;int main( ){int yams[3] ; // creates array with three elementsyams[0] = 7 ; // assign value to the first elementyams[1] = 8 ;yams[2] = 6 ;int yamcosts[3] = {20, 30, 5} ; // create, initialize array// NOTE: If your C++ compiler can’t initialize this array, use static int yamcosts[3]// instead of int yamcosts[3]cout << “Total yams = “ ;cout << yams[0] + yams[1] + yams[2] << “\n” ;cout << “The package with “ << yams[1] << “ yams costs “ ;cout << yamcosts[1] << “ cents per yam.\n” ;int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1] ;total = total + yams[2] * yamcosts[2] ;cout << “ The total yam expense is “ << total << “ cents.\n” ;cout << “\nSize of yams array = “ << sizeof yams ;cout << “bytes.\n “ ;cout << “Size of one element = “ << size of yams[0] ;cout << “bytes.\n “ ;return o ;}

11

OutputTotal yams = 21The package with 8 yams costs 30 cents per yam.The total yam expenses is 410 cents.Size of yams array = 12 bytes.Size of one element = 4 bytes.

Example:int cards[4] = {3, 6, 8, 10} ; // okayint hand[4] ; // okayhand[4] = {5, 6, 7, 9} ; // not allowedhand = cards ; // not allowed

12

Static Arrays and Local Static VariablesStatic Arrays and Local Static Variables

Arrays that are declared static are initialized when the program is loaded. If a static arrayis not explicitly initialized by the programmer, that array is initialized to zero by the compiler.

A static local variable in a function definition exists for the duration of the program but is only visible in the function body.

// Static arrays are initialized to zero#include <iostream.h>void staticArrayInit( void );void automaticArrayInit( void );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;

}

13

Static Arrays and Local Static Variables cont’dStatic Arrays and Local Static Variables cont’d

// function to demonstrate a static local array

void staticArrayInit( void ){

static int array1[ 3 ];int i;cout << "\nValues on entering staticArrayInit:\n";

for ( i = 0; i < 3; i++ )cout << "array1[" << i << "] = " << array1[ i ] << " ";

cout << "\nValues on exiting staticArrayInit:\n";for ( i = 0; i < 3; i++ )

cout << "array1[" << i << "] = " << ( array1[ i ] += 5 ) << " ";

}

14

Static Arrays and Local Static Variables cont’dStatic Arrays and Local Static Variables cont’d

// function to demonstrate an automatic local arrayvoid automaticArrayInit( void ){

int i, array2[ 3 ] = { 1, 2, 3 };cout << "\n\nValues on entering automaticArrayInit:\n";for ( i = 0; i < 3; i++ )

cout << "array2[" << i << "] = " << array2[ i ] << " ";cout << "\nValues on exiting automaticArrayInit:\n";for ( i = 0; i < 3; i++ )

cout << "array2[" << i << "] = " << ( array2[ i ] += 5 ) << " ";

}

15

OutputOutput

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

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

16

Passing Arrays to FunctionsPassing Arrays to Functions

To pass an array argument to a function, specify the name of the array without any brackets. The array size is normally pass as well so the function can process the specific number of elements in the array.C++ automatically passes arrays to functions using simulated call-by-reference. The name of the array is the address of the first element of the array. Because the starting address is passed, the called function knows precisely where the array is stored. Therefore, when the called function modifies array elements in its function body, it is modifying the actual elements of the array in their original location. Although entire array are passed call-by-reference, individual array elements are passed call-by-value exactly as simple variables are.The function’s parameter list must specify that an array will be received. For example

void modifyArray ( int b[ ], int arraySize ) ;The size of the array is not required between the brackets. If it is included, the compiler will ignore it.The function prototype in this case is

void modifyArray ( int [ ], int ) ;

17

Arrays as ParametersArrays as Parameters

Consider a function to sum an arrayint arrayTotal (int numList [],

int listSize){ int total = 0;

for (int i = 0; i < listSize ; i++)total += numList[i];

return total; }- - - - -cout << "Sum = " <<

arrayTotal(intList, CAPACITY) ;

Must use an array name, square brackets [ ], and a

parameter for size.

Must use an array name, square brackets [ ], and a

parameter for size.

Use name of the array (without square brackets) to be sent to the function.

Use name of the array (without square brackets) to be sent to the function.

Note: the function does not care about the capacity of the array

you send it … the second parameter takes care of that

Note: the function does not care about the capacity of the array

you send it … the second parameter takes care of that

18

Passing Array ElementsPassing Array Elements

Individual elements can be passed to a function like ordinary values.

19

// Passing arrays and individual array elements to functions#include <iostream.h>#include <iomanip.h>void modifyArray( int [], int ); // appears strangevoid modifyElement( int );int main(){

const int arraySize = 5;int i, a[ arraySize ] = { 0, 1, 2, 3, 4 };cout << "Effects of passing entire array call-by-reference:"

<< "\n\nThe values of the original array are:\n";for ( i = 0; i < arraySize; i++ )

cout << setw( 3 ) << a[ i ];cout << endl;// array a passed call-by-referencemodifyArray( a, arraySize ); cout << "The values of the modified array are:\n";for ( i = 0; i < arraySize; i++ )

cout << setw( 3 ) << a[ i ];cout << "\n\n\n"

<< "Effects of passing array element call-by-value:"<< "\n\nThe value of a[3] is " << a[ 3 ] << '\n';

modifyElement( a[ 3 ] );

20

cout << "The value of a[3] is " << a[ 3 ] << endl;return 0;

}void modifyArray( int b[], int sizeOfArray ){

for ( int j = 0; j < sizeOfArray; j++ )b[ j ] *= 2;

}void modifyElement( int e ){

cout << "Value in modifyElement is " << ( e *= 2 ) << endl;

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

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

21

// Demonstrating the const type qualifier#include <iostream.h>void tryToModifyArray( const int [] );int main(){

int a[] = { 10, 20, 30 };tryToModifyArray( a );cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << '\n';return 0;

}void tryToModifyArray( const int b[] ){

b[ 0 ] /= 2; // errorb[ 1 ] /= 2; // errorb[ 2 ] /= 2; // error

}OutputCompiling FIG04_15.CPP:Error FIG04_15.CPP 18 : Cannot modify a const objectError FIG04_15.CPP 19 : Cannot modify a const objectError FIG04_15.CPP 20 : Cannot modify a const objectWarning FIG04_15.CPP 21 : Parameter ‘b’ is never used

22

22--D Array ExampleD Array Example

int table[5][4];

23

Accessing Array ComponentsAccessing Array Components

The syntax to access a component of a two-dimensional array is:arrayName[indexexp1][indexexp2]

where indexexp1 and indexexp2 are expressions yielding nonnegative integer valuesindexexp1 specifies the row position and indexexp2specifies the column position

24

InitializationInitialization

Like one-dimensional arraysTwo-dimensional arrays can be initialized when they are declared

To initialize a two-dimensional array when it is declared

1. Elements of each row are enclosed within braces and separated by commas

2. All rows are enclosed within braces3. For number arrays, if all components of a row are not

specified, the unspecified components are initialized to zero

25

Processing TwoProcessing Two--Dimensional ArraysDimensional Arrays

A two-dimensional array can be processed in three different ways:

1. Process the entire array

2. Process a particular row of the array, called row processing

3. Process a particular column of the array, called column processing

26

Processing TwoProcessing Two--Dimensional Arrays cont’dDimensional Arrays cont’d

Each row and each column of a two-dimensional array is a one-dimensional array

When processing a particular row or column of a two-dimensional array

We use algorithms similar to processing one-dimensional arrays

27

28

29

30

31

Passing TwoPassing Two--Dimensional Arrays as Parameters to FunctionsDimensional Arrays as Parameters to Functions

Two-dimensional arrays can be passed as parameters to a function

By default, arrays are passed by reference

The base address, that is, the address of the first component of the actual parameter is passed to the formal parameter

32

TwoTwo--Dimensional ArraysDimensional Arrays

Two-dimensional arrays are stored in row orderThe first row is stored first, followed by the second row, followed by the third row and so on

When declaring a two-dimensional array as a formal parameter

Can omit size of first dimension, but not the second

Number of columns must be specified

33

Multidimensional ArraysMultidimensional Arrays

Multidimensional Array: collection of a fixed number of elements (called components) arranged in n dimensions (n >= 1), Also called an n-dimensional arrayGeneral syntax of declaring an n-dimensional array is:dataType arrayName[intExp1][intExp2]...[intExpn];

where intExp1, intExp2, … are constant expressions yielding positive integer values