{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Functions - Functions Motivation All of our programs so far...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Functions Motivation All of our programs so far have lived entirely inside the main() function. In other words, all the code was in one big pile. Mathematics were mixed in with cout statements were mixed with file operations. So far this has not been much of a problem because our programs were small. But we did use functions that others have written. We used the string at() function, the cmath pow() and sqrt() functions, and the open() and is_open() functions from fstream . Even cout and cin are functions, though they are quite a bit more complicated and a little bit special (actually, the stream operators << and >> are functions too but that's beyond the scope of this class). If we did not have, say, sqrt() , at our disposal as functions, we would have had to include our own code for sqrt() (using an approximation method like Newton's) in our big pile of code in main() . This is undesirable. So the moral is that functions allow the programmer to modularize and isolate code, so that in any single function, only one task is being performed. This generally makes code more understandable. You can think of a function as simply code that has a name. The name of some chunk of code is what the code does . The sqrt() function contains only enough code to find the square root of a number, for example. Where to write your own functions For now, we will write functions in the same file as main() so that our programs still consist of just one file. Programs need not be just one file, however, and in the future we will explore ways to split up code into multiple files (by putting functions in different files). Functions can be defined above main() , or they can have just a prototype (or signature ) above main() with the function definition below main() . (Function prototypes or definitions cannot be placed inside other functions.) Here are examples: #include <iostream> using namespace std ; // this is an example of a function fully defined above main() double timesTwo ( double x ) {
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
return 2*x; } int main () { cout << timesTwo(4.5) << endl; } #include <iostream> using namespace std ; // this is an example of just a prototype above main() // the function code itself is below main() double timesTwo ( double ); int main () { cout << timesTwo(4.5) << endl; } double timesTwo ( double x ) { return 2*x; } The importance of where the function is defined (above main()
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}