Download presentation
Presentation is loading. Please wait.
1
1 Lecture 14:User-Definded function I Introduction to Computer Science Spring 2006
2
2 #include using namespace std; int main() { int i, j; int k; cin>>i>>j; if (i > j) { k = i; } else { k = j; } return 0; } #include using namespace std; /* Function Declarations */ int FindMax(int n1, int n2); int main() { int i, j; int k; cin>>i>>j; k = FindMax(i,j); return 0; } /* Function Definitions */ int FindMax(int n1, int n2) { if (n1 > n2) { return n1; } else { return n2; }
3
3 Functions Functions are like building blocks They allow complicated programs to be divided into manageable pieces Some advantages of functions: A programmer can focus on just that part of the program and construct it, debug it, and perfect it Different people can work on different functions simultaneously Can be used in more than one place in a program or in different programs
4
4 Functions (continued) Functions Called modules Like miniature programs Can be put together to form a larger program
5
5 Predefined Functions In algebra, a function is defined as a rule or correspondence between values, called the function ’ s arguments, and the unique value of the function associated with the arguments If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11 1, 2, and 3 are arguments 7, 9, and 11 are the corresponding values
6
6 Question What should we do if we want to calculate x y ? Answer: use standard(library) function pow(x,y) Pow(x,y)=x y Parameters(arguments) x and y are of type double the value of pow(x,y) is type double: we say function pow is of type double
7
7 Use of standard function pow #include using namespace std; int main() { double u,v; double result; u = 4.2; v = 3.0; return 0; } #include result=pow(u, v); cout << u << " to the power of " << v << " = " << pow(u, v) << endl; cout << "u = " << u << endl; u = u + pow(3, 3);
8
8 Predefined Functions (continued) Some of the predefined mathematical functions are: sqrt(x) pow(x,y) floor(x) Predefined functions are organized into separate libraries I/O functions are in iostream header Math functions are in cmath header
9
9 The Power Function (pow) pow(x,y) calculates x y, pow(2,3) = 8.0 pow returns a value of the type double x and y are called the parameters (or arguments) of the function pow Function pow has two parameters
10
10 The sqrt and floor Functions The square root function sqrt(x) Calculates the non-negative square root of x, for x >= 0.0 sqrt(2.25) is 1.5 Type double and has only one parameter
11
11 The sqrt and floor Functions (continued) The floor function floor(x) Calculates largest whole number not greater than x floor(48.79) is 48.0 Type double and has only one parameter
12
12
13
13 End of lecture 14 Thank you!
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.