arrays in c++: numeric character (part 2). passing arrays as arguments in c++, arrays are always...

23
Arrays in C++: Numeric Character (Part 2)

Upload: sharlene-welch

Post on 14-Dec-2015

260 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Arrays in C++:

NumericCharacter(Part 2)

Page 2: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Passing Arrays as Arguments

in C++, arrays are always passed by reference (Pointer)

whenever an array is passed as an argument, its base address is sent to the called function

Page 3: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Using Arrays as Arguments to Functions

Generally, functions that work with arrays require 2 items of information as arguments:

the beginning memory address of the array (base address)

the number of elements to process in the array

Page 4: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Simple Exampleconst int MAX=5;float get_sum(float vector[]); // Prototypeint main ( )

{ float sum, scores[MAX];

<assign values to scores>sum = get_sum(scores);return 0;

}float get_sum (float vector[]) // definition{ float total = 0.0;

int j; for (j = 0; j < MAX; ++j)

total += vector[j];return total;

}

Page 5: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Programming Tip

When passing an array as an argument, also pass the size of the array.Previous example revisited

Page 6: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Question

How to pass an element or part of an array as a parameter?

-- Revisit the previous example

Page 7: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

#include <iostream>#include <iomanip>using namespace std;

void obtain ( int [ ], int ) ; // prototypes here void findWarmest ( const int[ ], int , int& ) ; // note const here void findAverage ( const int[ ], int , int& ) ;void print ( const int [ ], int ) ;

int main ( ){ int temp[31] ; // array to hold up to 31 temperatures int numDays ; int average=0 ; int hottest =0; int m ;

Example with Array Parameters

Page 8: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

cout << “How many daily temperatures? ”; cin >> numDays;

obtain( temp, numDays ) ; // call passes value of numDays and // address of array temp to function

cout << numDays << “ temperatures“; print ( temp, numDays ) ;

findAverage ( temp, numDays, average ) ; findWarmest ( temp, numDays, hottest ) ;

cout << “Average was: “ << average << endl; cout << “Highest was: “ << hottest << endl; return 0;}

Page 9: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Memory Allocated for Array

temp[0] temp[1] temp[2] temp[3] temp[4] . . . . . temp[30]

6000

Base Address

50 65 70 62 68 ..

int temp[31] ; // array to hold up to 31 temperatures

Page 10: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

void obtain ( /* out */ int temp [ ] , /* in */ int number )

/* Has user enter number temperature values at keyboard

// Precondition:// number is assigned && number > 0// Postcondition:// temp [ 0 . . number -1 ] are assigned */{ int m;

for ( m = 0 ; m < number; m++ ) { cout << “Enter a temperature : “; cin >> temp [m]; }}

Page 11: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

void print ( /* in */ const int temp [ ] , /* in */ int number )

/* Prints number temperature values to screen// Precondition:// number is assigned && number > 0// temp [0 . . number -1 ] are assigned// Postcondition:// temp [ 0 . . number -1 ] have been printed 5 to a line*/{

int m; cout << “You entered: “; for ( m = 0 ; m < number; m++ ) { if ( m % 5 == 0 ) cout << endl; cout << setw(7) << temp [m]; }}

Page 12: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Use of const

because the identifier of an array holds the base address of the array, an & is never needed for an array in the parameter list

arrays are always passed by reference

to prevent elements of an array used as an argument from being unintentionally changed by the function, you place const in the function heading and prototype

Page 13: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Use of const in prototypes

void obtain ( int [ ], int ) ;

void findWarmest ( const int [ ], int, int& ) ;

void findAverage ( const int [ ], int, int& ) ;

void print ( const int [ ], int ) ;

do not use const with outgoing array becausefunction is supposed to change array values

use const with incoming array values to prevent unintentional changes by function

Page 14: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

void findAverage ( /* in */ const int temp [ ] , /* in */ int number , /* out */ int& avg )

/* Determines average of temp[0 . . number-1]// Precondition:// number is assigned && number > 0// temp [0 . . number -1 ] are assigned// Postcondition:// avg = arithmetic average of temp[0 . . number-1]*/{

int m; int total = 0; for ( m = 0 ; m < number; m++ ) { total = total + temp [m] ; }

avg = int (float (total) / float (number));}

Page 15: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

void findWarmest ( /* in */ const int temp [ ] , /* in */ int number , /* out */ int& largest )

/* Determines largest of temp[0 . . number-1]// Precondition:// number is assigned && number > 0// temp [0 . . number -1 ] are assigned// Postcondition:// largest=largest value in temp[0 . . number-1] */{

int m; largest = temp[0] ; // initialize largest to first element

// then compare with other elements

for ( m = 0 ; m < number; m++ ) { if ( temp [m] > largest ) largest = temp[m] ; }}

Page 16: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Using arrays for Counters

Write a program to count the number of each alphabet letter in a text file.

letterASCII

‘A’ 65

‘B’ 66

‘C’ 67

‘D’ 68 . . . . . .

‘Z’ 90

This is my text file.

It contains many

things!

5 + 8 is not 14.

Is it?

“my.dat”

Page 17: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

const int SIZE 91;int freqCount[SIZE]={0};

freqCount [ 0 ] 0

freqCount [ 1] 0 . . . . . .freqCount [ 65 ] 2

freqCount [ 66 ] 0 . . . . . .

freqCount [ 89] 1

freqCount [ 90 ] 0

unused

counts ‘A’ and ‘a’

counts ‘B’ and ‘b’ . . .

counts ‘ Y’ and ‘y’

counts ‘Z’ and ‘z’

Page 18: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

Main Module Pseudocode

Level 0Open dataFile (and verify success)Zero out freqCountRead ch from dataFileWHILE NOT EOF on dataFile

If ch is alphabetic characterIf ch is lowercase alphabetic

Change ch to uppercaseIncrement freqCount[ch] by 1

Read ch from dataFilePrint characters and frequencies

Page 19: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

/* Program counts frequency of each alphabetic character in text file. */

#include <iostream>#include <ifstream>#include <cstdlib>#include <ctype>using namespace std;

const int SIZE 91;void printOccurrences ( const int [ ] ) ; /*prototype */

Counting Frequency of Alphabetic Characters

Page 20: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

int main ( ){

ifstream inStream; int freqCount [SIZE ]; char ch , index;

inStream.open(“my.dat”) ; /* open and verify success */ if ( inStream.fail()) { cout << “ CAN’T OPEN INPUT FILE ! “; exit(1); } for ( int m = 0 ; m < SIZE ; m++ ) /* zero out the array */

freqCount [ m ] = 0 ;

Page 21: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

inStream.get(ch); /* read file one character at a time */ while ( ! inStream.eof( ) ) /* while last read was successful */ {

if (isalpha ( ch ) ){

if ( islower ( ch ) )ch = toupper ( ch ) ;

freqCount [ ch ] = freqCount [ ch ] + 1 ;/* use ch as a type of integer*/

}inStream.get(ch); /* get next character */

}printOccurrences ( freqCount ) ;return 0;

} // end of main function

Page 22: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

void printOccurrences ( const int freqCount [ ] )

// Prints each alphabet character and its frequency

// Precondition:

// freqCount [ ‘A’ . . ‘Z’ ] are assigned

// Postcondition:

// freqCount [ ‘A’ . . ‘Z’ ] have been printed */

{ char index ;

cout << “File contained\n “;

cout << “LETTER OCCURRENCES\n”;

for ( index = ‘A’ ; index < = ‘Z’ ; index++ )

{

cout << index <<“\t”

<< freqCount [ index ] << endl;

}

}

Page 23: Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed

More about Array Index

array index can be any integral type. This includes char and enum type.

it is programmer’s responsibility to make sure that an array index does not go out of bounds. The index must be within the range 0 through the declared array size minus one

using an index value outside this range causes the program to access memory locations outside the array. The index value determines which memory location is used