Why functions? Next Slide

Often, we need to use one set of code over and over again. Functions allow us to write code once and reuse it many times.

For example, we might use a function to calculate the length of the hypotenuse of a right triangle:

cout << "Enter triangle width: ";
cin >> w;
cout << "Enter triangle height: ";
cin >> h;
cout << "The hypotenuse is " << hypotenuse(w, h) << endl;

Using functions can act as documentation (if they are given appropriate names). Compare the instant recognition of hypotenuse(w, h) to sqrt(w*w+h*h).


BU CAS CS - Functions
Copyright © 1993-2000 by Robert I. Pitts <rip at bu dot edu>. All Rights Reserved.