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.

Slides:



Advertisements
Similar presentations
1 Lecture 10 Chapter 7 Functions Dale/Weems/Headington.
Advertisements

1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
Array What it is. How to use it How to declare it How to initialize it.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.
Chapter 7 Functions.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
1 Chapter 7 Functions. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 Chapter 11 One-Dimensional Arrays. 2 Chapter 11 Topics l Atomic and composite data types l Declaring and instantiating an array l The length of an array.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Chapter 8 Functions. Chapter 8 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
1 Functions. 2 Chapter 7 Topics  Writing a Program Using Functional Decomposition  Writing a Void Function for a Task  Using Function Arguments and.
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Chapter 12-2 Arrays Dale/Weems. 2 Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information n.
1 Chapter 12 Arrays. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Arrays. 2 Chapter 12 Topics  One-Dimensional Arrays  Using const in Function Prototypes  Using an Array of struct or class Objects  Using an enum.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Objective: Students will be able to: Declare and use variables Input integers.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
1 Chapter 11 Arrays. 2 Chapter 11 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Chapter 12 Arrays Dale/Weems. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const.
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
CS 1430: Programming in C++.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Chapter 8 Functions.
Chapter 11 Arrays.
Lecture 7 1 Dimension Arrays Richard Gesick.
Basic Elements of C++.
Dale/Weems/Headington
C++ Data Types Simple Structured Address Integral Floating
Basic Elements of C++ Chapter 2.
String in C++ A string is an array of characters which contains a non-printing null character ‘\0’ ( with ASCII value 0 ) marking its end. A string.
Chapter 9 Scope, Lifetime, and More on Functions
One-Dimensional Array Introduction Lesson xx
Pointers, Dynamic Data, and Reference Types
Chapter 11 Arrays.
CS150 Introduction to Computer Science 1
Chapter 8 Functions.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Presentation transcript:

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 as an argument, its base address is sent to the called function

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

Simple Example const int MAX=5; float get_sum(float vector[]); // Prototype int main ( ) { float sum, scores[MAX]; 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; }

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

Question How to pass an element or part of an array as a parameter? -- Revisit the previous example

#include 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

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; }

Memory Allocated for Array temp[0] temp[1] temp[2] temp[3] temp[4]..... temp[30] 6000 Base Address int temp[31] ; // array to hold up to 31 temperatures

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]; }

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]; }

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

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 because function is supposed to change array values use const with incoming array values to prevent unintentional changes by function

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)); }

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] ; }

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! is not 14. Is it? “my.dat”

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’

Main Module Pseudocode Level 0 Open dataFile (and verify success) Zero out freqCount Read ch from dataFile WHILE NOT EOF on dataFile If ch is alphabetic character If ch is lowercase alphabetic Change ch to uppercase Increment freqCount[ch] by 1 Read ch from dataFile Print characters and frequencies

/* Program counts frequency of each alphabetic character in text file. */ #include using namespace std; const int SIZE 91; void printOccurrences ( const int [ ] ) ; /*prototype */ Counting Frequency of Alphabetic Characters

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 ;

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

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; }

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