0% found this document useful (0 votes)
32 views

05-Functions in C

The document discusses functions in C++. It covers the general syntax of function definitions, which include the return type, name, and parameter list. It also describes C++ enhancements to functions, such as function overloading, optional parameters, and call by reference. Finally, it provides an example of the simpio.h interface, which exports functions that simplify input/output operations and provide error checking on console input in C++.

Uploaded by

Pranab Phagetra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

05-Functions in C

The document discusses functions in C++. It covers the general syntax of function definitions, which include the return type, name, and parameter list. It also describes C++ enhancements to functions, such as function overloading, optional parameters, and call by reference. Finally, it provides an example of the simpio.h interface, which exports functions that simplify input/output operations and provide error checking on console input in C++.

Uploaded by

Pranab Phagetra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Eric Roberts Handout #5

CS 106B January 9, 2013


Functions in C++

Administrative Essentials

Functions in C++
•• All handouts and course information are on the web site:
http://cs106b.stanford.edu/

•• Extra handouts are placed in the ““Handout Hangout”” in Gates.


•• All CS 106B students must sign up for a section by Sunday at
5:00P.M. The signup form will appear on the web tomorrow:
http://cs198.stanford.edu/section/

Eric Roberts •• All undergraduates must take CS 106B for 5 units. The Axess
CS 106B default is 3 units, and we end up signing lots of petitions each
year to correct this error.
January 9, 2013
•• You need to install the appropriate C++ software for the type
of computer you intend to use. The instructions for doing so
are described in the appropriate version of Handout #7.

Finding the Handout Hangout The Syntax of a Function Definition


•• The general form of a function definition looks essentially the
same as it does in Java:
Gates Computer Science Building
(ground floor)
type name(parameter list) {
statements in the function body
}

where type indicates what type the method returns, name is


the name of the method, and parameter list is a list of variable
declarations used to hold the values of each argument.
•• All functions need to be declared before they are called by
specifying a prototype consisting of the header line followed
by a semicolon.

Computing Factorials C++ Enhancements to Functions


•• The factorial of a number n (which is usually written as n! in •• Functions can be overloaded, which means that you can
mathematics) is defined to be the product of the integers from define several different functions with the same name as long
1 up to n. Thus, 5! is equal to 120, which is 1 x 2 x 3 x 4 x 5. as the correct version can be determined by looking at the
number and types of the arguments. The pattern of arguments
•• The following function definition uses a for loop to compute required for a particular function is called its signature.
the factorial function:
•• Functions can specify optional parameters by including an
int fact(int n) { initializer after the variable name. For example, the function
int result = 1; prototype
for (int i = 1; i <= n; i++) {
result *= i; void setMargin(int margin = 72);
}
return result;
} Indicates that setMargin takes an optional argument that
defaults to 72.
•• C++ supports call by reference, which allows functions to
share data with their callers.
–2–

Call by Reference Call by Reference Example


•• C++ indicates call by reference by adding an ampersand (&) •• The following function swaps the values of two integers:
before the parameter name. A single function often has both
value parameters and reference parameters, as illustrated by void swap(int & x, int & y) {
the solveQuadratic function from Figure 2-3 on page 76, int tmp = x;
x = y;
which has the following prototype: y = tmp;
}
void solveQuadratic(double a, double b, double c,
double & x1, double & x2);
•• The arguments to swap must be assignable objects, which for
•• Call by reference has two primary purposes: the moment means variables.
 It creates a sharing relationship that makes it possible to pass •• If you left out the & characters in the parameter declarations,
information in both directions through the parameter list. calling this function would have no effect on the calling
 It increases efficiency by eliminating the need to copy an arguments because the function would exchange local copies.
argument. This consideration becomes more important when
the argument is a large object.

Libraries and Interfaces The simpio.h Interface


•• Modern programming depends on the use of libraries. When /*
you create a typical application, you write only a tiny fraction * File: simpio.h
* --------------
of the code. * This interface exports a set of functions that simplify
* input/output operations in C++ and provide some error-checking
•• Libraries can be viewed from two perspectives. Code that * on console input.
uses a library is called a client. The code for the library itself */
is called the implementation. #ifndef _simpio_h
#define _simpio_h
•• The point at which the client and the implementation meet is
called the interface, which serves as both a barrier and a
communication channel:

client implementation

interface

The simpio.h Interface The simpio.h Interface


/* /*
* Function: getInteger * Function: getReal
* Usage: int n = getInteger(); * Usage: double x = getReal();
* int n = getInteger(prompt); * double x = getReal(prompt);
* ---------------------------------- * ----------------------------------
* Reads a complete line from cin and scans it as an integer. * Reads a complete line from cin and scans it as a floating-point
* If the scan succeeds, the integer value is returned. If the * number. If the scan succeeds, the floating-point value is
* argument is not a legal integer or if extraneous characters * returned. If the input is not a legal number or if extraneous
* (other than whitespace) appear in the string, the user is * characters (other than whitespace) appear in the string, the
* given a chance to reenter the value. If supplied, the * user is given a chance to reenter the value. If supplied, the
* optional prompt string is printed before reading the value. * optional prompt string is printed before reading the value.
*/ */
int getInteger(std::string prompt = ""); double getReal(std::string prompt = "");
–3–

The simpio.h Interface Exercise: Finding Perfect Numbers


/* •• Greek mathematicians took a special interest in numbers that
* Function: getLine
* Usage: string line = getLine();
are equal to the sum of their proper divisors (a proper divisor
* string line = getLine(prompt); of n is any divisor less than n itself). They called such
* ------------------------------------- numbers perfect numbers. For example, 6 is a perfect
* Reads a line of text from cin and returns that line as a string. number because it is the sum of 1, 2, and 3, which are the
* The newline character that terminates the input is not stored
* as part of the return value. If supplied, the optional prompt
integers less than 6 that divide evenly into 6. Similarly, 28 is
* string is printed before reading the value. a perfect number because it is the sum of 1, 2, 4, 7, and 14.
*/
•• Our first exercise today is to design and implement a C++
std::string getLine(std::string prompt = ""); program that finds all the perfect numbers between two limits
entered by the user, as follows:
#endif
FindPerfect

Enter lower limit: 1


Enter upper limit: 10000
6
28
496
8128

Simulating the fact Function Recursive Functions


•• The easiest examples of recursion to understand are functions
in which the recursion is clear from the definition. As an
example, consider the factorial function, which can be defined
in either of the following ways:
n! = n x (n  1) x (n  2) x . . . x 3 x 2 x 1
1 if n is 0
n! =
n x (n  1)! otherwise

•• The second definition leads directly to the following code,


which is shown in simulated execution on the next slide:
int fact(int n) {
if (n == 0) {
return 1;
RecursiveFactorial } else {
Enter n: 5 return n * fact(n - 1);
5! = 120 }
}

The Recursive Paradigm Exercise: Greatest Common Divisor


•• Most recursive methods you encounter in an introductory One of the oldest known algorithms that is worthy of the title is
course have bodies that fit the following general pattern: Euclid’’s algorithm for computing the greatest common divisor
(GCD) of two integers, x and y. Euclid’’s algorithm is usually
if (test for a simple case) {
Compute and return the simple solution without using recursion. implemented iteratively using code that looks like this:
} else {
int gcd(int x, int y) {
Divide the problem into one or more subproblems that have the same form. int r = x % y;
Solve each of the problems by calling this method recursively. while (r != 0) {
Return the solution from the results of the various subproblems. x = y;
} y = r;
r = x % y;
}
•• Finding a recursive solution is mostly a matter of figuring out return y;
how to break it down so that it fits the paradigm. When you }

do so, you must do two things:


1. Identify simple cases that can be solved without recursion. Rewrite this method so that it uses recursion instead of iteration,
taking advantage of Euclid’’s insight that the greatest common
2. Find a recursive decomposition that breaks each instance of the divisor of x and y is also the greatest common divisor of y and
problem into simpler subproblems of the same type, which you the remainder of x divided by y.
can then solve by applying the method recursively.

You might also like