Write 2 C++ Programs

profilegina123
assignment11.pptx

C++ Functions

Passing Parameters by Value and by Reference

Passing Parameters

By value

The called routine gets a COPY of the parameters passed

Any changes made to the parameters passed by value are NOT reflected in the calling routine

By reference

The called routine gets the locations (addresses) of the passed parameters

Any changes made to the parameters passed by reference ARE reflected int eh calling routine

Function Return Values

A function may ONLY have one return value

Suppose we want a function that returns MORE THAN ONE value?

Then we have to use passing by reference

Example:

void squareAndCube (int n, int& square, int& cube) {

square = n * n;

cube = n * n * n;

return;

}

Example (Continued)

int main () {

int n = 4;

int sq, cu;

squareAndCube(n, sq, cu);

cout << "The square of " << n << " is " << sq << endl;

cout << "The cube of " << n << " is " << cu << endl;

return;

}

Passing ifstream & ofstream Variables

MUST BE DONE BY REFERENCE

Example:

void prTest (ofstream&); // prototype

int main ( ) {

ofstream outFile ("test.out");

prTest (outFile);

outFile.close( );

return 0;

}

Example (Continued)

void prTest (ofstream& os) {

os << "This is a test" << endl;

return;

}

Assignment 11

6.28 (Perfect Numbers) An integer is a perfect number if it is the sum of its divisors, including 1, but not the number itself. For example, 6 is a perfect number, because 1 + 2 + 3 = 6

Write a function isPerfect that determines whether an integer is a perfect number (returns bool)

Use this function to print to the monitor all perfect numbers between 1 and 1000; this cout is in the main routine!

Also print to a file, perfect.txt, ALL the divisors of each integer to confirm that a perfect number is indeed equal to the sum of its divisors

Open (and close) the file in the main routine; print all file output in the isPerfect function

Sample file output: see sample.docx