SlideShare une entreprise Scribd logo
1  sur  28
C++ PROGRAMMING
       User-Defined Functions
•   Introduction
•   Function Definition
•   Void function
•   Global Vs Local variables
•   Random Number Generator
•   Recursion
•   Function Overloading
•   Sample Code
Functions in C++
•   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;                                                  {
    }                                                             ---
                                                                  ---
                                                               }
(.Functions in C++(Cont
• In FORTRAN Modules Known as Subprograms
• In C++ Modules Known as Functions & Classes
• Programs use new and “prepackaged” modules
  – New: programmer-defined functions and classes
  – Prepackaged: from the standard library
++About Functions in C
  •      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
Function Calling
• 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) ) ;
Function Calling
• 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
• 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 Definition
• 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
Function Definition
• 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)
Function Definition
• 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
Function Prototypes
• 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 )
        {
          …
        }
void Function takes arguments
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;
       }
void Function take no arguments
If the function Does Not Take Arguments specify this with EMPTY-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”;
     }
Remarks on Functions
• 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
Remarks on Functions
• 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
Local vs Global Variables
#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”;
                                        global x=11
   return 0;
}
                                        global y=22
int add2(int x1,int y1)                 Local x=44
{ int x; //local variables              11+22=33
   x=44;                                ---end of output---
   cout << “nLocal x=” << x << endl;
   return x1+y1;
}
Finding Errors in Function Code
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);
Finding Errors in Function Code
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;
}
Finding Errors in Function Code
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;
Function Call Methods
•   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
Function Call Methods
• 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)
Example Function Call
#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
}
                                                   4
int squareVal(int a)
                                                   x=2 after returning
{
                                                   z=4 before calling squareRef
   return a*=a; // caller’s argument not modified
                                                   z=16 after returning squareRef
}
void squarRef(int &cRef)
{
   cRef *= cRef; // caller’s argument modified
}
Call-by-value vs.
           Call-by-reference
   So far we looked at functions that get a •
         copy of what thecaller. passed in
This is call-by-value, as the value is what gets –
             .(passed in (the value of a variable
      We can also define functions that are •
          passed areference. to a variable
    This is call-by-reference, the function can –
           .change a callers variables directly
Recursion and Recursive Functions

• 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.
Concept Of recursion
• 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
Function Overloading
• 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

Contenu connexe

Tendances (19)

Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
C++ Chapter III
C++ Chapter IIIC++ Chapter III
C++ Chapter III
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Chtp405
Chtp405Chtp405
Chtp405
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
C++ Chapter IV
C++ Chapter IVC++ Chapter IV
C++ Chapter IV
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Link list
Link listLink list
Link list
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
Programming Homework Help
Programming Homework Help Programming Homework Help
Programming Homework Help
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Function notes
Function notesFunction notes
Function notes
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
 
Dive Into PyTorch
Dive Into PyTorchDive Into PyTorch
Dive Into PyTorch
 

En vedette

Toc indian retail industry
Toc indian retail industryToc indian retail industry
Toc indian retail industryRehman7376
 
Presentacion de Literatura, Lírica Griega Antigua
Presentacion de Literatura, Lírica Griega AntiguaPresentacion de Literatura, Lírica Griega Antigua
Presentacion de Literatura, Lírica Griega AntiguaEdwinPFLC440
 
Bathroom Before and After
Bathroom Before and AfterBathroom Before and After
Bathroom Before and AfterBree Marungo
 
Exterior Repairs- Pillars
Exterior Repairs- PillarsExterior Repairs- Pillars
Exterior Repairs- PillarsBree Marungo
 
Future Job Scope of Mechanical engineering
Future Job Scope of Mechanical engineeringFuture Job Scope of Mechanical engineering
Future Job Scope of Mechanical engineeringCGCLandran
 

En vedette (6)

Toc indian retail industry
Toc indian retail industryToc indian retail industry
Toc indian retail industry
 
Presentacion de Literatura, Lírica Griega Antigua
Presentacion de Literatura, Lírica Griega AntiguaPresentacion de Literatura, Lírica Griega Antigua
Presentacion de Literatura, Lírica Griega Antigua
 
Bathroom Before and After
Bathroom Before and AfterBathroom Before and After
Bathroom Before and After
 
Exterior Repairs- Pillars
Exterior Repairs- PillarsExterior Repairs- Pillars
Exterior Repairs- Pillars
 
fiu
fiufiu
fiu
 
Future Job Scope of Mechanical engineering
Future Job Scope of Mechanical engineeringFuture Job Scope of Mechanical engineering
Future Job Scope of Mechanical engineering
 

Similaire à Functions123

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++NUST Stuff
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptcpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptSuleman Khan
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Abdul Samee
 
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 196Mahmoud Samir Fayed
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
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 184Mahmoud Samir Fayed
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03sanya6900
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college2017eee0459
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Platonov Sergey
 
The Ring programming language version 1.5.4 book - Part 21 of 185
The Ring programming language version 1.5.4 book - Part 21 of 185The Ring programming language version 1.5.4 book - Part 21 of 185
The Ring programming language version 1.5.4 book - Part 21 of 185Mahmoud Samir Fayed
 

Similaire à Functions123 (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++
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.pptcpphtp4_PPT_03.ppt
cpphtp4_PPT_03.ppt
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
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
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Chap 9(functions)
 
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
 
Functions.docx
Functions.docxFunctions.docx
Functions.docx
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Function
FunctionFunction
Function
 
The Ring programming language version 1.5.4 book - Part 21 of 185
The Ring programming language version 1.5.4 book - Part 21 of 185The Ring programming language version 1.5.4 book - Part 21 of 185
The Ring programming language version 1.5.4 book - Part 21 of 185
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Dernier (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Functions123

  • 1. C++ PROGRAMMING User-Defined Functions • Introduction • Function Definition • Void function • Global Vs Local variables • Random Number Generator • Recursion • Function Overloading • Sample Code
  • 2. Functions in C++ • 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. (.Functions in C++(Cont • In FORTRAN Modules Known as Subprograms • 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. ++About Functions in C • 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. Function Calling • 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. Function Calling • 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 • 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 Definition • 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. Function Definition • 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. Function Definition • 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. Function Prototypes • 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 ) { … }
  • 14. void Function takes arguments 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; }
  • 15. void Function take no arguments If the function Does Not Take Arguments specify this with EMPTY-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”; }
  • 16. Remarks on Functions • 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
  • 17. Remarks on Functions • 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
  • 18. Local vs Global Variables #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”; global x=11 return 0; } global y=22 int add2(int x1,int y1) Local x=44 { int x; //local variables 11+22=33 x=44; ---end of output--- cout << “nLocal x=” << x << endl; return x1+y1; }
  • 19. Finding Errors in Function Code 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);
  • 20. Finding Errors in Function Code 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; }
  • 21. Finding Errors in Function Code 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;
  • 22. Function Call Methods • 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
  • 23. Function Call Methods • 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)
  • 24. Example Function Call #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 } 4 int squareVal(int a) x=2 after returning { z=4 before calling squareRef return a*=a; // caller’s argument not modified z=16 after returning squareRef } void squarRef(int &cRef) { cRef *= cRef; // caller’s argument modified }
  • 25. Call-by-value vs. Call-by-reference So far we looked at functions that get a • copy of what thecaller. passed in This is call-by-value, as the value is what gets – .(passed in (the value of a variable We can also define functions that are • passed areference. to a variable This is call-by-reference, the function can – .change a callers variables directly
  • 26. Recursion and Recursive Functions • 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.
  • 27. Concept Of recursion • 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
  • 28. Function Overloading • 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