1 / 72

Functions

Learn about the importance and advantages of using functions in C and C++ programming languages. Understand how to define, call, and use both internal and external functions to improve code organization and reusability.

nbaugh
Download Presentation

Functions

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 Programming Applications

  2. Functions • every C program must have a function called main • program execution always begins with function main • any other functions are subprograms and must be called

  3. Advantages of Functions • Functions separate the concept (what is done) from the implementation (how it is done). • Functions make programs easier to understand. • Functions can be called several times in the same program, allowing the code to be reused.

  4. Every C function has 2 parts int main ( ) heading { body block return 0; }

  5. C++ Functions • C++ allows the use of both internal (user-defined) and external functions. • External functions (e.g., abs,ceil,rand, sqrt, etc.) are usually grouped into specialized libraries (e.g., iostream, stdlib,math, etc.)

  6. Program with Several Functions main function Square function Cube function

  7. Writing Functions • Need to specify: • the name of the function • its parameters • what it returns • The block of statements is called the “function body”

  8. Function Input and Output

  9. Function Definition float CircleArea (float r) { const float Pi = 3.1415; return Pi * r * r; } Function name Formal parameter Return type Local object definition Function body Return statement

  10. Function Invocation cout << CircleArea(MyRadius) << endl; Actual parameter To process the invocation, the function that contains the insertion statement is suspended and CircleArea() does its job. The insertion statement is then completed using the value supplied by CircleArea().

  11. Review: Pass By Value void foo () { int i = 7; baz (i); } void baz (int j) { j = 3; } 7 local variable i (stays 7) Think of this as declaration with initialization, along the lines of: int j = what baz was passed; parameter variable j (initialized with the value passed to baz, and then is assigned the value 3) 7 → 3

  12. #include <iostream> using namespace std; float CircleArea(float r); // main(): manage circle computation int main() { cout << "Enter radius: "; float MyRadius; cin >> MyRadius; float Area = CircleArea(MyRadius); cout << "Circle has area " << Area; return 0; } // CircleArea(): compute area of radius r circle float CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r; }

  13. Function definition Function call Example1: hello.cpp #include <iostream> /* * Print a simple greeting. */ void sayHello ( void ) { cout<<“Hello World!\n”; } /* * Call a function which prints a * simple greeting. */ int main() { sayHello(); return 0; }

  14. Function name Function body Example1: hello.cpp #include <iostream> /* * Print a simple greeting. */ void sayHello ( void ) { cout<<“Hello World!\n”; } /* * Call a function which prints a * simple greeting. */ int main() { sayHello(); return 0; }

  15. Return type Formal Parameter List Example1: hello.cpp #include <iostream> /* * Print a simple greeting. */ void sayHello ( void ) { cout<<“Hello World!\n”; } /* * Call a function which prints a * simple greeting. */ int main() { sayHello(); return 0; }

  16. Example2: sort.cpp /* Print two numbers in order. */ void Sort ( int a, int b ) { int temp; if ( a > b ) { cout<<b<< a; } else { cout<<a<<b; } } Parameters

  17. Formal parameters Actual parameters Example2: sort.cpp /* Print two numbers in order. */ void Sort ( int a, int b ) { int temp; if ( a > b ) { cout<<b<< a; } else { cout<<a<<b; } } int main() { int x = 3, y = 5; Sort ( 10, 9 ); Sort ( y, x + 4 ); return 0; }

  18. Function definition Function call #include <iostream> float Average ( int X, int Y, int Z ) { float AVG; AVG = (X+Y+Z)/ 3.0; return AVG; } void main(void) { int a,b,c; float AVG; a = 5; b = 6; c = 2; AVG = Average (a, b, c); cout<<“Average” <<AVG; } Example3: Average.cpp 18

  19. Two Kinds of Functions Value-Returning Void Always returns a single value to its caller and is called from within an expression. Never returns a value to its caller, and is called as aseparate statement.

  20. Range.cpp #include <iostream> using namespace std; int PromptAndRead(); int Sum(int a, int b); int main() { int FirstNumber = PromptAndRead(); int SecondNumber = PromptAndRead(); int RangeSum = Sum(FirstNumber , SecondNumber); cout << "The sum from " << FirstNumber << " to " << SecondNumber << " is " << RangeSum << endl; return 0; }

  21. Range.cpp // PromptAndRead(): prompt & extract next integer int PromptAndRead() { cout << "Enter number (integer): "; int Response; cin >> Response; return Response; } // Sum(): compute sum of integers in a ... b int Sum(int a, int b) { int Total = 0; for (int i = a; i <= b; ++i) { Total += i; } return Total; }

  22. Trace void main() { int a = 2; int b = 2; int c = 3; b = mult( a , c ) ; cout<<a << b << c ; c = squares( a , b ) ; cout<<a << b << c ; } int mult (int x, int y ) { return x * y; } int squares ( int p , int q ) { int r = p * p + q * q ; return r ; }

  23. Absolute Value (alternative) • Note that it is possible to omit the function prototype if the function is placed before it is called. #include <iostream> using namespace std; int absolute(int x){ if (x >= 0) return x; elsereturn -x; } int main(){ int num, answer; cout << "Enter an integer (0 to stop): "; cin >> num; while (num!=0){ answer = absolute(num); cout << "The absolute value of " << num << " is: " << answer << endl; cin >> num; } return 0; }

  24. Example4 Write a C++ program to read two integer numbers and Use function to find the maximum of them

  25. Example5 Write a complete program that asks for radius of a circle and calculates its area using a function with return value of float type.

  26. Call by Value & Call by Reference

  27. Call by Value & Call by Reference • Call by Value: The Formal Parameters are not the Actual Parameters. Only Values from the Actual Parameters are passed to the Formal Parameters. • Call by Reference: The Formal Parameters are referring to the Actual Parameters.

  28. Call by Value & Call by Reference • Call by Value: Changes in the Formal Parameters Will not affect the Actual Parameters. • Call by Reference: Changes in the Formal Parameters Will affect the Actual Parameters.

  29. Call By Value

  30. Passing Information to Parameters by Value • Example: int val=5; evenOrOdd(val); • evenOrOdd can change variable num, but it will have no effect on variable val val num 5 5 argument in calling function parameter in evenOrOdd function

  31. Example showSum(value1, value2, value3); //function call function header void showSum(int num1, int num2, int num3){ cout << num1 + num2 + num3 << endl;}

  32. Example6: bad_swap.cpp /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; cout<<a<< b; } int main() { int a = 3, b = 5; cout<<a<<b; badSwap ( a, b ); cout<<a<<b; return 0; } Output: 3 5

  33. Example6: bad_swap.c /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; cout<<a<< b; } int main() { int a = 3, b = 5; cout<<a<<b; badSwap ( a, b ); cout<<a<<b; return 0; } Output: 3 5 5 3

  34. Example6: bad_swap.c /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; cout<<a<< b; } int main() { int a = 3, b = 5; cout<<a<<b; badSwap ( a, b ); cout<<a<<b; return 0; } Output: 3 5 5 3 3 5 34

  35. Example6: bad_swap.c /* Swap the values of two variables. */ void badSwap ( int a, int b ) { int temp; temp = a; a = b; b = temp; cout<<a<< b; } int main() { int a = 3, b = 5; cout<<a<<b; badSwap ( a, b ); cout<<a<<b; return 0; } Output: 3 5 5 3 3 5 35

  36. Call By Reference

  37. Reference Parameters • If the formal argument declaration is a reference parameter then • Formal parameter becomes an alias for the actual parameter • Changes to the formal parameter change the actual parameter • Function definition determines whether a parameter’s passing style is by value or by reference • Reference parameter form ptypei &pnamei void Swap(int &a, int &b)

  38. Review: Pass By Reference again declaration with initialization int & j = what baz was passed; void foo () { int i = 7; baz (i); } void baz (int & j) { j = 3; } 7 → 3 local variable i j is initialized to refer to the variable that was passed to baz: when j is assigned 3, the passed variable is assigned 3. 7 → 3 argument variable j

  39. What About Pointers as By-Value Arguments? j is initialized with the address (value) that was passed to baz void foo () { int i = 7; baz (&i); } void baz (int * j) { *j = 3; } local variable i 7 → 3 address-of operator dereferencing j gives the location to which it points, so the variable whose address was passed is assigned 3. 0x74bead00 argument variable j dereference operator

  40. Reconsider int main() { int Number1 = PromptAndRead(); int Number2 = PromptAndRead(); if (Number1 > Number2) { Swap(Number1, Number2); } cout << "The numbers in sorted order: " << Number1 << ", " << Number2 << endl; return 0; }

  41. Default Parameters • Consider bool GetNumber(int &n, istream &sin = cin) { return sin >> n ; } • Some possible invocations int x, y, z; ifstream fin("Data.txt"); GetNumber(x, cin); GetNumber(y); GetNumber(z, fin); • Design your functions for ease and reuse!

  42. Using void Swap(int &a, int &b) { int Temp = a; a = b; b = Temp; return; } Passed by reference -- in aninvocation the actualparameter is given ratherthan a copy Return statement notnecessary for void functions

  43. Remember !! • void Average ( int x, y, z)  Wrong • void Average (int x, int y, int z)  Correct

  44. What is in a prototype? • A prototype looks like the function heading but must end with a semicolon”;” • It has no body. • Usually located at the beginning of the program to declare all the functions to be used. int Cube( int n); /* prototype */

  45. int main() { int a, b=1, c=2, d=3, e; a=d; e=c; a=1; Cout<<e<< c<< d; b=SomeFunction(&c); Cout<<b<< c<< e; return 0; }  int SomeFunction(int *m) { *m= (*m)+1; return (*m); }

  46. #include <stdio.h> void duplicate (int a, int *b, int *c) { *b=a; a=1; *c=2; }   int Star(int a, int b) {  int c=0; int i;  for(i=0 ; i<2 ; i++) {

  47.  duplicate ( c, &a, &b); a++; b++; c++; Cout<<a<< b<< c; }  return a; }   void main (void) { int x=1, y=3, z=7; x = Star(y, z); Cout<<x<< y<< z; }

  48. Function Overloading • A function name can be overloaded • Two functions with the same name but with different interfaces • Typically this means different formal parameter lists • Difference in number of parameters Min(a, b, c) Min(a, b) • Difference in types of parameters Min(10, 20) Min(4.4, 9.2)

  49. Function Overloading int Min(int a, int b) { cout << "Using int min()" << endl; if (a > b) return b; else return a; } double Min(double a, double b) { cout << "Using double min()" << endl; if (a > b) return b; else return a; }

  50. Function Overloading int main() { int a = 10; int b = 20; double x = 4.4; double y = 9.2; int c = Min(a, b); cout << "c is " << c << endl; int z = Min(x, y); cout << "z is " << z << endl; return 0; }

More Related