SlideShare a Scribd company logo
Name – Tarandeep Kaur
Section – N2
Roll No. – 115331
   Definition of functions
   Function calling
   Function definition
   Void function
   Remarks on function
   Local v/s Global variables
   Function call methods
   Concept of recursion
   Function overloading
   A function is a subprogram that acts on data
    and often returns a value.
     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)
   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
   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
        {
           // loop 10 times and calculate and output
                                                             an int.
           // square of x each time
           for ( int x = 1; x <= 10; x++ )
              cout << square( x ) << " "; // function call

              cout << endl;
                                                             Parentheses () cause function to be called.
                                                             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
// 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 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”;
    }
   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
#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)                global y=22
{ int x; //local variables             Local x=44
  x=44;
                                       11+22=33
  cout << “nLocal x=” << x << endl;
  return x1+y1;                        ---end of output---
}
   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
}
 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
   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
   THANKS
Ad

More Related Content

What's hot (20)

Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
minal kumar soni
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
sai tarlekar
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Rokonuzzaman Rony
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
Tanmay Modi
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
P M Patil
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
Chaand Sheikh
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++
Jaspal Singh
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
Dhrumil Panchal
 
Function in c
Function in cFunction in c
Function in c
Raj Tandukar
 
user defined function
user defined functionuser defined function
user defined function
King Kavin Patel
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Rajat Busheheri
 
Virtual Functions | Polymorphism | OOP
Virtual Functions | Polymorphism | OOPVirtual Functions | Polymorphism | OOP
Virtual Functions | Polymorphism | OOP
shubham ghimire
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP
Muhammad Hammad Waseem
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
Tanmay Modi
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
P M Patil
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++
Jaspal Singh
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
Dhrumil Panchal
 
Virtual Functions | Polymorphism | OOP
Virtual Functions | Polymorphism | OOPVirtual Functions | Polymorphism | OOP
Virtual Functions | Polymorphism | OOP
shubham ghimire
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 

Similar to functions of C++ (20)

Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
temkin abdlkader
 
Functions12
Functions12Functions12
Functions12
sandhubuta
 
Functions123
Functions123 Functions123
Functions123
sandhubuta
 
User defined functions
User defined functionsUser defined functions
User defined functions
shubham_jangid
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
ankita44
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
NagasaiT
 
3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger
3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger
3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger
edukuldeep2005
 
Pro
ProPro
Pro
TeshaleSiyum
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
HNDE Labuduwa Galle
 
Programming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptxProgramming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptx
singyali199
 
Function
FunctionFunction
Function
venkatme83
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
ShashiShash2
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
TAlha MAlik
 
functions
functionsfunctions
functions
Makwana Bhavesh
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
WaheedAnwar20
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
rohassanie
 
Introduction to functions in C programming language
Introduction to functions in C programming languageIntroduction to functions in C programming language
Introduction to functions in C programming language
ssuserbad56d
 
Function C++
Function C++ Function C++
Function C++
Shahzad Afridi
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
jleed1
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 
User defined functions
User defined functionsUser defined functions
User defined functions
shubham_jangid
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
ankita44
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
NagasaiT
 
3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger
3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger
3.pptirgggggggggggggggggggggggggggrrrrrrrrrrger
edukuldeep2005
 
Programming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptxProgramming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptx
singyali199
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
ShashiShash2
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
TAlha MAlik
 
Introduction to functions in C programming language
Introduction to functions in C programming languageIntroduction to functions in C programming language
Introduction to functions in C programming language
ssuserbad56d
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
jleed1
 
Ad

Recently uploaded (20)

Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Ad

functions of C++

  • 1. Name – Tarandeep Kaur Section – N2 Roll No. – 115331
  • 2. Definition of functions  Function calling  Function definition  Void function  Remarks on function  Local v/s Global variables  Function call methods  Concept of recursion  Function overloading
  • 3. A function is a subprogram that acts on data and often returns a value.
  • 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. 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
  • 8. 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
  • 9. 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
  • 10. // 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 { // loop 10 times and calculate and output an int. // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call cout << endl; Parentheses () cause function to be called. 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
  • 11. // 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
  • 12. 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 ) { … }
  • 13. 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; }
  • 14. 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”; }
  • 15. 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
  • 16. #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) global y=22 { int x; //local variables Local x=44 x=44; 11+22=33 cout << “nLocal x=” << x << endl; return x1+y1; ---end of output--- }
  • 17. 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
  • 18. 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)
  • 19. #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 }
  • 20.  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.
  • 21. 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
  • 22. 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
  • 23. THANKS
  翻译: