SlideShare a Scribd company logo
C Functions
Objectives
• Create functions
• Function prototypes
• Parameters
– Pass by value or reference
– Sending a reference
• Return values
• Math functions
Intro
• Why:
– Divide and conquer
– Reuse abstractions
– Don’t rebuild the bridge
• What:
– Used prepackaged functions
• printf, scanf, rand()
– Create our own
• main
– Pass parameters
– Accept return values
Math
• #include <math.h>
• Use any math function
• If c1 = 13.0, d = 3.0 and f = 4.0, then the
statement
printf( "%.2f", sqrt( c1 + d * f ) );
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
Create your function
• Choose a name
– Function should perform a single well defined task
– If you can’t find a concise descriptive name, you may have too many
jobs for the function
• Define a contract
– Inputs
• Arguments – choose type
• None should be noted as void
• Will the function change the parameter’s value?
– Output
• Only one ; by convention, 0 means good
• Write prototype
– Looks like function header but has ;
– int square( int y );
– Tells compiler what is valid input and output
– Forces type conversion
• Write body
Sample Function
#include <stdio.h>
int square ( int y ); // function prototype
// function main begins program execution
int main ( void )
{ int x; // counter
for ( x = 1; x <= 10; x++ ) {// loop 10 times and calc square of x each time
printf ( "%d ", square ( x ) ); // function call
}
puts (""); // add a blank line
}
// square function returns the square of its parm
int square ( int y ) // y is a copy of the x sent
{
return y * y; // returns square of y as an int
}
D From Deitel C How to Program
return
• return serves two purposes:
– It tells the computer the value to return as the
result
– It tells the computer to leave the function
immediately and return the calling function (or
the main program).
• Void return:
– Ex: void printit ( int x );
– You can still return to leave, but without a value
Prototypes
• Looks like function header but has ;
• int square( int y );
• Forces type conversion
• Tells compiler what is valid input and output
• Placement
– Applies to all functions appearing within the top level braces
(or all if outside all braces)
– Can put into its own .h file and then include without <>
• #include “myfunctions.h” (no semicolon)
• No Overloading
• Every function name can have only one contract
Where do the variables live?
• On Stack: (lives and dies with function)
– Local – created in the function – automatic – on
stack
– Argument – same as local
• On Heap: (lives with program life)
– Use keyword static
• static int x = 1;
• When you return to the function it will retain old value
– Global
• declare outside a function block
Function Call Stack
• Pile like one of dishes
– Access from the top
– Call a function – push it on the stack
– Execute function
• Push on other functions from within function
• Variables created in the stack
– Finish executing a function – pop it off the stack
– supports the creation, maintenance and destruction
of each called function’s automatic variables (local
variables, parameters)
Introduction of function in c programming.pptx
Introduction of function in c programming.pptx
What Are Reference Parameters?
• Reference parameters do not copy the value of
the parameter.
• Instead, they give the function being called a
copy of the address at which the data is stored.
This way, the function works with the original
data.
• We call this passing by reference because we
are making references to the parameters.
Write SquareInPlace
with Reference Parm
• tell the main program about the change in y by
placing (*) between the data type and variable
name:
int squareInPlace (int *y)
{ *y = *y * *y;
return 0;}
• Send an address instead of the variable contents
using (&) before variable name:
int number = 6;
squareInPlace (&number);
printf(“%d”, number);
Passing Reference Parameters
4.0
number y
Any data
intended for y
in the
function goes
to the
location of
number in the
main
program
When to Use Value and Reference Parameters
• We use value parameters when:
– We are not going to change the parameters’ value
– We may change it but the main program should not
know about it
• When we are simply printing the value
– We use reference parameters when:
– We are going to change the parameter’s value and
the main program MUST know about it.
– We are reading in a new value
Recursion – Function calls itself
• Method for repetition
• Need a stopping condition
• Need to call with some way to reach the stop
eventually
• Pushes copies of itself onto the stack (memory
use)
Introduction of function in c programming.pptx
Introduction of function in c programming.pptx
Introduction of function in c programming.pptx
Java Comparison
Feature C Java
Including
Math
functions
#include "math.h" part of base
Calling Math
function x = sqrt(2.2); x = Math.sqrt(2.2);
functions int max(int a, int b) public static int max(int a, int
b)
pass-by-
value
primitive data types, structs,
and pointers are passed by
value; array decays to pointer
all primitive data types and
references (which includes
arrays), are passed by value
overloading no yes for methods, no for
operators
Summary
• Create a function
– <return type> <function name> (<type> <var> …)
• Call a function (can call it recursively)
– <function name> (<var>…)
• Pass by reference
– Argument accepts address: *<var name>
– Caller sends address: &<var name>
• Variable life
– Local vs global
Thank You
• By Komal Gadekar
Ad

More Related Content

Similar to Introduction of function in c programming.pptx (20)

Lecture6
Lecture6Lecture6
Lecture6
Dr. Kavita Sharma
 
4th unit full
4th unit full4th unit full
4th unit full
Murali Saktheeswaran
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
Nico Ludwig
 
Functions
FunctionsFunctions
Functions
Online
 
Function (rule in programming)
Function (rule in programming)Function (rule in programming)
Function (rule in programming)
Unviersity of balochistan quetta
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
temkin abdlkader
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
Venkateswarlu Vuggam
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
Function
FunctionFunction
Function
Saniati
 
Function
Function Function
Function
Kathmandu University
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
C language
C languageC language
C language
Robo India
 
user-definedfunctions-converted.pptx
user-definedfunctions-converted.pptxuser-definedfunctions-converted.pptx
user-definedfunctions-converted.pptx
ZaibunnisaMalik1
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
Venkateswarlu Vuggam
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
Appili Vamsi Krishna
 
User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.
NabeelaNousheen
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
LadallaRajKumar
 
c-programming
c-programmingc-programming
c-programming
Zulhazmi Harith
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
WaheedAnwar20
 

Recently uploaded (20)

Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Ad

Introduction of function in c programming.pptx

  • 2. Objectives • Create functions • Function prototypes • Parameters – Pass by value or reference – Sending a reference • Return values • Math functions
  • 3. Intro • Why: – Divide and conquer – Reuse abstractions – Don’t rebuild the bridge • What: – Used prepackaged functions • printf, scanf, rand() – Create our own • main – Pass parameters – Accept return values
  • 4. Math • #include <math.h> • Use any math function • If c1 = 13.0, d = 3.0 and f = 4.0, then the statement printf( "%.2f", sqrt( c1 + d * f ) );
  • 5. ©1992-2013 by Pearson Education, Inc. All Rights Reserved.
  • 6. ©1992-2013 by Pearson Education, Inc. All Rights Reserved.
  • 7. Create your function • Choose a name – Function should perform a single well defined task – If you can’t find a concise descriptive name, you may have too many jobs for the function • Define a contract – Inputs • Arguments – choose type • None should be noted as void • Will the function change the parameter’s value? – Output • Only one ; by convention, 0 means good • Write prototype – Looks like function header but has ; – int square( int y ); – Tells compiler what is valid input and output – Forces type conversion • Write body
  • 8. Sample Function #include <stdio.h> int square ( int y ); // function prototype // function main begins program execution int main ( void ) { int x; // counter for ( x = 1; x <= 10; x++ ) {// loop 10 times and calc square of x each time printf ( "%d ", square ( x ) ); // function call } puts (""); // add a blank line } // square function returns the square of its parm int square ( int y ) // y is a copy of the x sent { return y * y; // returns square of y as an int } D From Deitel C How to Program
  • 9. return • return serves two purposes: – It tells the computer the value to return as the result – It tells the computer to leave the function immediately and return the calling function (or the main program). • Void return: – Ex: void printit ( int x ); – You can still return to leave, but without a value
  • 10. Prototypes • Looks like function header but has ; • int square( int y ); • Forces type conversion • Tells compiler what is valid input and output • Placement – Applies to all functions appearing within the top level braces (or all if outside all braces) – Can put into its own .h file and then include without <> • #include “myfunctions.h” (no semicolon) • No Overloading • Every function name can have only one contract
  • 11. Where do the variables live? • On Stack: (lives and dies with function) – Local – created in the function – automatic – on stack – Argument – same as local • On Heap: (lives with program life) – Use keyword static • static int x = 1; • When you return to the function it will retain old value – Global • declare outside a function block
  • 12. Function Call Stack • Pile like one of dishes – Access from the top – Call a function – push it on the stack – Execute function • Push on other functions from within function • Variables created in the stack – Finish executing a function – pop it off the stack – supports the creation, maintenance and destruction of each called function’s automatic variables (local variables, parameters)
  • 15. What Are Reference Parameters? • Reference parameters do not copy the value of the parameter. • Instead, they give the function being called a copy of the address at which the data is stored. This way, the function works with the original data. • We call this passing by reference because we are making references to the parameters.
  • 16. Write SquareInPlace with Reference Parm • tell the main program about the change in y by placing (*) between the data type and variable name: int squareInPlace (int *y) { *y = *y * *y; return 0;} • Send an address instead of the variable contents using (&) before variable name: int number = 6; squareInPlace (&number); printf(“%d”, number);
  • 17. Passing Reference Parameters 4.0 number y Any data intended for y in the function goes to the location of number in the main program
  • 18. When to Use Value and Reference Parameters • We use value parameters when: – We are not going to change the parameters’ value – We may change it but the main program should not know about it • When we are simply printing the value – We use reference parameters when: – We are going to change the parameter’s value and the main program MUST know about it. – We are reading in a new value
  • 19. Recursion – Function calls itself • Method for repetition • Need a stopping condition • Need to call with some way to reach the stop eventually • Pushes copies of itself onto the stack (memory use)
  • 23. Java Comparison Feature C Java Including Math functions #include "math.h" part of base Calling Math function x = sqrt(2.2); x = Math.sqrt(2.2); functions int max(int a, int b) public static int max(int a, int b) pass-by- value primitive data types, structs, and pointers are passed by value; array decays to pointer all primitive data types and references (which includes arrays), are passed by value overloading no yes for methods, no for operators
  • 24. Summary • Create a function – <return type> <function name> (<type> <var> …) • Call a function (can call it recursively) – <function name> (<var>…) • Pass by reference – Argument accepts address: *<var name> – Caller sends address: &<var name> • Variable life – Local vs global
  • 25. Thank You • By Komal Gadekar