Functions Programming Applications Functions l every C program

  • Slides: 72
Download presentation
Functions Programming Applications

Functions Programming Applications

Functions l every C program must have a function called main l program execution

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

Advantages of Functions l l l Functions separate the concept (what is done) from

Advantages of Functions l l l 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.

Every C function has 2 parts int main ( ) { heading return 0;

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

C++ Functions l C++ allows the use of both internal (userdefined) and external functions.

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

Program with Several Functions main function Square function Cube function

Program with Several Functions main function Square function Cube function

Writing Functions l l Need to specify: l the name of the function l

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

Function Input and Output

Function Input and Output

Function Definition Return type Function name Formal parameter float Circle. Area (float r) {

Function Definition Return type Function name Formal parameter float Circle. Area (float r) { Local object const float Pi = 3. 1415; definition return Pi * r; } Function body Return statement

Function Invocation Actual parameter cout << Circle. Area(My. Radius) << endl; To process the

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

Review: Pass By Value void foo () { int i = 7; baz (i);

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

#include <iostream> using namespace std; float Circle. Area(float r); // main(): manage circle computation

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

Example 1: hello. cpp Function definition #include <iostream> /* * Print a simple greeting.

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

Example 1: hello. cpp Function name Function body #include <iostream> /* * Print a

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

Example 1: hello. cpp Return type #include <iostream> /* * Print a simple greeting.

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

Example 2: sort. cpp /* Print two numbers in order. */ void Sort (

Example 2: 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 } 16

Example 2: sort. cpp Formal parameters /* Print two numbers in order. */ void

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

Example 3: Average. cpp Function definition #include <iostream> float Average ( int X, int

Example 3: Average. cpp Function definition #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; Function call AVG = Average (a, b, c); cout<<“Average” <<AVG; } 18

Two Kinds of Functions Value-Returning Always returns a single value to its caller and

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

Range. cpp #include <iostream> using namespace std; int Prompt. And. Read(); int Sum(int a,

Range. cpp #include <iostream> using namespace std; int Prompt. And. Read(); int Sum(int a, int b); int main() { int First. Number = Prompt. And. Read(); int Second. Number = Prompt. And. Read(); int Range. Sum = Sum(First. Number , Second. Number);

Range. cpp // Prompt. And. Read(): prompt & extract next integer int Prompt. And.

Range. cpp // Prompt. And. Read(): prompt & extract next integer int Prompt. And. Read() { 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; }

Trace void main() { int a = 2; int b = 2; int c

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 ; }

Absolute Value (alternative( Note that it is possible to omit the function prototype if

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; else return -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; } l

Example 4 Write a C++ program to read two integer numbers and Use function

Example 4 Write a C++ program to read two integer numbers and Use function to find the maximum of them

Example 5 Write a complete program that asks for radius of a circle and

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

Call by Value & Call by Reference

Call by Value & Call by Reference

Call by Value & Call by Reference l l Call by Value: The Formal

Call by Value & Call by Reference l l 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.

Call by Value & Call by Reference l l Call by Value: Changes in

Call by Value & Call by Reference l l 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.

Call By Value

Call By Value

Passing Information to Parameters by Value l Example: int val=5; even. Or. Odd(val); val

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

Example show. Sum(value 1, value 2, value 3); function header //function call void show.

Example show. Sum(value 1, value 2, value 3); function header //function call void show. Sum(int num 1, int num 2, int num 3) { cout << num 1 + num 2 + num 3 << endl; }

Example 6: bad_swap. cpp /* Swap the values of two variables. */ void bad.

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

Example 6: bad_swap. c /* Swap the values of two variables. */ void bad.

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

Example 6: bad_swap. c /* Swap the values of two variables. */ void bad.

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

Example 6: bad_swap. c /* Swap the values of two variables. */ void bad.

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

Call By Reference

Call By Reference

Reference Parameters l If the formal argument declaration is a reference parameter then l

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

Review: Pass By Reference void foo () { int i = 7; baz (i);

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

Arguments? void foo () { int i = 7; baz (&i); } j is

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

Reconsider int main() { int Number 1 = Prompt. And. Read(); int Number 2

Reconsider int main() { int Number 1 = Prompt. And. Read(); int Number 2 = Prompt. And. Read(); if (Number 1 > Number 2) { Swap(Number 1, Number 2); } cout << "The numbers in sorted order: " << Number 1 << ", " << Number 2 << endl;

Default Parameters l Consider bool Get. Number(int &n, istream &sin = cin) { return

Default Parameters l Consider bool Get. Number(int &n, istream &sin = cin) { return sin >> n ; } l Some possible invocations int x, y, z; ifstream fin("Data. txt"); Get. Number(x, cin); Get. Number(y); Get. Number(z, fin);

Using void Swap(int &a, int &b) { int Temp = a; a = b;

Using void Swap(int &a, int &b) { int Temp = a; a = b; Passed by reference -- in an b = Temp; invocation the actual parameter is given rather return; than a copy } Return statement not necessary for void functions

Remember!! l l void Average ( int x, y, z) Wrong void Average (int

Remember!! l l void Average ( int x, y, z) Wrong void Average (int x, int y, int z) Correct

What is in a prototype? • A prototype looks like the function heading but

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 */

int main() { int a, b=1, c=2, d=3, e; a=d; e=c; a=1; Cout<<e<< c<<

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

 #include <stdio. h> void duplicate (int a, int *b, int *c) { *b=a;

#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++) {

 duplicate ( c, &a, &b); a++; b++; c++; Cout<<a<< b<< c; } return

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; }

Function Overloading l A function name can be overloaded l Two functions with the

Function Overloading l A function name can be overloaded l Two functions with the same name but with different interfaces l 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)

Function Overloading int Min(int a, int b) { cout << "Using int min()" <<

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; }

Function Overloading int main() { int a = 10; int b = 20; double

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;

The exit() Function l Terminates execution of a program l Can be called from

The exit() Function l Terminates execution of a program l Can be called from any function l Can pass an int value to operating system to indicate status of program termination l l EXIT_SUCCESS EXIT_FAILURE l Usually used for abnormal termination of program l Requires cstdlib header file

Recursive Function l The recursive function is function calls itself l The function repeat

Recursive Function l The recursive function is function calls itself l The function repeat to call itself with different parameter values.

Trace #include<iostream> int f(int x) { if (x==0) return 0; else if (x>=1) return

Trace #include<iostream> int f(int x) { if (x==0) return 0; else if (x>=1) return x+f(x-1); } void main() { int y=f(0); int z = f(4); Cout<< y<< z; }

Example l l l l l what are the value of fun(7, 1) and

Example l l l l l what are the value of fun(7, 1) and fun(6, 3) int fun (int m, int n) { if(n==1) return m; else return (m+fun(m, n-1)); }

Trace #include<stdio. h> int f(int x){ if (x==0) return 0; else if (x>=1) return

Trace #include<stdio. h> int f(int x){ if (x==0) return 0; else if (x>=1) return x+f(x-1); } void main() { int y=f(0); int z = f(4); Cout<<y<< z; }

Trace #include<iostream> int g(int a) {if (a==0) return 1; Else if(a==1) return 2; Else

Trace #include<iostream> int g(int a) {if (a==0) return 1; Else if(a==1) return 2; Else if (x>=2) return g(a-1)*g(a-2); } void main() {Int y=g(0); Int z = g(1); Int x = g(5) Cout<<y<< z<< x; }

Example What are the values of gcd(7, 21) and gcd(5, 3) int gcd(int m,

Example What are the values of gcd(7, 21) and gcd(5, 3) int gcd(int m, int n) { int r; if (m < n) return gcd(n, m); r = m%n; if (r = = 0) return(n); else return(gcd(n, r));

Example l Write a recursive function MULT to perform integer multiplication mn using addition

Example l Write a recursive function MULT to perform integer multiplication mn using addition operator where n>0.

Example int MULT (int m, int n) { int ans; if( n==1 ) ans=

Example int MULT (int m, int n) { int ans; if( n==1 ) ans= m; else ans = m + MULT (m, n-1); return ans; }

Sheet The value of xy can be calculated as recursive function Write recursive function

Sheet The value of xy can be calculated as recursive function Write recursive function called power() that accept real number and integer number as arguments and return the value of xy

Sheet Write recursive function called Fact() that applies the factorial of integer N as

Sheet Write recursive function called Fact() that applies the factorial of integer N as

Organizing a Parade P(1) = 2 P(2) = 3 P(n) = P(n-1) + P(n-2)

Organizing a Parade P(1) = 2 P(2) = 3 P(n) = P(n-1) + P(n-2) for n > 2

Example l Implements the bisection method for approximation a root of a function in

Example l Implements the bisection method for approximation a root of a function in interval [Xl, Xu]. Approximation the root within epsilon of a root.

Bisection algorithm l Compute x_mid = (xl + xu)/2 l If f(xl)*f(x_mid) <0 l

Bisection algorithm l Compute x_mid = (xl + xu)/2 l If f(xl)*f(x_mid) <0 l Find root by Bisection (xl, x_mid) l Find root by Bisection (x_mid, xu)

The Bisection program double Bis (double xl, double xu) { double root, x_mid; x_mid

The Bisection program double Bis (double xl, double xu) { double root, x_mid; x_mid = (xl +xu)/2. 0; if ((xu – xl) < epslion) || (f (x_mid)<0. 0)) root = x_mid; else if ( f(xl) * f(x_mid)<0. 0) root = Bis (xl, x_mid); else root = Bis(x_mid, xu); return root; }

Example l Write a program that inputs a vector v and call function Normalize

Example l Write a program that inputs a vector v and call function Normalize to display a corresponding unit vector W where

Example l Write a program contains function Mystrlen() to find the length of given

Example l Write a program contains function Mystrlen() to find the length of given string

Example l Write a program to read group of numbers from the user and

Example l Write a program to read group of numbers from the user and then average them after stored them in an array and print the result.

Recursive Solutions l A binary search is recursive l Repeatedly halves the collection and

Recursive Solutions l A binary search is recursive l Repeatedly halves the collection and determines which half could contain the item l Uses a divide and conquer strategy

l l l l l Write a function that satisfies the following definition: Int

l l l l l Write a function that satisfies the following definition: Int is. Sorted (int *array, int n. Elements) { /* array is a pointer to an array of ints. n. Elements is the number of ints in the array. This function returns true if the array elements are sorted in ascending numerical order, and false otherwise. */ }

Example ( Hanoi Game) l The object of game is to transfer the disks

Example ( Hanoi Game) l The object of game is to transfer the disks from the leftmost pole to rightmost pole, without ever placing a larger disk on top of a smaller disk. Only one disk may be moved at a time, and each disk must always be placed on one pole.

The End

The End