SlideShare une entreprise Scribd logo
1  sur  21
By:-
Fatima saqlain
Gaurav raj khaiwal
Gaurav subham
Gautam ahuja
Karan singh bisht
Madhur chopra
•   5.1 Introduction
•   5.2 Math Library Functions
•   5.3 Functions
•   5.4 Function Definitions
•   5.5 Function Prototypes
•   5.6 Header Files
•   5.7 Calling Functions: Call by Value and Call by Reference
•   5.8 Storage Classes
•   5.9 Scope Rules
•   5.10 Recursion
•   5.11 Example Using Recursion: The Fibonacci Series
•   Divide and conquer
    • Construct a program from smaller pieces or
     components
     • These smaller pieces are called modules
    • Each piece more manageable than the original
     program
•   Math library functions
    • perform common mathematical calculations
    • #include <math.h>
•   Format for calling functions
    • FunctionName( argument );
      • If multiple arguments, use comma-separated list
    • Cout<<2f<<sqrt( 900.0 );
      • Calls function sqrt, which returns the square root of its
        argument
      • All math functions return data type double
    • Arguments may be constants, variables, or
      expressions
•   Functions
    • Modularize a program
    • All variables declared inside functions are local variables
      • Known only in function defined
    • Parameters
      • Communicate information between functions
      • Local variables
•   Benefits of functions
    • Divide and conquer
      • Manageable program development
    • Software reusability
      • Use existing functions as building blocks for new programs
      • Abstraction - hide internal details (library functions)
    • Avoid code repetition
•   Function definition format
      • return-value-type function-name( parameter-list )
        {
          declarations and statements
        }
    • Function-name: any valid identifier
    • Return-value-type: data type of the result (default int)
      • void – indicates that the function returns nothing
    • Parameter-list: comma separated list, declares
      parameters
      • A type must be listed explicitly for each parameter unless,
        the parameter is of type int
•   Function definition format (continued)
      • return-value-type function-name( parameter-list )
        {
          declarations and statements
        }
    • Declarations and statements: function body (block)
      • Variables can be declared inside blocks (can be nested)
      • Functions can not be defined inside other functions
    • Returning control
      • If nothing returned
       • return;
       • or, until reaches right brace
      • If something returned
       • return expression;
•   Function prototype
    • Function name
    • Parameters – what the function takes in
    • Return type – data type function returns (default int)
    • Used to validate functions
    • Prototype only needed if function definition comes after use
      in program
    • The function with the prototype
        • int maximum( int, int, int );
        • Takes in 3 ints
        • Returns an int
•   Promotion rules and conversions
    • Converting to lower types can lead to errors
•   Header files
    • Contain function prototypes for library functions
    • <stdlib.h> , <math.h> , etc
    • Load with #include <filename>
      • #include <math.h>
•   Custom header files
    • Create file with functions
    • Save as filename.h
    • Load in other files with #include "filename.h"
    • Reuse functions
•   Used when invoking functions
•   Call by value
    • Copy of argument passed to function
    • Changes in function do not effect original
    • Use when function does not need to modify argument
      • Avoids accidental changes
•   Call by reference
    • Passes original argument
    • Changes in function effect original
    • Only used with trusted functions
•   For now, we focus on call by value
•   In C ++ programming language, variables can be
    referred differently depending on the context. For
    example, if you are writing a program for a low
    memory system, you may want to avoid copying
    larger sized types such as structs and arrays when
    passing them to functions. On the other hand, with
    data types like integers, there is no point in
    passing by reference when a pointer to an integer
    is the same size in memory as an integer itself.
•   Now, let us learn how variables can be passed in a
    C program.
•   When you use pass-by-value, the compiler copies the value of
    an argument in a calling function to a corresponding non-
    pointer or non-reference parameter in the called function
    definition. The parameter in the called function is initialized
    with the value of the passed argument. As long as the
    parameter has not been declared as constant, the value of the
    parameter can be changed, but the changes are only
    performed within the scope of the called function only; they
    have no effect on the value of the argument in the calling
    function.
•   In the following example, main passes func two values: 5 and
    7. The function func receives copies of these values and
    accesses them by the identifiers a and b. The function func
    changes the value of a. When control passes back to main,
    the actual values of x and y are not changed.
•   Storage class specifiers
    • Storage duration – how long an object exists in memory
    • Scope – where object can be referenced in program
    • Linkage – specifies the files in which an identifier is known
      (more in Chapter 14)
•   Automatic storage
    • Object created and destroyed within its block
    • auto: default for local variables
       • auto double x, y;
    • register: tries to put variable into high-speed registers
      • Can only be used for automatic variables
       • register int counter = 1;
•   Static storage
    • Variables exist for entire program execution
    • Default value of zero
    • static: local variables defined in functions.
      • Keep value after function ends
      • Only known in their own function
    • extern: default for global variables and functions
      • Known in any function
•   File scope
    • Identifier defined outside function, known in all
      functions
    • Used for global variables, function definitions,
      function prototypes
•   Function scope
    • Can only be referenced inside a function body
    • Used only for labels (start:, case: , etc.)
•   Block scope
    • Identifier declared inside a block
      • Block scope begins at declaration, ends at right brace
    • Used for variables, function parameters (local
      variables of function)
    • Outer blocks "hidden" from inner blocks if there is
      a variable with the same name in the inner block
•   Function prototype scope
    • Used for identifiers in parameter list
•   Recursive functions
    • Functions that call themselves
    • Can only solve a base case
    • Divide a problem up into
      • What it can do
      • What it cannot do
       • What it cannot do resembles original problem
       • The function launches a new copy of itself (recursion step) to
         solve what it cannot do
    • Eventually base case gets solved
      • Gets plugged in, works its way up and solves whole
        problem
•   Example: factorials
    • 5! = 5 * 4 * 3 * 2 * 1
    • Notice that
      • 5! = 5 * 4!
      • 4! = 4 * 3! ...
    • Can compute factorials recursively
    • Solve base case (1! = 0! = 1) then plug in
      • 2! = 2 * 1! = 2 * 1 = 2;
      • 3! = 3 * 2! = 3 * 2 = 6;
•   Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
    • Each number is the sum of the previous two
    • Can be solved recursively:
      • fib( n ) = fib( n - 1 ) + fib( n – 2 )
    • Code for the fibaonacci function
      • long fibonacci( long n )
      •{
      • if (n == 0 || n == 1) // base case
      •     return n;
      • else
      •     return fibonacci( n - 1) +
             fibonacci( n – 2 );
      •}
•   Set of recursive calls to function
                       f( 3 )
    fibonacci
                  return       f( 2 )     +   f( 1 )



    return     f( 1 )      +    f( 0 )            return 1



             return 1          return 0
Functions

Contenu connexe

Tendances

Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionJeongbae Oh
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functionsSwapnil Yadav
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8Garth Gilmour
 
Python functions
Python functionsPython functions
Python functionsAliyamanasa
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of VariableMOHIT DADU
 

Tendances (20)

Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Function & Recursion
Function & RecursionFunction & Recursion
Function & Recursion
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Intro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: FunctionIntro to JavaScript - Week 2: Function
Intro to JavaScript - Week 2: Function
 
user defined function
user defined functionuser defined function
user defined function
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Functions in C
Functions in CFunctions in C
Functions in C
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
 
Python functions
Python functionsPython functions
Python functions
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 

En vedette

3263270 human-resource-management-systems-hrms
3263270 human-resource-management-systems-hrms3263270 human-resource-management-systems-hrms
3263270 human-resource-management-systems-hrmschetanmbhimewal
 
Employee Management System
Employee Management SystemEmployee Management System
Employee Management SystemAnjali Agrawal
 
Student database management system
Student database management systemStudent database management system
Student database management systemSnehal Raut
 
Student management system
Student management systemStudent management system
Student management systemGaurav Subham
 
Human Resource Management System (HRMS)
Human Resource Management System (HRMS)Human Resource Management System (HRMS)
Human Resource Management System (HRMS)Samaresh Debbarma
 
Project report-on-student-information-management-system-php-mysql
Project report-on-student-information-management-system-php-mysqlProject report-on-student-information-management-system-php-mysql
Project report-on-student-information-management-system-php-mysqlRaj Sharma
 
Library mangement system project srs documentation.doc
Library mangement system project srs documentation.docLibrary mangement system project srs documentation.doc
Library mangement system project srs documentation.docjimmykhan
 

En vedette (7)

3263270 human-resource-management-systems-hrms
3263270 human-resource-management-systems-hrms3263270 human-resource-management-systems-hrms
3263270 human-resource-management-systems-hrms
 
Employee Management System
Employee Management SystemEmployee Management System
Employee Management System
 
Student database management system
Student database management systemStudent database management system
Student database management system
 
Student management system
Student management systemStudent management system
Student management system
 
Human Resource Management System (HRMS)
Human Resource Management System (HRMS)Human Resource Management System (HRMS)
Human Resource Management System (HRMS)
 
Project report-on-student-information-management-system-php-mysql
Project report-on-student-information-management-system-php-mysqlProject report-on-student-information-management-system-php-mysql
Project report-on-student-information-management-system-php-mysql
 
Library mangement system project srs documentation.doc
Library mangement system project srs documentation.docLibrary mangement system project srs documentation.doc
Library mangement system project srs documentation.doc
 

Similaire à Functions

Functions
FunctionsFunctions
FunctionsOnline
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdfManiMala75
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxsarthakgithub
 
chapter-2-functionseng-1 (1).pdf
chapter-2-functionseng-1 (1).pdfchapter-2-functionseng-1 (1).pdf
chapter-2-functionseng-1 (1).pdfYashikaTanwar2
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionBlue Elephant Consulting
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxGebruGetachew2
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptxYagna15
 

Similaire à Functions (20)

Functions
FunctionsFunctions
Functions
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
Functions
FunctionsFunctions
Functions
 
Functions
FunctionsFunctions
Functions
 
c-functions.ppt
c-functions.pptc-functions.ppt
c-functions.ppt
 
c-functions.ppt
c-functions.pptc-functions.ppt
c-functions.ppt
 
c-functions.ppt
c-functions.pptc-functions.ppt
c-functions.ppt
 
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
 
C language
C languageC language
C language
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Functions
FunctionsFunctions
Functions
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptx
 
chapter-2-functionseng-1 (1).pdf
chapter-2-functionseng-1 (1).pdfchapter-2-functionseng-1 (1).pdf
chapter-2-functionseng-1 (1).pdf
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, Recursion
 
Funtional Programming
Funtional ProgrammingFuntional Programming
Funtional Programming
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
 

Dernier

BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 

Dernier (20)

BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 

Functions

  • 1. By:- Fatima saqlain Gaurav raj khaiwal Gaurav subham Gautam ahuja Karan singh bisht Madhur chopra
  • 2. 5.1 Introduction • 5.2 Math Library Functions • 5.3 Functions • 5.4 Function Definitions • 5.5 Function Prototypes • 5.6 Header Files • 5.7 Calling Functions: Call by Value and Call by Reference • 5.8 Storage Classes • 5.9 Scope Rules • 5.10 Recursion • 5.11 Example Using Recursion: The Fibonacci Series
  • 3. Divide and conquer • Construct a program from smaller pieces or components • These smaller pieces are called modules • Each piece more manageable than the original program
  • 4. Math library functions • perform common mathematical calculations • #include <math.h> • Format for calling functions • FunctionName( argument ); • If multiple arguments, use comma-separated list • Cout<<2f<<sqrt( 900.0 ); • Calls function sqrt, which returns the square root of its argument • All math functions return data type double • Arguments may be constants, variables, or expressions
  • 5. Functions • Modularize a program • All variables declared inside functions are local variables • Known only in function defined • Parameters • Communicate information between functions • Local variables • Benefits of functions • Divide and conquer • Manageable program development • Software reusability • Use existing functions as building blocks for new programs • Abstraction - hide internal details (library functions) • Avoid code repetition
  • 6. Function definition format • return-value-type function-name( parameter-list ) { declarations and statements } • Function-name: any valid identifier • Return-value-type: data type of the result (default int) • void – indicates that the function returns nothing • Parameter-list: comma separated list, declares parameters • A type must be listed explicitly for each parameter unless, the parameter is of type int
  • 7. Function definition format (continued) • return-value-type function-name( parameter-list ) { declarations and statements } • Declarations and statements: function body (block) • Variables can be declared inside blocks (can be nested) • Functions can not be defined inside other functions • Returning control • If nothing returned • return; • or, until reaches right brace • If something returned • return expression;
  • 8. Function prototype • Function name • Parameters – what the function takes in • Return type – data type function returns (default int) • Used to validate functions • Prototype only needed if function definition comes after use in program • The function with the prototype • int maximum( int, int, int ); • Takes in 3 ints • Returns an int • Promotion rules and conversions • Converting to lower types can lead to errors
  • 9. Header files • Contain function prototypes for library functions • <stdlib.h> , <math.h> , etc • Load with #include <filename> • #include <math.h> • Custom header files • Create file with functions • Save as filename.h • Load in other files with #include "filename.h" • Reuse functions
  • 10. Used when invoking functions • Call by value • Copy of argument passed to function • Changes in function do not effect original • Use when function does not need to modify argument • Avoids accidental changes • Call by reference • Passes original argument • Changes in function effect original • Only used with trusted functions • For now, we focus on call by value
  • 11. In C ++ programming language, variables can be referred differently depending on the context. For example, if you are writing a program for a low memory system, you may want to avoid copying larger sized types such as structs and arrays when passing them to functions. On the other hand, with data types like integers, there is no point in passing by reference when a pointer to an integer is the same size in memory as an integer itself. • Now, let us learn how variables can be passed in a C program.
  • 12. When you use pass-by-value, the compiler copies the value of an argument in a calling function to a corresponding non- pointer or non-reference parameter in the called function definition. The parameter in the called function is initialized with the value of the passed argument. As long as the parameter has not been declared as constant, the value of the parameter can be changed, but the changes are only performed within the scope of the called function only; they have no effect on the value of the argument in the calling function. • In the following example, main passes func two values: 5 and 7. The function func receives copies of these values and accesses them by the identifiers a and b. The function func changes the value of a. When control passes back to main, the actual values of x and y are not changed.
  • 13. Storage class specifiers • Storage duration – how long an object exists in memory • Scope – where object can be referenced in program • Linkage – specifies the files in which an identifier is known (more in Chapter 14) • Automatic storage • Object created and destroyed within its block • auto: default for local variables • auto double x, y; • register: tries to put variable into high-speed registers • Can only be used for automatic variables • register int counter = 1;
  • 14. Static storage • Variables exist for entire program execution • Default value of zero • static: local variables defined in functions. • Keep value after function ends • Only known in their own function • extern: default for global variables and functions • Known in any function
  • 15. File scope • Identifier defined outside function, known in all functions • Used for global variables, function definitions, function prototypes • Function scope • Can only be referenced inside a function body • Used only for labels (start:, case: , etc.)
  • 16. Block scope • Identifier declared inside a block • Block scope begins at declaration, ends at right brace • Used for variables, function parameters (local variables of function) • Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner block • Function prototype scope • Used for identifiers in parameter list
  • 17. Recursive functions • Functions that call themselves • Can only solve a base case • Divide a problem up into • What it can do • What it cannot do • What it cannot do resembles original problem • The function launches a new copy of itself (recursion step) to solve what it cannot do • Eventually base case gets solved • Gets plugged in, works its way up and solves whole problem
  • 18. Example: factorials • 5! = 5 * 4 * 3 * 2 * 1 • Notice that • 5! = 5 * 4! • 4! = 4 * 3! ... • Can compute factorials recursively • Solve base case (1! = 0! = 1) then plug in • 2! = 2 * 1! = 2 * 1 = 2; • 3! = 3 * 2! = 3 * 2 = 6;
  • 19. Fibonacci series: 0, 1, 1, 2, 3, 5, 8... • Each number is the sum of the previous two • Can be solved recursively: • fib( n ) = fib( n - 1 ) + fib( n – 2 ) • Code for the fibaonacci function • long fibonacci( long n ) •{ • if (n == 0 || n == 1) // base case • return n; • else • return fibonacci( n - 1) + fibonacci( n – 2 ); •}
  • 20. Set of recursive calls to function f( 3 ) fibonacci return f( 2 ) + f( 1 ) return f( 1 ) + f( 0 ) return 1 return 1 return 0