cs 141 computer programming 1

65
CS 141 Computer Programming 1 1 Functions

Upload: madra

Post on 05-Jan-2016

20 views

Category:

Documents


2 download

DESCRIPTION

Functions. CS 141 Computer Programming 1. Outline. Introduction Math Library Functions Function Definitions Function Prototypes Static Variables Scope Rules Example using Function References and Reference Parameters Function Overloading Passing Array to Functions. Introduction. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS 141 Computer Programming 1

1

CS 141Computer

Programming 1

Functions

Page 2: CS 141 Computer Programming 1

2

Outline Introduction Math Library Functions Function Definitions Function Prototypes Static Variables Scope Rules Example using Function References and Reference Parameters Function Overloading Passing Array to Functions

Page 3: CS 141 Computer Programming 1

Introduction Divide and conquer

Construct a program from smaller pieces or components

Each piece more manageable than the original program

Page 4: CS 141 Computer Programming 1

Program Components in C++ Modules: functions and classes Programs use new and “prepackaged”

modules New: programmer-defined functions, classes Prepackaged: from the standard library

Functions invoked by function call Function name and information (arguments)

it needs Function definitions

Only written once Hidden from other functions

Page 5: CS 141 Computer Programming 1

Math Library Functions

Perform common mathematical calculations Include the header file <cmath>

Functions called by writing functionName (argument);or functionName(argument1, argument2, …);

Examplecout << sqrt( 900.0 );

sqrt (square root) function. The preceding statement would print 30

All functions in math library return a double

Page 6: CS 141 Computer Programming 1

Math Library Functions

Function arguments can be Constants

sqrt( 4.0 ); Variables

sqrt( x ); Expressions

sqrt( sqrt( x ) ) ; sqrt( 3 – 6*x );

Page 7: CS 141 Computer Programming 1

Math Library FunctionsMethod Description Example ceil( x ) rounds x to the smallest integer

not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x in radians)

cos( 0.0 ) is 1.0

exp( x ) exponential function ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906

fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76

floor( x ) rounds x to the largest integer not greater than x

floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0

fmod( x, y ) remainder of x/y as a floating-point number

fmod( 13.657, 2.333 ) is 1.992

log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0

log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0

pow( x, y ) x raised to power y (xy) pow( 2.0, 7 ) is 128 pow( 9, .5 ) is 3

sin( x ) trigonometric sine of x (x in radians)

sin( 0.0 ) is 0

sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0

tan( x ) trigonometric tangent of x (x in radians)

tan( 0.0 ) is 0

Fig. 3.2 Math library functions.

Page 8: CS 141 Computer Programming 1

Functions

Functions Modularize a program Software reusability

Call function multiple times Local variables

Known only in the function in which they are defined

All variables declared in function definitions are local variables

Parameters Local variables passed to function when called Provide outside information

Page 9: CS 141 Computer Programming 1

Function Definitions Function prototype

Tells compiler argument type and return type of function

int square( int ); Function takes an int and returns an int

Explained in more detail later

Calling/invoking a function square(x); Parentheses an operator used to call function

Pass argument x Function gets its own copy of arguments

After finished, passes back result

Page 10: CS 141 Computer Programming 1

Function Definitions Format for function definition

return-value-type function-name( parameter-list ){ declarations and statements}

Parameter list Comma separated list of parameters

Data type needed for each parameter If no parameters, use void or leave blank Example?

Return-value-type Data type of result returned (use void if nothing

returned)

Page 11: CS 141 Computer Programming 1

Function Definitions Example function

int square( int y ){

return y * y;}

return keyword Returns data, and control goes to function’s caller

If no data to return, use return; Function ends when reaches right brace

Control goes to caller Functions cannot be defined inside other functions Next: program examples

Page 12: CS 141 Computer Programming 1

Example 1 12 // Creating and using a programmer-defined function.3 #include <iostream>4 using namespace std;5 6 7 8 int square( int ); // function prototype9 10 int main()11 {12 // loop 10 times and calculate and output 13 // square of x each time14 for ( int x = 1; x <= 10; x++ ) 15 cout << square( x ) << " "; // function call16 17 cout << endl;18 19 return 0; // indicates successful termination20 21 } // end main22

Parentheses () cause function to be called. When done, it returns the result.

Function prototype: specifies data types of arguments and return values. square expects and int, and returns an int.

Example

Page 13: CS 141 Computer Programming 1

Example1 Cont.23 // square function definition returns square of an integer 24 int square( int y ) // y is a copy of argument to function25 { 26 return y * y; // returns square of y as an int 27 28 } // end function square

1 4 9 16 25 36 49 64 81 100

Definition of square. y is a copy of the argument passed. Returns y * y, or y squared.

Example

Page 14: CS 141 Computer Programming 1

Function Prototypes Function prototype contains

Function name Parameters (number and data type) Return type (void if returns nothing) Only needed if function definition after function

call Prototype must match function definition

Function prototypedouble maximum( double, double, double );

Definitiondouble maximum( double x, double y, double z ){ …}

Page 15: CS 141 Computer Programming 1

Function Prototypes Cont. Function signature

Part of prototype with name and parameters double maximum( double, double, double );

Argument Coercion Force arguments to be of proper type

Converting int (4) to double (4.0)cout << square(4)

Conversion rules Arguments usually converted automatically Changing from double to int can truncate data

(Demotion) 3.4 to 3

Mixed type goes to highest type (promotion) int * double

Function signature

Page 16: CS 141 Computer Programming 1

Static Variables static keyword

Local variables in function Keeps value between function calls Only known in own function

Page 17: CS 141 Computer Programming 1

Scope Rules Scope

Portion of program where identifier(variable/function) can be used

Types of scopes for an identifier: File scope

Defined outside a function, known in all functions Global variables, function definitions and

prototypes Function scope

Can only be referenced inside defining function Cannot be referenced outside the function body Local variables and function parameters

Page 18: CS 141 Computer Programming 1

Scope Rules Block scope

Blocks are defined by the beginning left brace { and the terminating right brace}.

Block scope begins at declaration of the identifier and ends at right brace } of the block Can only be referenced in this range Example:

Function-prototype scope Parameter list of prototype Names in prototype optional

Compiler ignores In a single prototype, name can be used once

Page 19: CS 141 Computer Programming 1

Scope Example2 // A scoping example.3 #include <iostream>4 5 using namespace std;6 7 8 void useLocal( void ); // function prototype9 void useStaticLocal( void ); // function prototype10 void useGlobal( void ); // function prototype11 12 int x = 1; // global variable13 14 int main()15 {16 int x = 5; // local variable to main17 18 cout << "local x in main's outer scope is " << x << endl;19 20 { // start new scope 21 22 int x = 7; 23 24 cout << "local x in main's inner scope is " << x << endl;25 26 } // end new scope

Declared outside of function; global variable with file scope.

Local variable with function scope.

Create a new block, giving x block scope. When the block ends, this x is destroyed.

Page 20: CS 141 Computer Programming 1

Scope Example27 28 cout << "local x in main's outer scope is " << x << endl;29 30 useLocal(); // useLocal has local x31 useStaticLocal(); // useStaticLocal has static local x32 useGlobal(); // useGlobal uses global x33 useLocal(); // useLocal reinitializes its local x34 useStaticLocal(); // static local x retains its prior value35 useGlobal(); // global x also retains its value36 37 cout << "\nlocal x in main is " << x << endl;38 39 return 0; // indicates successful termination40 41 } // end main42

Page 21: CS 141 Computer Programming 1

Scope Example43 // useLocal reinitializes local variable x during each call44 void useLocal( void )45 {46 int x = 25; // initialized each time useLocal is called47 48 cout << endl << "local x is " << x 49 << " on entering useLocal" << endl;50 ++x;51 cout << "local x is " << x 52 << " on exiting useLocal" << endl;53 54 } // end function useLocal55

local variable of function. This is destroyed when the function exits, and reinitialized when the function begins.

Page 22: CS 141 Computer Programming 1

Scope Example56 // useStaticLocal initializes static local variable x only the57 // first time the function is called; value of x is saved58 // between calls to this function59 void useStaticLocal( void )60 {61 // initialized only first time useStaticLocal is called62 static int x = 50; 63 64 cout << endl << "local static x is " << x 65 << " on entering useStaticLocal" << endl;66 ++x; 67 cout << "local static x is " << x 68 << " on exiting useStaticLocal" << endl;69 70 } // end function useStaticLocal71

Static local variable of function; it is initialized only once, and retains its value between function calls.

Page 23: CS 141 Computer Programming 1

Scope Example72 // useGlobal modifies global variable x during each call73 void useGlobal( void )74 {75 cout << endl << "global x is " << x 76 << " on entering useGlobal" << endl;77 x *= 10;78 cout << "global x is " << x 79 << " on exiting useGlobal" << endl;80 81 } // end function useGlobal

local x in main's outer scope is 5local x in main's inner scope is 7local x in main's outer scope is 5 local x is 25 on entering useLocallocal x is 26 on exiting useLocal local static x is 50 on entering useStaticLocallocal static x is 51 on exiting useStaticLocal

global x is 1 on entering useGlobalglobal x is 10 on exiting useGlobal

This function does not declare any variables. It uses the global x declared in the beginning of the program.

Scope Example

Page 24: CS 141 Computer Programming 1

Scope Example

 

local x is 25 on entering useLocallocal x is 26 on exiting useLocal 

local static x is 51 on entering useStaticLocallocal static x is 52 on exiting useStaticLocal 

global x is 10 on entering useGlobalglobal x is 100 on exiting useGlobal 

local x in main is 5

Page 25: CS 141 Computer Programming 1

Functions with Empty Parameter Lists

Empty parameter lists void or leave parameter list empty Indicates function takes no arguments Function print takes no arguments and returns

no value void print(); void print( void );

Page 26: CS 141 Computer Programming 1

26

Problem Write a program that asks the user for her

exam grade and prints a message indicating if the user has passed the exam or not

Can you solve the problem using Modules ?

#include <iostream>using namespace std; int main() {

int grade;

cout<<"Enter your grade:\n"; cin>>grade;

if (grade>60) cout<<"You passed";

else cout<<“You failed"; return 0;

}

Page 27: CS 141 Computer Programming 1

27

Selecting Modules (1) Divide the program into tasks:

o Read the gradeo Print the correct message

Modules: Read_Grade Display_Msg Main Fct

Main Fct

Read_Grade

Display_Msg

Page 28: CS 141 Computer Programming 1

28

Flow of Control (2)

Read_Grade Display_Msg

Main FctStart here

Invo

ke to

read

inpu

t fro

m u

ser

1

2

Retu

rn th

e in

put r

ead

from

the

user

3

Invoke to display message A

ND

send

the grade returned by Read_G

rade

4

Display m

essage on screen

AN

D return control to M

ain

5

return 0; 6

Page 29: CS 141 Computer Programming 1

29

Defining Modules (3.1)

For each Module decide on:o Possible Parameter Listo Possible Return Value

int Read_Grade(){

}

void Display_Message(int g){

}

Read_Grade

Main Fct

Invoke

to r

ead inpu

t fr

om

use

r

Retu

rn t

he in

put

read f

rom

the u

ser

Display_Msg

Main Fct

Invoke

to d

ispla

y m

essa

ge A

ND

send

the g

rade re

turn

ed b

y R

ead_G

rad

e

Disp

lay m

essa

ge o

n scre

en

AN

D re

turn

con

trol to

Main

Page 30: CS 141 Computer Programming 1

30

Defining Modules (3.2)

#include <iostream>using namespace std; int main() {

int grade;

cout<<"Enter your grade:\n"; cin>>grade;

if (grade>60) cout<<"You passed";

else cout<<“You failed";

return 0; }

Read_Grade

Display_Msg

Main Fct

Read_Grade Display_Msg

Page 31: CS 141 Computer Programming 1

31

Defining Modules(3.3)int Read_Grade(){

int grade; // Local variable cout<<"Enter your grade:\n"; cin>>grade; return grade;

}

void Display_Msg(int g){

if (g>60) cout<<"You passed";

else cout<<“You failed";}

grade scope

Page 32: CS 141 Computer Programming 1

32

#include <iostream>using namespace std;int Read_Grade(){

int grade; // Local variable cout<<"Enter your grade:\n"; cin>>grade; return grade;

}void Display_Msg(int g){

if (g>60) cout<<"You passed";

else cout<<“You failed";}// ================== Main Fct =========================int main(){

// Invoke read module and store returned input// Invoke display module and pass the grade

return 0;}

Using Modules (4.1)

Page 33: CS 141 Computer Programming 1

Using Modules (4.2)

33

void Display_Msg(int g){

if (g>60) cout<<"You passed";

else cout<<“You failed";}

int main(){

Display_Msg(87); return 0;

}

Argument

Parameter

Page 34: CS 141 Computer Programming 1

34

#include <iostream>using namespace std;int Read_Grade(){

int grade; // Local variable cout<<"Enter your grade:\n"; cin>>grade; return grade;

}void Display_Msg(int g){

if (g>60) cout<<"You passed";

else cout<<“You failed";}// ================== Main Fct ==================int main(){

int n = Read_Grade(); Display_Msg(n);return 0;

}

Using Modules (4.3)

Page 35: CS 141 Computer Programming 1

35

References and Reference Parameters Call by value

Copy of data passed to function Changes to copy do not change original Prevent unwanted side effects

Call by reference Function can directly access data Changes affect original

Page 36: CS 141 Computer Programming 1

36

References and Reference Parameters Reference parameter

Alias for argument in function call Passes parameter by reference

Use & after data type in prototype void myFunction( int &data ) Read “data is a reference to an int”

Function call format the same However, original can now be changed

Page 37: CS 141 Computer Programming 1

37

Example1

1 2 // Comparing pass-by-value and pass-by-reference3 // with references.4 #include <iostream>5 6 using std::cout;7 using std::endl;8 9 int squareByValue( int ); // function prototype10 void squareByReference( int & ); // function prototype11 12 int main()13 {14 int x = 2;15 int z = 4;16 17 // demonstrate squareByValue18 cout << "x = " << x << " before squareByValue\n";19 cout << "Value returned by squareByValue: "20 << squareByValue( x ) << endl; 21 cout << "x = " << x << " after squareByValue\n" << endl;22

Notice the & operator, indicating pass-by-reference.

Page 38: CS 141 Computer Programming 1

38

Example1(Cont.)23 // demonstrate squareByReference24 cout << "z = " << z << " before squareByReference" << endl;25 squareByReference( z );26 cout << "z = " << z << " after squareByReference" << endl;27 28 return 0; // indicates successful termination29 } // end main30 31 // squareByValue multiplies number by itself, stores the 32 // result in number and returns the new value of number 33 int squareByValue( int number ) 34 { 35 return number *= number; // caller's argument not modified36 37 } // end function squareByValue 38 39 // squareByReference multiplies numberRef by itself and 40 // stores the result in the variable to which numberRef 41 // refers in function main 42 void squareByReference( int &numberRef ) 43 { 44 numberRef *= numberRef; // caller's argument modified45 46 } // end function squareByReference

Changes number, but original parameter (x) is not modified.

Changes numberRef, an alias for the original parameter. Thus, z is changed.

Page 39: CS 141 Computer Programming 1

39

Outputx = 2 before squareByValueValue returned by squareByValue: 4x = 2 after squareByValue 

z = 4 before squareByReferencez = 16 after squareByReference

Page 40: CS 141 Computer Programming 1

40

Example 2

#include <iostream>using std::cout;using std::endl;

int main(){ int x = 3; int &y = x; // y refers to (is an alias for)

x

cout << "x = " << x << endl << "y = " << y << endl;

y = 7; // actually modifies x cout << "x = " << x << endl << "y = " << y

<< endl; return 0; // indicates successful

termination} // end main

x = 3y = 3x = 7y = 7

Page 41: CS 141 Computer Programming 1

41

Function Overloading Function overloading

Functions with same name and different parameters

Should perform similar tasks I.e., function to square ints and function to

square floatsint square( int x) {return x * x;}float square(float x) { return x * x; }

Overloaded functions distinguished by signature Based on name and parameter types

(order matters)

Page 42: CS 141 Computer Programming 1

42

Example112 // Using overloaded functions.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function square for int values 9 int square( int x ) 10 { 11 cout << "Called square with int argument: " << x << endl;12 return x * x; 13 14 } // end int version of function square 15 16 // function square for double values 17 double square( double y ) 18 { 19 cout << "Called square with double argument: " << y << endl;20 return y * y; 21 22 } // end double version of function square 23

Overloaded functions have the same name, but the different parameters distinguish them.

Page 43: CS 141 Computer Programming 1

43

Example1(Cont.)24 int main()25 {26 int intResult = square( 7 ); // calls int version27 double doubleResult = square( 7.5 ); // calls double version28 29 cout << "\nThe square of integer 7 is " << intResult30 << "\nThe square of double 7.5 is " << doubleResult 31 << endl; 32 33 return 0; // indicates successful termination34 35 } // end main

Called square with int argument: 7Called square with double argument: 7.5 The square of integer 7 is 49The square of double 7.5 is 56.25

The proper function is called based upon the argument (int or double).

Page 44: CS 141 Computer Programming 1

44

Example 2#include <iostream>using std::cout;using std::endl;

// function multiply for two parameters

int multi( int x, int y )

{

return x * y;

}

// function multiply for one parameter

int multi( int y ) {

return y * 1;

}

int main(){ cout << multi( 7,5 ); // calls 2

parameter version cout << endl; cout << multi( 7 ); // calls 1 parameter

version cout << endl; return 0; }

Page 45: CS 141 Computer Programming 1

45

Example 3#include <iostream>using std::cout;using std::endl;

// function multiply for two parameters int multi( int x, double y )

{ return x * y; }

// function multiply for two parameter but with different order

double multi( double y , int x) { return y * x; }int main(){ cout << multi( 7,5.5 ); // calls int,double

version cout << endl; cout << multi( 7.5,3 ); // calls double,int

version cout << endl; return 0; }

Page 46: CS 141 Computer Programming 1

46

Passing Array to Functions Static Array Arrays passed-by-reference Individual array elements passed-by-

value

Page 47: CS 141 Computer Programming 1

47

Examples Using Arrays

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

Recall static storage

Page 48: CS 141 Computer Programming 1

48

Example // Static arrays are initialized to zero. #include <iostream> using namespace std ; void staticArrayInit( void ); // function prototype void automaticArrayInit( void ); // function prototype

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; // indicates successful termination } // end main

Page 49: CS 141 Computer Programming 1

49

26 // function to demonstrate a static local array27 void staticArrayInit( void )28 {29 // initializes elements to 0 first time function is called30 static int array1[ 3 ]; 31 32 cout << "\nValues on entering staticArrayInit:\n";33 34 // output contents of array135 for ( int i = 0; i < 3; i++ )36 cout << "array1[" << i << "] = " << array1[ i ] << " ";37 38 cout << "\nValues on exiting staticArrayInit:\n";39 40 // modify and output contents of array141 for ( int j = 0; j < 3; j++ )42 cout << "array1[" << j << "] = " 43 << ( array1[ j ] += 5 ) << " ";44 45 } // end function staticArrayInit46

Static array, initialized to zero on first function call.

Array data is changed; the modified values stay.

Example(Cont.)

Page 50: CS 141 Computer Programming 1

50

47 // function to demonstrate an automatic local array48 void automaticArrayInit( void )49 {50 // initializes elements each time function is called51 int array2[ 3 ] = { 1, 2, 3 };52 53 cout << "\n\nValues on entering automaticArrayInit:\n";54 55 // output contents of array256 for ( int i = 0; i < 3; i++ )57 cout << "array2[" << i << "] = " << array2[ i ] << " ";58 59 cout << "\nValues on exiting automaticArrayInit:\n";60 61 // modify and output contents of array262 for ( int j = 0; j < 3; j++ )63 cout << "array2[" << j << "] = " 64 << ( array2[ j ] += 5 ) << " ";65 66 } // end function automaticArrayInit

Automatic array, recreated with every function call.

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

Example(Cont.)

Page 51: CS 141 Computer Programming 1

51

Output

First call to each function: Values on entering staticArrayInit:array1[0] = 0 array1[1] = 0 array1[2] = 0Values 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 

Static local array is initialized to zero

Add 5 to each element

Initiliazed with values 1,2 and 3

First Time Calling

Add 5 to each element

Page 52: CS 141 Computer Programming 1

52

Output Second call to each function: Values on entering staticArrayInit:array1[0] = 5 array1[1] = 5 array1[2] = 5Values 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

Contains the modified values

Add 5 to each element

Initiliazed with values 1,2 and 3

Second Time Calling

Add 5 to each element

Page 53: CS 141 Computer Programming 1

53

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 If the size is not passed , place the size on

global variable.

Page 54: CS 141 Computer Programming 1

54

Passing Arrays to Functions

Functions can modify original array data Value of name of array is address of first

elemento Function knows where the array is storedo Can change original memory locations

Arrays passed-by-reference

Individual array elements passed-by-value Like regular variables square( myArray[3] );

Page 55: CS 141 Computer Programming 1

55

Passing Arrays to Functions

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 [] );

Functions taking arrays

Page 56: CS 141 Computer Programming 1

56

Example // Passing arrays and individual array elements to functions. #include <iostream> using namespace std; #include <iomanip> void modifyArray( int [], int ); // appears strange void modifyElement( int ); int main() { const int arraySize = 5; // size of array a int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // 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 ]; cout << endl;

Syntax for accepting an array in parameter list.

Page 57: CS 141 Computer Programming 1

57

Example(Cont.)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 termination 50 } // 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.

Page 58: CS 141 Computer Programming 1

58

Example(Cont.) 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.

Page 59: CS 141 Computer Programming 1

59

OutputEffects of passing entire array by reference: The values of the original array are: 0 1 2 3 4The values of the modified array are: 0 2 4 6 8  Effects of passing array element by value: The value of a[3] is 6Value in modifyElement is 12The value of a[3] is 6

Page 60: CS 141 Computer Programming 1

60

Exercise 1:Problem

Write a program that reads an array of n integers, then use a function findNumPos that takes two parameters the array and a number to be found, then returns the position of a number x in the array.Note: the maximum array size is 20

How many integers you want to enter: 7Enter the numbers: 10 8 200 8 1 0 5Which number you want to find its position: 200200 is at position(index) 2

Page 61: CS 141 Computer Programming 1

61

Page 62: CS 141 Computer Programming 1

62

Exercise 2:Compilation Error

#include <iostream>using std::cin;using std::cout;using std::endl;

int main(){ int a = 10; cout << a << " squared: " << square( a ) <<

endl; return 0; }

int square( int x ){ return x * x; }

Error: function undeclared before use'square': identifier not found

Page 63: CS 141 Computer Programming 1

63

Exercise 2:Solution 1

#include <iostream>using std::cin;using std::cout;using std::endl;

int square( int x ){ return x * x; }

int main(){ int a = 10; cout << a << " squared: " << square( a ) <<

endl; return 0; }

Page 64: CS 141 Computer Programming 1

64

Exercise 2:Solution 2

#include <iostream>using std::cin;using std::cout;

using std::endl;

int square( int ); // prototype for function square

int main(){ int a = 10;

cout << a << " squared: " << square( a ) << endl; return 0;

}

int square( int x ){ return x * x; }

Page 65: CS 141 Computer Programming 1

65

Exercise 3:Compilation Error

#include <iostream>using std::cin;using std::cout;using std::endl;

int square( int x ){ return x * x; }

void square( int x) { cout<< x * x; }

int main(){ return 0; } // end main

• Two functions in the global(file) scope• They have the same signature:

square(int)• This results in a compilation error:

'square' : redefinition