Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions and an Introduction to Recursion.  Write a program for learn C++ subfunction.  Exercise: ◦ Please implement the following functions:  double.

Similar presentations


Presentation on theme: "Functions and an Introduction to Recursion.  Write a program for learn C++ subfunction.  Exercise: ◦ Please implement the following functions:  double."— Presentation transcript:

1 Functions and an Introduction to Recursion

2  Write a program for learn C++ subfunction.  Exercise: ◦ Please implement the following functions:  double derivative(double a, double n, double x0);  receives three parameters and returns the slope of ax n at x 0.  double integral(double a, double n, double x1, double x2);  receives four parameters and returns the area enclosed by ax n, y=0, x=x 1 and x=x 2.

3  To compute the slope S between (x 1, y 1 ) and (x 2, y 2 ): x y x2x2 x1x1 (x 1, y 1 ) (x 2, y 2 ) y 2 - y 1 x 2 - x 1

4  To compute the slope of the tangent line at x 0 : x0x0 x y x 0 +dx f(x)f(x)

5  When dx approaches 0, then the slope of the tangent line at x 0 is called the derivative of f(x) at x 0. ◦ We would use a very small dx to approximate the derivative.

6  Program framework prototype implementation

7  You can use the #define directive to give a meaningful name to a constant in your program. ◦ Example:  DX will be replaced by 0.0001 #include #define DX 0.0001 int main () { cout << DX << endl; return 0; } #include #define DX 0.0001 int main () { cout << DX << endl; return 0; } 0.0001

8  Remember the only way for a sub-function to communication with outside is through its parameters and return value! Copy value Output x Parameter int value Return Value S argument int x3 int value = x*x + 2*x + 5; 20

9

10  What the sub-function can only access are its parameters and variables. ◦ Note: do not declare a variable of the same variable name with parameters.

11  How do we compute the area enclosed by ax n, y=0, x=x 1 and x=x 2 ? x y x1x1 x2x2

12  Use rectangles of the same width to cover the enclosed field and then sum up their area x y x1x1 x2x2 dx f(x 1 +dx) f(x1)f(x1)f(x 1 +2dx) f(x 1 +3dx) f(x 1 +4dx) f(x 1 +5dx)

13  The measure of area is ◦ The accuracy of area measure depends on how small dx is. x y x1x1 x2x2

14  When dx approaches 0, we can approximate the area below f(x) between x 1 and x 2. ◦ We denote as the integral of f(x) from x 1 to x 2.

15  Program framework

16  Use a very small value to represent dx.  Compute the area of rectangle by multiplying f(x) and dx.  Accumulate the area of rectangles. for (double i = x1; i <= x2; i += DX) { …… }


Download ppt "Functions and an Introduction to Recursion.  Write a program for learn C++ subfunction.  Exercise: ◦ Please implement the following functions:  double."

Similar presentations


Ads by Google