Function Examples
CS-150, Fall ’02, Dr. C. S. Tritt

sum.cpp –

/*

This program demonstrates sample function calls, pass by value,
default arguments, some I/O formatting and some I/O error control.

File: sum.cpp
Version: 4.1
Created: 9/24/96
Last updated: 10/16/02
Written by: Dr. C. S. Tritt

*/

#include <iostream>  // Header for stream I/O.
#include <iomanip> // Header for I/O manipulators.

using namespace std;

// Declare the sum function.

double sum(double x, double y = 73.15); // Function prototype.

// Main program

int main(void)
{
// Declare variables. Some programmers like to declare variables just
// before use.  I declare all of mine at the top of each function.

	int p; //  Output numeric precision.
	double a; // Units and description of a.
	double b; // Units and description of b.
	
	cout.setf(ios::showpoint); // Show decimal.  Good until changed.

	cout << "Enter the output precision (an integer): ";
	cin >> p;
	if (!cin)
	{
		cout << "Input error.  Aborting.\n";
		return 1;
	}
	cout << setprecision(p);  // Set precision.  Good until changed.

	cout << "Enter two real numbers to be summed: ";
	cin >> a >> b;
	if (!cin)
	{
		cout << "Input error.  Aborting.\n";
		return 2;
	}

	cout << "Entered values were a = " << a << " and b = "
   << b << endl;
	cout << "so sum(a, b) = " << sum(a, b) << endl;
	cout << "and sum(a) = " << sum(a) << endl;

	return 0;
}

double sum(double x, double y)
{
/*
    This function returns the sum of its arguments with the second
    argument having a weird default value.
*/ 
	
	return x + y;
}

swap.cpp –

// Sample Function Call with Argument Change
//
// File: SWAP.CPP
// Version: 4.1
// Created: 9/24/96
// Last updated: 10/16/02
// Written by: Dr. C. S. Tritt
//
#include <iostream>  // Header for stream I/O.

using namespace std;

void swap(double & x, double & y); // Function prototype.
 
// Main program

int main()
{

// Declare and initialize variables.

	double a = 2.5; // Units and description of a.
	double b = 7.5; // Units and description of b.

// Demonstrate swapping using pass by reference.

	cout << "Before swapping...\n";
	cout << "a = " << a << " and b = " << b << "\n";
	swap(a, b);
	cout << "After swapping...\n";
	cout << "a = " << a << " and b = " << b << "\n";

	return 0;
}

void swap(double & x, double & y)
{
/*
   This function swaps the values of its two arguments. Note the
   use of references so argument changes are returned. Spacing around
   "&" symbols is not critical.
*/
	double hold;
	hold = x;
	x = y;
	y = hold;
	return;
}