SlideShare a Scribd company logo
   Introduction
   Function Definition
   Void function
   Global Vs Local variables
   Random Number Generator
   Recursion
   Function Overloading
   Sample Code
   Experience has shown that the best way to develop and maintain large
    programs is to construct it from smaller pieces(Modules)
   This technique Called “Divide and Conquer”
    Bad Development Approach                              Wise Development Approach

                                                                main()
    main()                         •Easer To                    {
    {                                                             -----
       -----                       Design                         ----
       -----                       Build                       }
       -----                       Debug
       -----                       Extend                      function f1()
       .                           Modify                      {
       .                           Understand                     ---
       .                           Reuse                          ---
       ----                        Better Organization         }
       -----
       -----                                                    function f2()
    Return 0;                                                   {
    }                                                              ---
                                                                   ---
                                                                }
   In FORTRAN Modules Known as Subprograms
   In Pascal Modules known as Procedures &
    Functions
   In C++ Modules Known as Functions & Classes
   Programs use new and “prepackaged” modules
      New: programmer-defined functions and classes
      Prepackaged: from the standard library
      Functions invoked by a function–call-statement which consist of it’s
         name and information it needs (arguments)
        Boss To Worker Analogy
           A Boss (the calling/caller function) asks a worker (the called
         function) to perform a task and return result when it is done.

                                      Boss
                                     Main

                                                                          Worker
Worker               Worker
                                                                   Function Z
Function A           Function B

          Worker          Worker
                                             Note: usual main( ) Calls other
            Function B1       Function B2    functions, but other functions
                                                   can call each other
• Functions   called by writing
        functionName (argument);
        or
        functionName(argument1, argument2, …);
• Example
         cout << sqrt( 900.0 );
    • sqrt (square root) function
    • The preceding statement would print 30
    • All functions in math library return a double
   Function Arguments can be:
-   Constant         sqrt(9);
-   Variable         sqrt(x);
-   Expression sqrt( x*9 + y) ;
                     sqrt( sqrt(x) ) ;
• Calling/invoking a function
   – sqrt(x);
   – Parentheses an operator used to call function
       • Pass argument x
       • Function gets its own copy of arguments
   – After finished, passes back result

        Function Name           argument          Output
                                              3
       cout<< sqrt(9);


        Parentheses used to enclose argument(s)
Math Library Functions Revisited
Method              Description                      Example
ceil( x )           rounds x to the smallest integer ceil( 9.2 ) is 10.0
                    not less than x                  ceil( -9.8 ) is -9.0
cos( x )            trigonometric cosine of x        cos( 0.0 ) is 1.0
                    (x in radians)
exp( x )            exponential function ex          exp( 1.0 ) is 2.71828
                                                     exp( 2.0 ) is 7.38906
fabs( x )           absolute value of x              fabs( 5.1 ) is 5.1
                                                     fabs( 0.0 ) is 0.0
                                                     fabs( -8.76 ) is 8.76
floor( x )          rounds x to the largest integer floor( 9.2 ) is 9.0
                    not greater than x               floor( -9.8 ) is -10.0
fmod( x, y )        remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992
                    point number
log( x )            natural logarithm of x (base e) log( 2.718282 ) is 1.0
                                                     log( 7.389056 ) is 2.0
log10( x )          logarithm of x (base 10)         log10( 10.0 ) is 1.0
                                                     log10( 100.0 ) is 2.0
pow( x, y )         x raised to power y (xy)         pow( 2, 7 ) is 128
                                                     pow( 9, .5 ) is 3
sin( x )            trigonometric sine of x          sin( 0.0 ) is 0
                    (x in radians)
sqrt( x )           square root of x                 sqrt( 900.0 ) is 30.0
                                                     sqrt( 9.0 ) is 3.0
tan( x )            trigonometric tangent of x       tan( 0.0 ) is 0
                    (x in radians)
Fig. 3.2 Math library functions.
   Functions
       Modularize a program
       Software reusability
          Call function multiple times

   Local variables
       Known only in the function in which they are defined
       All variables declared in function definitions are local variables
   Parameters
       Local variables passed to function when called
       Provide outside information
   Function prototype
       Tells compiler argument type and return type of function
       int square( int );
            Function takes an int and returns an int
       Explained in more detail later

   Calling/invoking a function
      square(x);
      Parentheses an operator used to call function
            Pass argument x
            Function gets its own copy of arguments
       After finished, passes back result
   Syntax format for function definition
    returned-value-type function-name (parameter-list)
    {
         Declarations of local variables and Statements
    }

        Parameter list
             Comma separated list of arguments
                 Data type needed for each argument
             If no arguments, use void or leave blank
        Return-value-type
             Data type of result returned (use void if nothing
              returned)
   Example function
    int square( int y )
    {

        return y * y;
    }
   return keyword
      Returns data, and control goes to function’s
       caller
            If no data to return, use return;
       Function ends when reaches right brace
            Control goes to caller
   Functions cannot be defined inside other functions
// Creating and using a programmer-defined function.
        #include <iostream.h>
                                                          Function prototype: specifies
        int square( int );        // function prototype   data types of arguments and
                                                          return values. square
     int main()
                                                          expects an int, and returns
     {
                                                          an int.
        // loop 10 times and calculate and output
        // square of x each time
        for ( int x = 1; x <= 10; x++ )
           cout << square( x ) << " "; // function call

                                                          Parentheses () cause function to be called.
          cout << endl;
                                                          When done, it returns the result.
          return 0;    // indicates successful termination

     } // end main


     // square function definition returns square of an integer
     int square( int y ) // y is a copy of argument to function
     {
        return y * y;     // returns square of y as an int
                                                             Definition         of square. y is a
                                                                     copy of the argument passed.
     } // end function square                                        Returns y * y, or y squared.



1   4    9   16   25   36   49   64   81   100
#include<iostream.h>

int square(int); // prototype                        Output
int cube(int);   // prototype                        1 square=1
main()                                               1 cube=1
{ int i;                                             2 square=4
   for (int i=1;i<=10;i++){                          2 cube=8
                                                     .
                                                     .
        cout<< i<< “square=“ << square(i) << endl;
                                                     .
        cout<< i<< “cube=“   <<cube(i) << endl;      .
   } // end for                                      10 square=100
   return 0;                                         10 cube=1000
} // end main function
int square(int y) //function definition
{
   return y*y; // returned Result
}

int cube(int y) //function definition
{
   return y*y*y; // returned Result
}
// Finding the maximum of three floating-point (real) numbers.
    #include <iostream.h>
    double maximum( double, double, double ); // function prototype
    int main()
    {
       double number1, number2;
       double number3;                                    Function maximum takes 3
                                                        arguments (all double) and
      cout << "Enter three real numbers: ";             returns a double.
      cin >> number1 >> number2 >> number3;

      // number1, number2 and number3 are arguments to the maximum function call
      cout << "Maximum is: "
           << maximum( number1, number2, number3 ) << endl;
      return 0; // indicates successful termination

   } // end main

   // function maximum definition. x, y and z are parameters
   double maximum( double x, double y, double z )
   {
      double max = x;   // assume x is largest     Enter three   real numbers: 99.32 37.3 27.1928
      if ( y > max )    // if y is larger,         Maximum is:   99.32
         max = y;       // assign y to max
                                                   Enter three   real numbers: 1.1 3.333 2.22
      if ( z > max )    // if z is larger,
                                                   Maximum is:   3.333
         max = z;       // assign z to max
      return max;       // max is largest value

   } // end function maximum
   Function prototype contains
      Function name
      Parameters (number and data type)
      Return type (void if returns nothing)
      Only needed if function definition after
       function call
   Prototype must match function definition
      Function prototype
         double maximum( double, double, double );
       Definition
         double maximum( double x, double y, double
            z )
         {
           …
         }
If the Function does not RETURN result, it is called void Function

       #include<iostream.h>
       void add2Nums(int,int);
       main()
       {       int a, b;
               cout<<“enter tow Number:”;
               cin >>a >> b;
               add2Nums(a, b)
               return 0;
       }
       void add2Nums(int x, int y)
       {
               cout<< x<< “+” << y << “=“ << x+y;
       }
If the function Does Not Take Arguments specify this with EMPT Y-LIST OR
    write void inside
     #include<iostream.h>
    void funA();
    void funB(void)
    main()
    {                                    Will be the same
          funA();                            in all cases
          funB();
          return 0;
    }
     void funA()
     {
          cout << “Function-A takes no arqumentsn”;
    }
    void funB()
    {
          cout << “Also Function-B takes No argumentsn”;
    }
   Local variables
      Known only in the function in which they are
       defined
      All variables declared inside a function are local
       variables
   Parameters
      Local variables passed to function when called (passing-
       parameters)
   Variables defined outside and before function main:
        Called global variables
       Can be accessible and used anywhere in the entire
        program
   Omitting the type of returned result defaults to int, but
    omitting a non-integer type is a Syntax Error
   If a Global variable defined again as a local variable in a
    function, then the Local-definition overrides the Global
    defining
   Function prototype, function definition, and function call
    must be consistent in:
        1- Number of arguments
        2- Type of those arguments
        3-Order of those arguments
#include<iostream.h>
int x,y; //Global Variables
int add2(int, int); //prototype
main()
{ int s;
  x = 11;
  y = 22;
  cout << “global x=” << x << endl;
  cout << “Global y=” << y << endl;
  s = add2(x, y);
  cout << x << “+” << y << “=“ << s;
  cout<<endl;
  cout<<“n---end of output---n”;
  return 0;
}                                      global x=11
int add2(int x1,int y1)
{ int x; //local variables             global y=22
  x=44;                                Local x=44
  cout << “nLocal x=” << x << endl;   11+22=33
  return x1+y1;
}
                                       ---end of output---
int sum(int x, int y)
{
   int result;
   result = x+y;
}
this function must return an integer value as indicated in the header
   definition (return result;) should be added
----------------------------------------------------------------------------------------
   -
int sum (int n)
{ if (n==0)
           return 0;
   else
           n+sum(n-1);
}
the result of n+sum(n-1) is not returned; sum returns an improper
   result, the else part should be written as:-
else return n+sum(n-1);
void f(float a);
{
  float a;
  cout<<a<<endl;
}
   ; found after function definition header.
 redefining the parameter a in the function
void f(float a)
{
   float a2 = a + 8.9;
  cout <<a2<<endl;
}
void product(void)
{
   int a, b, c, result;
   cout << “enter three integers:”;
   cin >> a >> b >> c;
   result = a*b*c;
   cout << “Result is” << result;
   return result;
}
 According to the definition it should not return a value , but in the block (body) it
   did & this is WRONG.
  Remove return Result;
       Call by value
    •      A copy of the value is passed
       Call by reference
    •      The caller passes the address of the value


       Call by value
       Up to this point all the calls we have seen are call-by-value, a copy
        of the value (known) is passed from the caller-function to the called-
        function
       Any change to the copy does not affect the original value in the
        caller function
       Advantages, prevents side effect, resulting in reliable software
   Call By Reference
   We introduce reference-parameter, to perform call by reference. The caller
    gives the called function the ability to directly access the caller’s value, and to
    modify it.
   A reference parameter is an alias for it’s corresponding argument, it is stated in
    c++ by “flow the parameter’s type” in the function prototype by an
    ampersand(&) also in the function definition-header.
   Advantage: performance issue

                     void     function_name (type &);// prototype

                     main()
                     {
                               -----
                               ------
                     }
                     void function_name(type &parameter_name)
#include<iostream.h>
int squareVal(int); //prototype call by value function
void squareRef(int &); // prototype call by –reference function
int main()
{ int x=2; z=4;
   cout<< “x=“ << x << “before calling squareVal”;
   cout << “n” << squareVal(x) << “n”; // call by value
   cout<< “x=“ << x << “After returning”
   cout<< “z=“ << z << “before calling squareRef”;
   squareRef(z); // call by reference
   cout<< “z=“ << z<< “After returning squareRef”
   return 0;
}                                                  x=2 before calling squareVal
int squareVal(int a)                               4
{                                                  x=2 after returning
   return a*=a; // caller’s argument not modified z=4 before calling squareRef
}                                                  z=16 after returning squareRef
void squarRef(int &cRef)
{
   cRef *= cRef; // caller’s argument modified
}
   rand function generates an integer between 0 and RAND-
    MAX(~32767) a symbolic constant defined in <stdlib.h>
   You may use modulus operator (%) to generate numbers within a
    specifically range with rand.

//generate 10 random numbers open-range
int x;
for( int i=0; i<=10; i++){
   x=rand();
   cout<<x<<“ “;
}
             -------------------------------------------------------
//generate 10 integers between 0……..49
int x;
for( int i=0; i<10; i++){
   x=rand()%50;
   cout<<x<<“ “;
}
//generate 10 integers between 5…15
int x;
for ( int i=1; i<=10; i++){
  x= rand()%11 + 5;
  cout<<x<<“ “;
}
               ------------------------------------

//generate 100 number as simulation of rolling a
  dice
int x;
for (int i=1; i<=100; i++){
  x= rand%6 + 1;
  cout<<x<<“ “;
}
    the rand( ) function will generate the same set of random
    numbers each time you run the program .
   To force NEW set of random numbers with each new run
    use the randomizing process
   Randomizing is accomplished with the standard library
    function srand(unsigned integer); which needs a
    header file <stdlib.h>

Explanation of signed and unsigned integers:
 int is stored in at least two-bytes of memory and can
  have positive & negative values
 unsigned int also stored in at least two-bytes of
  memory but it can have only positive values 0…..65535
#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>
int main()
{
   int i;
   unsigned num;
   // we will enter a different number each time we run
   cin>>num;
   srand(num);
   for(i=1; i<=5; i++)
        cout<<setw(10)<< 1+rand()%6;
   return 0;
}

                  Output for Multiple Runs
19   6   1   1   4   2   1
18   6   1   5   1   4   4             Different-set of Random
 3   1   2   5   6   2   4               numbers
 0   1   5   5   3   5   5
 3   1   2   5   6   3   4
#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>
int main()
{
   int i;

    for(i=1; i<=5; i++)
        cout<<setw(10)<< 1+rand()%6;
    return 0;
}



                    Output for Multiple Runs
5   3   3   5   4    2
5   3   3   5   4    2                   Same set of numbers for
5   3   3   5   4    2
5   3   3   5   4    2
                                           each run
6   5   3   3   5    4
 Main calls another function…..normal
 A function calls another function2….normal
 A function calls itself ?! Possible?? YES

A recursive function is one that call itself.
   A recursive function is called to solve a problem
   The function knows to solve only the simplest cases
    or so-called base-cases
   Thus if the function called with a base-case, it simply
    returns a result. But if it is called with more complex
    problem, the function divides the problem into two
    conceptual pieces, one knows how to do, and another
    doesn't know what to do.
   The second case/piece must resemble the original
    problem, but be a slightly simpler/smaller version of
    the original problem
   Thus the function launches (calls) a fresh
    copy of itself to work on the smaller
    problem –this is related as a Recursive-
    call/recursive step.

   The function keeps dividing each new sub
    problem into two conceptual pieces until
    eventually terminates after converging on
    the base-case.
   The function thus recognize the base-case
    and returns a result to the previous copy of
    the way up the line until original call of the
    function returns the final result to main.
5!                                   Final value=120
                         5!
                                5!=5*24=120 returned
     5*4!                     5*4!
                                       4!=4*6=24 returned
       4*3!                     4*3!
                                              3!=3*2=6 returned
              3*2!                     3*2!
                                                   2!=2*1=2 returned
                 2*1!                      2*1!
                                                              1
                     1                         1
//Recursive factorial Function
#include<iostream.h>
#include<iomonip.h>
unsigned lion factorial(unsigned long);//prototype
int main()
{
   int num;
   cout<<“enter a positive integer:”;
   cin>>num;
   cout<<“factorial=“<<factorial(num);
   return 0;
}
unsigned long factorial(unsigned long n)
{
   if ( n <= 1) //the base case
        return 1;
   else
        return n * factorial (n - 1);
}
   Function overloading
       Functions with same name and different
        parameters
       Should perform similar tasks
            I.e., function to square ints and function to square floats
             int square( int x) {return x * x;}
             float square(float x) { return x * x; }
   A call-time c++ complier selects the proper function by
    examining the number, type and order of the parameters
User defined functions

More Related Content

What's hot

Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
Dr. Md. Shohel Sayeed
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
Dr. Md. Shohel Sayeed
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
rohassanie
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
Russell Childs
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
chetan_p211
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Ilian Iliev
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
Link list
Link listLink list
Link list
Malainine Zaid
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
Chan Shik Lim
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
nebuta
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
Fabernovel
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
hhliu
 
Materi 6 user definedfunction
Materi 6 user definedfunctionMateri 6 user definedfunction
Materi 6 user definedfunction
Al Frilantika
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
 
Function notes
Function notesFunction notes
Function notes
Hitesh Wagle
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
rik0
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
Zsolt Mészárovics
 
C++ Chapter III
C++ Chapter IIIC++ Chapter III
C++ Chapter III
Sorn Chanratha
 

What's hot (20)

Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Link list
Link listLink list
Link list
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Materi 6 user definedfunction
Materi 6 user definedfunctionMateri 6 user definedfunction
Materi 6 user definedfunction
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Function notes
Function notesFunction notes
Function notes
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
C++ Chapter III
C++ Chapter IIIC++ Chapter III
C++ Chapter III
 

Similar to User defined functions

functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
functions
functionsfunctions
functions
Makwana Bhavesh
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
Chtp405
Chtp405Chtp405
Functions.docx
Functions.docxFunctions.docx
Functions.docx
VandanaGoyal21
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
Sheik Uduman Ali
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
rohassanie
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptcpphtp4_PPT_03.ppt
cpphtp4_PPT_03.ppt
Suleman Khan
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
Victor Stinner
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
Umer Azeem
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
Praveen M Jigajinni
 
The Ring programming language version 1.5.3 book - Part 21 of 184
The Ring programming language version 1.5.3 book - Part 21 of 184The Ring programming language version 1.5.3 book - Part 21 of 184
The Ring programming language version 1.5.3 book - Part 21 of 184
Mahmoud Samir Fayed
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
ssuser823678
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
ssuser2076d9
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
The Ring programming language version 1.7 book - Part 24 of 196
The Ring programming language version 1.7 book - Part 24 of 196The Ring programming language version 1.7 book - Part 24 of 196
The Ring programming language version 1.7 book - Part 24 of 196
Mahmoud Samir Fayed
 

Similar to User defined functions (20)

functions of C++
functions of C++functions of C++
functions of C++
 
functions
functionsfunctions
functions
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Chtp405
Chtp405Chtp405
Chtp405
 
Functions.docx
Functions.docxFunctions.docx
Functions.docx
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptcpphtp4_PPT_03.ppt
cpphtp4_PPT_03.ppt
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Chap 9(functions)
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
The Ring programming language version 1.5.3 book - Part 21 of 184
The Ring programming language version 1.5.3 book - Part 21 of 184The Ring programming language version 1.5.3 book - Part 21 of 184
The Ring programming language version 1.5.3 book - Part 21 of 184
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
The Ring programming language version 1.7 book - Part 24 of 196
The Ring programming language version 1.7 book - Part 24 of 196The Ring programming language version 1.7 book - Part 24 of 196
The Ring programming language version 1.7 book - Part 24 of 196
 

Recently uploaded

How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 

Recently uploaded (20)

How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 

User defined functions

  • 1. Introduction  Function Definition  Void function  Global Vs Local variables  Random Number Generator  Recursion  Function Overloading  Sample Code
  • 2. Experience has shown that the best way to develop and maintain large programs is to construct it from smaller pieces(Modules)  This technique Called “Divide and Conquer” Bad Development Approach Wise Development Approach main() main() •Easer To { { ----- ----- Design ---- ----- Build } ----- Debug ----- Extend function f1() . Modify { . Understand --- . Reuse --- ---- Better Organization } ----- ----- function f2() Return 0; { } --- --- }
  • 3. In FORTRAN Modules Known as Subprograms  In Pascal Modules known as Procedures & Functions  In C++ Modules Known as Functions & Classes  Programs use new and “prepackaged” modules  New: programmer-defined functions and classes  Prepackaged: from the standard library
  • 4. Functions invoked by a function–call-statement which consist of it’s name and information it needs (arguments)  Boss To Worker Analogy  A Boss (the calling/caller function) asks a worker (the called function) to perform a task and return result when it is done. Boss Main Worker Worker Worker Function Z Function A Function B Worker Worker Note: usual main( ) Calls other Function B1 Function B2 functions, but other functions can call each other
  • 5. • Functions called by writing functionName (argument); or functionName(argument1, argument2, …); • Example cout << sqrt( 900.0 ); • sqrt (square root) function • The preceding statement would print 30 • All functions in math library return a double  Function Arguments can be: - Constant sqrt(9); - Variable sqrt(x); - Expression sqrt( x*9 + y) ; sqrt( sqrt(x) ) ;
  • 6. • Calling/invoking a function – sqrt(x); – Parentheses an operator used to call function • Pass argument x • Function gets its own copy of arguments – After finished, passes back result Function Name argument Output 3 cout<< sqrt(9); Parentheses used to enclose argument(s)
  • 7. Math Library Functions Revisited Method Description Example ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0 not less than x ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0 (x in radians) exp( x ) exponential function ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76 floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0 not greater than x floor( -9.8 ) is -10.0 fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992 point number log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128 pow( 9, .5 ) is 3 sin( x ) trigonometric sine of x sin( 0.0 ) is 0 (x in radians) sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x tan( 0.0 ) is 0 (x in radians) Fig. 3.2 Math library functions.
  • 8. Functions  Modularize a program  Software reusability  Call function multiple times  Local variables  Known only in the function in which they are defined  All variables declared in function definitions are local variables  Parameters  Local variables passed to function when called  Provide outside information
  • 9. Function prototype  Tells compiler argument type and return type of function  int square( int );  Function takes an int and returns an int  Explained in more detail later  Calling/invoking a function  square(x);  Parentheses an operator used to call function  Pass argument x  Function gets its own copy of arguments  After finished, passes back result
  • 10. Syntax format for function definition returned-value-type function-name (parameter-list) { Declarations of local variables and Statements }  Parameter list  Comma separated list of arguments  Data type needed for each argument  If no arguments, use void or leave blank  Return-value-type  Data type of result returned (use void if nothing returned)
  • 11. Example function int square( int y ) { return y * y; }  return keyword  Returns data, and control goes to function’s caller  If no data to return, use return;  Function ends when reaches right brace  Control goes to caller  Functions cannot be defined inside other functions
  • 12. // Creating and using a programmer-defined function. #include <iostream.h> Function prototype: specifies int square( int ); // function prototype data types of arguments and return values. square int main() expects an int, and returns { an int. // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call Parentheses () cause function to be called. cout << endl; When done, it returns the result. return 0; // indicates successful termination } // end main // square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { return y * y; // returns square of y as an int Definition of square. y is a copy of the argument passed. } // end function square Returns y * y, or y squared. 1 4 9 16 25 36 49 64 81 100
  • 13. #include<iostream.h> int square(int); // prototype Output int cube(int); // prototype 1 square=1 main() 1 cube=1 { int i; 2 square=4 for (int i=1;i<=10;i++){ 2 cube=8 . . cout<< i<< “square=“ << square(i) << endl; . cout<< i<< “cube=“ <<cube(i) << endl; . } // end for 10 square=100 return 0; 10 cube=1000 } // end main function int square(int y) //function definition { return y*y; // returned Result } int cube(int y) //function definition { return y*y*y; // returned Result }
  • 14. // Finding the maximum of three floating-point (real) numbers. #include <iostream.h> double maximum( double, double, double ); // function prototype int main() { double number1, number2; double number3; Function maximum takes 3 arguments (all double) and cout << "Enter three real numbers: "; returns a double. cin >> number1 >> number2 >> number3; // number1, number2 and number3 are arguments to the maximum function call cout << "Maximum is: " << maximum( number1, number2, number3 ) << endl; return 0; // indicates successful termination } // end main // function maximum definition. x, y and z are parameters double maximum( double x, double y, double z ) { double max = x; // assume x is largest Enter three real numbers: 99.32 37.3 27.1928 if ( y > max ) // if y is larger, Maximum is: 99.32 max = y; // assign y to max Enter three real numbers: 1.1 3.333 2.22 if ( z > max ) // if z is larger, Maximum is: 3.333 max = z; // assign z to max return max; // max is largest value } // end function maximum
  • 15. Function prototype contains  Function name  Parameters (number and data type)  Return type (void if returns nothing)  Only needed if function definition after function call  Prototype must match function definition  Function prototype double maximum( double, double, double );  Definition double maximum( double x, double y, double z ) { … }
  • 16. If the Function does not RETURN result, it is called void Function #include<iostream.h> void add2Nums(int,int); main() { int a, b; cout<<“enter tow Number:”; cin >>a >> b; add2Nums(a, b) return 0; } void add2Nums(int x, int y) { cout<< x<< “+” << y << “=“ << x+y; }
  • 17. If the function Does Not Take Arguments specify this with EMPT Y-LIST OR write void inside #include<iostream.h> void funA(); void funB(void) main() { Will be the same funA(); in all cases funB(); return 0; } void funA() { cout << “Function-A takes no arqumentsn”; } void funB() { cout << “Also Function-B takes No argumentsn”; }
  • 18. Local variables  Known only in the function in which they are defined  All variables declared inside a function are local variables  Parameters  Local variables passed to function when called (passing- parameters)  Variables defined outside and before function main:  Called global variables  Can be accessible and used anywhere in the entire program
  • 19. Omitting the type of returned result defaults to int, but omitting a non-integer type is a Syntax Error  If a Global variable defined again as a local variable in a function, then the Local-definition overrides the Global defining  Function prototype, function definition, and function call must be consistent in: 1- Number of arguments 2- Type of those arguments 3-Order of those arguments
  • 20. #include<iostream.h> int x,y; //Global Variables int add2(int, int); //prototype main() { int s; x = 11; y = 22; cout << “global x=” << x << endl; cout << “Global y=” << y << endl; s = add2(x, y); cout << x << “+” << y << “=“ << s; cout<<endl; cout<<“n---end of output---n”; return 0; } global x=11 int add2(int x1,int y1) { int x; //local variables global y=22 x=44; Local x=44 cout << “nLocal x=” << x << endl; 11+22=33 return x1+y1; } ---end of output---
  • 21. int sum(int x, int y) { int result; result = x+y; } this function must return an integer value as indicated in the header definition (return result;) should be added ---------------------------------------------------------------------------------------- - int sum (int n) { if (n==0) return 0; else n+sum(n-1); } the result of n+sum(n-1) is not returned; sum returns an improper result, the else part should be written as:- else return n+sum(n-1);
  • 22. void f(float a); { float a; cout<<a<<endl; }  ; found after function definition header.  redefining the parameter a in the function void f(float a) { float a2 = a + 8.9; cout <<a2<<endl; }
  • 23. void product(void) { int a, b, c, result; cout << “enter three integers:”; cin >> a >> b >> c; result = a*b*c; cout << “Result is” << result; return result; }  According to the definition it should not return a value , but in the block (body) it did & this is WRONG.   Remove return Result;
  • 24. Call by value • A copy of the value is passed  Call by reference • The caller passes the address of the value  Call by value  Up to this point all the calls we have seen are call-by-value, a copy of the value (known) is passed from the caller-function to the called- function  Any change to the copy does not affect the original value in the caller function  Advantages, prevents side effect, resulting in reliable software
  • 25. Call By Reference  We introduce reference-parameter, to perform call by reference. The caller gives the called function the ability to directly access the caller’s value, and to modify it.  A reference parameter is an alias for it’s corresponding argument, it is stated in c++ by “flow the parameter’s type” in the function prototype by an ampersand(&) also in the function definition-header.  Advantage: performance issue void function_name (type &);// prototype main() { ----- ------ } void function_name(type &parameter_name)
  • 26. #include<iostream.h> int squareVal(int); //prototype call by value function void squareRef(int &); // prototype call by –reference function int main() { int x=2; z=4; cout<< “x=“ << x << “before calling squareVal”; cout << “n” << squareVal(x) << “n”; // call by value cout<< “x=“ << x << “After returning” cout<< “z=“ << z << “before calling squareRef”; squareRef(z); // call by reference cout<< “z=“ << z<< “After returning squareRef” return 0; } x=2 before calling squareVal int squareVal(int a) 4 { x=2 after returning return a*=a; // caller’s argument not modified z=4 before calling squareRef } z=16 after returning squareRef void squarRef(int &cRef) { cRef *= cRef; // caller’s argument modified }
  • 27. rand function generates an integer between 0 and RAND- MAX(~32767) a symbolic constant defined in <stdlib.h>  You may use modulus operator (%) to generate numbers within a specifically range with rand. //generate 10 random numbers open-range int x; for( int i=0; i<=10; i++){ x=rand(); cout<<x<<“ “; } ------------------------------------------------------- //generate 10 integers between 0……..49 int x; for( int i=0; i<10; i++){ x=rand()%50; cout<<x<<“ “; }
  • 28. //generate 10 integers between 5…15 int x; for ( int i=1; i<=10; i++){ x= rand()%11 + 5; cout<<x<<“ “; } ------------------------------------ //generate 100 number as simulation of rolling a dice int x; for (int i=1; i<=100; i++){ x= rand%6 + 1; cout<<x<<“ “; }
  • 29. the rand( ) function will generate the same set of random numbers each time you run the program .  To force NEW set of random numbers with each new run use the randomizing process  Randomizing is accomplished with the standard library function srand(unsigned integer); which needs a header file <stdlib.h> Explanation of signed and unsigned integers:  int is stored in at least two-bytes of memory and can have positive & negative values  unsigned int also stored in at least two-bytes of memory but it can have only positive values 0…..65535
  • 30. #include<iostream.h> #include<iomanip.h> #include<stdlib.h> int main() { int i; unsigned num; // we will enter a different number each time we run cin>>num; srand(num); for(i=1; i<=5; i++) cout<<setw(10)<< 1+rand()%6; return 0; } Output for Multiple Runs 19 6 1 1 4 2 1 18 6 1 5 1 4 4 Different-set of Random 3 1 2 5 6 2 4 numbers 0 1 5 5 3 5 5 3 1 2 5 6 3 4
  • 31. #include<iostream.h> #include<iomanip.h> #include<stdlib.h> int main() { int i; for(i=1; i<=5; i++) cout<<setw(10)<< 1+rand()%6; return 0; } Output for Multiple Runs 5 3 3 5 4 2 5 3 3 5 4 2 Same set of numbers for 5 3 3 5 4 2 5 3 3 5 4 2 each run 6 5 3 3 5 4
  • 32.  Main calls another function…..normal  A function calls another function2….normal  A function calls itself ?! Possible?? YES A recursive function is one that call itself.
  • 33. A recursive function is called to solve a problem  The function knows to solve only the simplest cases or so-called base-cases  Thus if the function called with a base-case, it simply returns a result. But if it is called with more complex problem, the function divides the problem into two conceptual pieces, one knows how to do, and another doesn't know what to do.  The second case/piece must resemble the original problem, but be a slightly simpler/smaller version of the original problem
  • 34. Thus the function launches (calls) a fresh copy of itself to work on the smaller problem –this is related as a Recursive- call/recursive step.  The function keeps dividing each new sub problem into two conceptual pieces until eventually terminates after converging on the base-case.  The function thus recognize the base-case and returns a result to the previous copy of the way up the line until original call of the function returns the final result to main.
  • 35. 5! Final value=120 5! 5!=5*24=120 returned 5*4! 5*4! 4!=4*6=24 returned 4*3! 4*3! 3!=3*2=6 returned 3*2! 3*2! 2!=2*1=2 returned 2*1! 2*1! 1 1 1
  • 36. //Recursive factorial Function #include<iostream.h> #include<iomonip.h> unsigned lion factorial(unsigned long);//prototype int main() { int num; cout<<“enter a positive integer:”; cin>>num; cout<<“factorial=“<<factorial(num); return 0; } unsigned long factorial(unsigned long n) { if ( n <= 1) //the base case return 1; else return n * factorial (n - 1); }
  • 37. Function overloading  Functions with same name and different parameters  Should perform similar tasks  I.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; }  A call-time c++ complier selects the proper function by examining the number, type and order of the parameters