SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
IPCRF/RPMS 2024 Classroom Observation tool is your access to the new performa...
IPCRF/RPMS 2024 Classroom Observation tool is your access to the new performa...IPCRF/RPMS 2024 Classroom Observation tool is your access to the new performa...
IPCRF/RPMS 2024 Classroom Observation tool is your access to the new performa...MerlizValdezGeronimo
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
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
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
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
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
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
 
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
 

Kürzlich hochgeladen (20)

Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
IPCRF/RPMS 2024 Classroom Observation tool is your access to the new performa...
IPCRF/RPMS 2024 Classroom Observation tool is your access to the new performa...IPCRF/RPMS 2024 Classroom Observation tool is your access to the new performa...
IPCRF/RPMS 2024 Classroom Observation tool is your access to the new performa...
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
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
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
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
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
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
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
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
 
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
 
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
 

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