1 / 41

Functions: - using Library functions - writing our own

Functions: - using Library functions - writing our own. Please read Sections 3.1 and 3.2 in the text. programs solve math problems. an arithmetic expression: x = 4 * 4 * 4; a library call: x = pow( 4, 3 ); // raise 4 to the 3 rd power, using a program someone else wrote

apria
Télécharger la présentation

Functions: - using Library functions - writing our own

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions:- using Library functions- writing our own Please read Sections 3.1 and 3.2 in the text

  2. programs solve math problems • an arithmetic expression: x = 4 * 4 * 4; • a library call: x = pow( 4, 3 ); // raise 4 to the 3rd power, using a program someone else wrote • write your own function (e.g. if you don't have access to math.h, for some reason): x = powerOf( 4.0, 3 ); // raise 4.0 to the 3rd power

  3. #include <math.h> a math library x = pow( 12, 2 ); // x is assigned 122 " function "

  4. functions a math library x = pow( 12, 2 ); that's what parenthesis are for!! PARAMETERS sent TO a function RESULT returned FROM a function

  5. the term "CALL" • means that you invoke a function from main( ) or another function, by sending data to a function, and receiving its answer int ans = 0; // declare a variable to receive results ans = pow(2,2);

  6. note the value passed TO the function math.h functionshttp://www.cplusplus.com/reference/clibrary/cmath/ Function Description abs(x) computes absolute value of an int x fabs(x) computes absolute value of a double x sqrt(x) computes square root of x, where x >=0 pow(x,y) computes xy ceil(x) nearest integer larger than x floor(x) nearest integer smaller than x exp(x) computes ex log(x) computes ln x, where x >0 log10(x) computes log10x, where x>0 sin(x) sine of x, where x is in radians cos(x) cosine of x, where x is in radians tan(x) tangent of x, where x is in radians

  7. function spec

  8. Pi // M_PI is a math.h variable that // holds 3.14159… #include <math.h> double x = 0.0; double y = M_PI;

  9. use of a library function #include <math.h> double x = 0.0; double y = M_PI; x = cos( 2.0 * y ); cout << x ; // or cout << cos( 2.0 * y ); // yields the same thing

  10. note that! • in C++, there is no difference between • an actual number • a variable that holds an actual number • a math formula using *, / +, - • a math function that calculates and returns an actual number • or any function that returns an actual number

  11. Write our own functions • Formal C++ Definition – • Collection of code to perform a particular task • Three important parts when using a function • Function Prototype // introducing the function to program, at the top • Function Definition // Writing the task the function is supposed to do • Function Call //invoking the function to do the task

  12. example (3 parts in red) #include<iostream>using namespace std;int add1( int x, int y ); // function prototype int main() { int sum = 0; int q, z; cout<<"Enter two numbers"<<endl; cin>>q; cin>>z; sum = add1( q, z ); // calling the function cout << "The sum using the first function is " << sum << endl; } // end main int add1(int x, int y) { return (x+y); }

  13. writing our own • we can write functions right in our main program • it involves 6 steps • why? - to isolate code that you want to run (“call”) repeatedly - to provide library-like capabilities x = pow(y, 2); x = yourOwnFunction( a, b, c, d );

  14. Step 1 - think of a good name addTwoNumbers( )

  15. Step 2 - decide what the function needs to do its job addTwoNumbers ( int addend1, int addend2) you can name those variables anything you want, but you have to specify their type

  16. Step 3 - what will the function return as a service? int addTwoNumbers (int addend1, int addend2) note: sometimes it doesn’t return anything.

  17. Step 4 - write the function, outside of the main brackets #include <iostream> using namespace std; int main ( ) { } // end program int addTwoNumbers ( int addend1, int addend2 ) { int sum = 0; sum = addend1 + addend2; return sum; }

  18. Step 5 - Introduce it to main(i.e. put the function definition at the top) #include <iostream> using namespace std; int addTwoNumbers ( int addend1, int addend2 ) ; int main ( ) { } int addTwoNumbers ( int addend1, int addend2 ) { int sum = 0; sum = addend1 + addend2; return sum; }

  19. Step 6 - use (call) the function from main #include <iostream> using namespace std; int addTwoNumbers ( int addend1, int addend2 ) ; int main ( ) { int x, y = 12, z = 44; x = addTwoNumbers ( y, z ); cout << x ; } note: different variables… (the “exchange”)

  20. #include <iostream> using namespace std; int addTwoNumbers ( int addend1, int addend2 ) ; int main ( ) { int x, y = 12, z = 44; x = addTwoNumbers ( y, z ); cout << x ; } int addTwoNumbers ( int addend1, int addend2 ) { int sum = 0; sum = addend1 + addend2; return sum; }

  21. return types functions can return ints, doubles, bools, chars, strings… what if a function doesn't return anything? two input "parameters", no output: void drawLine ( int length, char displayChar );

  22. (upcoming) Lab 4 - use of a void function // this function is called from main // e.g. drawLine( 10, '*' ); void drawLine (int lineLength, char displayChar) { for (int x=1; x <= lineLength; x=x+1) { cout << displayChar; }cout << endl;}

  23. a program to use drawLine

  24. nested for loops

  25. create a function that... • draws an asterisk * at a given place on the output console • there are 80 columns on the output console, so void placePoint( int lineLength ) // where lineLength is 1-80

  26. Drawing a sin curve Use this external function:

  27. drawing a sin curve 1. A FOR loop to loop through degree values from 0 to 180, by 4s for( int t=0; t<=180; t=t+4) { } // end for

  28. drawing a sin curve 2. the variables you'll need double radians=0.0, sinValue=0.0; int normalize=0; // also, M_PI

  29. drawing a sin curve 3. how to calculate a plot point from a degree value // convert degrees to radians (0 to Pi) radians = (t * M_PI) / 180; // calulate a sin value (0 to 1.0) sinValue = sin(radians); // stretch it out to fit on screen normalize = (int)(80.0*sinValue);

  30. drawing a sin curve for( int t=0; t<=180; t=t+4) { radians = (t * M_PI)/ 180; sinValue = sin(radians); normalize = (int)(80*sinValue); placePoint( normalize ); } // end for

  31. The "normalization" step Stretching Shifting for( int t=0; t<=360; t=t+4) { radians = (t * M_PI)/ 180; sinValue = sin(radians); normalize= (int)(40*sinValue)+40; placePoint( normalize ); } // end for for( int t=0;t<=180; t=t+4) { radians = (t * M_PI)/ 180; sinValue = sin(radians); normalize = (int)(80*sinValue); placePoint( normalize ); } // end for this is called BIAS this is called GAIN

  32. But what is function used for? • Imagine an accounting company led by you. • You are responsible for everything • interacting with customer • performing the business tasks • giving the output back to the customer • Now let the company be equivalent to the C++ program you type, then the above functionalities are performed by the main • Hence main is a function

  33. Now you want to delegate some work and you hire more people and assign responsibility to them. • That is what user-defined functions are for – performing specific task given to them • Imagine you have hired two employees to do addition and subtraction of two numbers. • There can be three scenarios.

  34. Scenario-1 • You (main) interact with the user • Ask the user to what he wants to perform – addition or subtraction • Get the two numbers to be added or subtracted • Give the numbers to the correct employee (function) • The function computes and gives the result to you (main) • You (main) give the answer to the user

  35. Sample Function add for scenario 1 The name of the function int add (int x, int y) { return (x+y); } The type of value that will be returned Also called return type The two inputs along with the types the function takes The return statement to give the value back to the main

  36. Scenario-2 • You (main) interact with the user • Ask the user to what he wants to perform – addition or subtraction • Redirect the user to correct employee (function) • Employee (function) gets the two numbers to be added or subtracted • The employee function computes and gives the result to you (main) • You (main) give the answer to the user

  37. Sample Function add for scenario 2 int add ( ) { int x, y, sum; cout<<“Enter two numbers”<<endl; cin>>x; cin>>y; sum = x+y; return sum; } NOTE: No inputs in parenthesis.

  38. Scenario – 3 • You (main) interact with the user • Ask the user to what he wants to perform – addition or subtraction • Redirect the user to correct employee (function) • employee (function) gets the two numbers to be added or subtracted • The function computes the result. • The function itself prints the answer.

  39. Sample Function add for scenario 3 voidadd( ) { int x,y,sum; cout<<“Enter two numbers”<<endl; cin>>x; cin>>y; sum = x+y; cout<<“The sum is “<<sum<<endl; } NOTE: void is the return type of function as the function is not returning anything

  40. Take away message • Employee (function) should have ability to accept input from main • The employee (function) should have ability to return the computed answer back to main.

More Related