Functions Why we use functions C library functions
Functions • Why we use functions • C library functions • Creating our own functions
Why functions • average human mind can hold 6 things at once. (directions example) • Construct a large program from smaller pieces or modules • in C++ the pieces are called functions • final program made up of library pieces plus pieces you write.
C Library Functions • mathematical calculations sqrt, exp, log, sin, cos, tan, pow, etc. • string manipulations strcat, strcpy, strcmp, strstr • character manipulations isalpha, isdigit, islower, isupper, atol • input/output cout, cin, printf, fopen, fclose, fwrite, fread • memory allocation alloc, free • searching and sorting bsearch (binary search), qsort (quick sort) • www. cplus. com
Invoking a library function Functions are called by writing the name of the function, followed by a left parentheses, followed by the argument list, followed by the right parentheses. For example: cout << sqrt (900. 0); This code displays 30
Invoking a library function #include <iostream> #include <cmath> using namespace std; int main() { for (double i = 1; i <= 10; i++) { cout << "The square root of " << i << " is "; cout << sqrt (i) << endl; } return 0; }
Invoking a library function #include <iostream> #include <cmath> using namespace std; int main() { double square. Root; for (double i = 1; i <= 10; i++) { cout << "The square root of " << i << " is "; square. Root = sqrt (i) cout << square. Root << endl; } return 0; }
Functions as black boxes y sqrt square root of y double
Function arguments • constants double root. D 1; rootd 1 = sqrt (900. 0) ; • variables double root. D 1, d 1 = 900. 0; rootd 1 = sqrt (d 1) ; • expressions double root. D 1, d 1 = 900. 0; rootd 1 = sqrt (d 1 + 20) ;
More than one argument x (double) y pow x to the power y (double) #include <cmath> for (double i = 1; i <= 10; i++) { cout << i << " to the power of 10 is "; cout << pow (i, 10) << endl; }
Common programming error using a library function without reading the whole description For example: the pow library function description says “ pow does not recognize integral floating point values greater than 264, such as 1. 0 E 100” A library function will explain it’s deficiences and limitations. Make sure you know what they are before using it!
Exercise - use abort instead #include <fstream> // provides ifstream, ofstream #include <iostream> // provides cout using namespace std; int main() { ifstream infile; infile. open("yards. in"); if (!infile) { cout << "Unable to open input file" << endl; cout << "Abnormal termination program" << endl; return 0; }
Exercise - using rand write a code segment to generate and display 5 random numbers between 0 and 1000. assume srand has already been called with the current time to properly initialize the random generator
function definition return-value-type function-name (argument list) { declarations and statements } Example: int Square (int y) { int result; result = y * y; return result; }
function definition return-value-type function-name (argument list) { declarations and statements } • function-name - any valid identifier. Our standard - verb, each word capitalized (Get. Input) • return-value-type - any valid data type, plus void abort (); • argument list - comma separated list of arguments. Each must have a data type. Okay if function has no arguments. bool Is. Empty();
Example - Square function int main () { int x. Squared, int x = 10; x. Squared = Square (x); cout << “ the square of “ << x << “ is “ << x. Squared; return 0; } int Square (int y) { int result; result = y * y; return result; } What happens to x. Squared, x, y, result? Walk through
variables inside a function are not visible outside the function int main () { int x. Squared; for (int x = 1; x <= 10; x++) { x. Squared = Square (x); cout << x. Squared << “ “ ; } cout << result; // would cause a compiler error return 0; } int Square (int y) { int result; result = y * y; return result; }
y is not visible outside the function int main () { int x. Squared; for (int x = 1; x <= 10; x++) { x. Squared = Square (x); cout << x. Squared << “ “ ; } cout << y; // would cause a compiler error return 0; } int Square (int y) { int result; result = y * y; return result; }
Returning control to caller - no return value void Display. Error. Message(string error. Message) { cout << error. Message << endl; } or void Display. Error. Message(string error. Message) { cout << error. Message << endl; return ; }
Returning control to caller with return value bool Is. Empty() { if (0 == buffer. Count ) return true; else return false; }
function prototype Tells compiler: • type of data returned from function • number of arguments function expects to receive • type of arguments the function expects to receive • order in which those arguments are expected. Example: int Square (int y);
function prototype Compiler must see either the function itself or the function prototype before the function is actually called in the code. int Square (int y); int main () { int x. Squared; for (int x = 1; x <= 10; x++) { x. Squared = Square (x); cout << x. Squared << “ “ ; } return 0; } Function itself may be in a different file as it is with library functions
Area of a Triangle side 1 (float) side 2 (float) side 3 (float) Area. Triangle area of the triangle (float)
#include < iostream> #include < cmath> using namespace std; float Area. Triangle (float side 1, float side 2, float side 3); // prototype int main () { float a, b, c; // the three sides of the triangle float area; cout << endl << "This program calculates the area of a triangle"; cout << endl << "with sides of length 3. 0, 4. 0, and 5. 0" << endl; a = 3. 0; b = 4. 0; c = 5. 0; area = Area. Triangle(a, b, c); cout << endl << "The area of the triangle is " << area << endl; return 0; } /* * PRE: side 1, side 2, and side 3 are positive numbers that * form the sides of a triangle * POST: returns the area of a triangle with sides side 1, * side 2, side 3 */ float Area. Triangle (float side 1, float side 2, float side 3) { float s; // local variable - the semiperimiter s = (side 1 + side 2 + side 3) / 2. 0; return (sqrt ( s * (s - side 1) * (s - side 2) * (s - side 3) ) ); }
variables s side 3 side 2 side 1 6. 0 5. 0 4. 0 3. 0 area c b a 6. 0 5. 0 4. 0 3. 0 s, side 1, side 2, side 3 are variables in the Area. Triangle function area, a, b and c are variables in the main program At runtime a copy of a, b, c is made and used to initialize side 1, side 2 and side 3
miscellaneous • you could skip writing a prototype all together and just put the function ahead of main. Not intuitive. Makes source code hard to read. • you could implement Area. Triangle initially as a stub with no other code except return 0;
1) Write a function named Smallest that takes three integer inputs and returns an integer that is the smallest of the three inputs. Write the prototype for the Smallest function. Write a program that gets 3 integers from a user and displays the smallest 2) Write a function that, given a letter of the alphabet, returns true if the letter is a vowel (lower or uppercase) and returns false if the letter is not a vowel. letter (char) Is. AVowel true if letter is a vowel false if letter is not a vowel 3) Write a program to invoke the Is. AVowel function. Inputs a letter and prints out whether it is or is not a vowel.
Automatic conversions What if the parameter you want to send is different than that expected by the function? double Square (double y); int main () { double x. Squared; for (int x = 1; x <= 10; x++) { x. Squared = Square (x); cout << x. Squared << “ “ ; } return 0; } x converted to double. Works fine.
Automatic conversions What if the parameter you want to send is different than that expected by the function? int Square (int y); int main () { double d 1 = 9. 8; cout << Square (d 1); // displays 81 return 0; } d 1 converted to int. Information is lost. Beware!
Promotion rules • Specify which types can be converted to other types without losing data. • As long as you follow the promotion rules then conversions are okay. • Must promote to a data type higher in the hierarchy
Promotion hierarchy long double float unsigned long int unsigned short int unsigned char
Common programming error • Losing data by allowing the compiler to change a data type and not follow the promotion rules.
Exercises 1) Find the error in each of the following program segments and explain how to fix it. a) int sum (int x, int y) { int result; result = x + y; } b) int sum (int n) { if (0 == n) return 0; else n = n + n; } c) in main program: double x = 1 E 10; cout << "square of 1 E 10 = " << square (x) << endl; int square (int x) return x * x; } {
- Slides: 32