SlideShare ist ein Scribd-Unternehmen logo
1 von 31
C Programming
User Defined
Functions
1
Introduction to Functions
b A complex problem is often
easier to solve by dividing it
into several smaller parts,
each of which can be solved by
itself.
b This is called structured
programming.
2
Introduction to Functions
b These parts are sometimes made
into functions in C.
b main() then uses these
functions to solve the original
problem.
3
Structured Programming
b Keep the flow of control in a
program as simple as possible.
b Use top-down design.
• Keep decomposing (also known as
factoring) a problem into smaller
problems until you have a
collection of small problems that
you can easily solve.
4
Top-Down Design Using Functions
b C programs normally consist
of a collection of user-
defined functions.
• Each function solves one of the
small problems obtained using
top-down design.
• Functions call or invoke other
functions as needed.
5
6
Functions
b A function is a block of code that
performs a specific task.
b A function is a black box that gets
some input and produces some
output
b Functions provide reusable code
b Functions simplify debugging
Functions
b Functions
• Modularize a program
• All variables declared inside
functions are local variables
–Known only in function defined
• Parameters
–Communicate information between
functions
–Local variables
7
Advantages of Functions
b Functions separate the concept
(what is done) from the
implementation (how it is
done).
b Functions make programs easier
to understand.
b Functions can be called several
times in the same program,
allowing the code to be reused.
8
Advantages of Functions
b 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
9
Function Definitions
b Function definition format
return-value-type function-
name( parameter-list )
{
declarations and statements
}
10
Function Definitions
• 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
11
Function Definitions,
Prototypes, and Calls
#include <stdio.h>
void prn_message(void); /* fct prototype */
/* tells the compiler that this */
/* function takes no arguments */
int main(void) /* and returns no value. */
{
prn_message(); /* fct invocation */
}
void prn_message(void) /* fct definition */
{
printf(“A message for you: “);
printf(“Have a nice day!n”);
} 12
Demo Program – Using a Function
to Calculate the Minimum of 2 Values
#include <stdio.h>
int min(int a, int b);
int main(void)
{
int j, k, m;
printf(“Input two integers: “);
scanf(“%d%d”, &j, &k);
m = min(j, k);
printf(“nOf the two values %d and %d, “
“the minimum is %d.nn”, j, k, m);
return 0;
}
int min(int a, int b)
{
if (a < b)
return a;
else
return b;
}
13
14
Types of User-defined Functions in C
Programming
•Functions with no arguments and no return
value
•Functions with no arguments and a return
value
•Functions with arguments and no return value
•Functions with arguments and a return value
Scope and Lifetime of a variable
Every variable in C programming
has two properties: type and
storage class.
Type refers to the data type of
a variable.
And, storage class determines
the scope and lifetime of a
variable.
15
Scope and Lifetime of a variable
There are 4 types of storage
class:
1. automatic
2. external
3. static
4. register
16
Local Variable
b The variables declared inside
the function are automatic or
local variables.
b The local variables exist
only inside the function in
which it is declared. When
the function exits, the local
variables are destroyed.
17
Global Variable
Variables that are declared
outside of all functions are
known as external variables.
External or global variables
are accessible to any
function.
18
Register Variable
b The register keyword is used to
declare register variables.
Register variables were supposed to
be faster than local variables.
b However, modern compilers are very
good at code optimization and there
is a rare chance that using
register variables will make your
program faster.
19
Static Variable
Static variable is declared by
using keyword static. For
example;
static int i;
The value of a static variable
persists until the end of the
program.
20
Calling Functions: Call by Value
and Call by Reference
b Used when invoking functions
b 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 21
Calling Functions: Call by Value
and Call by Reference
b Call by reference
• Passes original argument
• Changes in function effect
original
• Only used with trusted functions
b For now, we focus on call by
value
22
Recursion
b 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
23
Recursion
b 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; 24
Example Using Recursion: The
Fibonacci Series
b 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 )
{ 25
Function Prototypes
b A function prototype tells the
compiler:
• The number and type of arguments that
are to be passed to the function.
• The type of the value that is to be
returned by the function.
b General Form of a Function
Prototype
type function_name( parameter type list);
26
Examples of Function Prototypes
double sqrt(double);
b The parameter list is typically a
comma-separated list of types.
Identifiers are optional.
void f(char c, int i);
is equivalent to
void f(char, int);
27
The Keyword void
b void is used if:
• A function takes no arguments.
• If no value is returned by the
function.
28
Function Invocation
b As we have seen, a function is
invoked (or called) by writing
its name and an appropriate
list of arguments within
parentheses.
• The arguments must match in
number and type the parameters
in the parameter list of the
function definition.
29
Call-by-Value
b In C, all arguments are
passed call-by-value.
• This means that each argument is
evaluated, and its value is used
in place of the corresponding
formal parameter in the called
function.
30
Demonstration Program for Call-by-Value
#include <stdio.h>
int compute_sum(int n);
int main(void)
{
int n = 3, sum;
printf(“%dn”, n); /* 3 is printed */
sum = compute_sum(n);
printf(“%dn”, n); /* 3 is printed */
printf(“%dn”, sum);
return 0;
}
int compute_sum(int n)
{
int sum = 0;
for (; n > 0; --n) /* in main(), n is unchanged */
sum += n;
printf(“%dn”, n); /* 0 is printed */
return sum;
}
31

Weitere ähnliche Inhalte

Was ist angesagt?

RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmigAppili Vamsi Krishna
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++Neeru Mittal
 
Concept of c data types
Concept of c data typesConcept of c data types
Concept of c data typesManisha Keim
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++Vraj Patel
 
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptxC-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptxSKUP1
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in CJeya Lakshmi
 
10. switch case
10. switch case10. switch case
10. switch caseWay2itech
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++Lahiru Dilshan
 
C++ goto statement tutorialspoint
C++ goto statement   tutorialspointC++ goto statement   tutorialspoint
C++ goto statement tutorialspointNAMITHNAVAKRISHNAN
 

Was ist angesagt? (20)

RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Concept of c data types
Concept of c data typesConcept of c data types
Concept of c data types
 
Inline function
Inline functionInline function
Inline function
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
C tokens
C tokensC tokens
C tokens
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptxC-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
10. switch case
10. switch case10. switch case
10. switch case
 
Function in C
Function in CFunction in C
Function in C
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
 
C++ goto statement tutorialspoint
C++ goto statement   tutorialspointC++ goto statement   tutorialspoint
C++ goto statement tutorialspoint
 
Break and continue
Break and continueBreak and continue
Break and continue
 
String functions in C
String functions in CString functions in C
String functions in C
 
C string
C stringC string
C string
 

Ähnlich wie User defined functions

Ähnlich wie User defined functions (20)

CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Functions
Functions Functions
Functions
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
Functions
FunctionsFunctions
Functions
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
 
Functions
FunctionsFunctions
Functions
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 

Mehr von Rokonuzzaman Rony (20)

Course outline for c programming
Course outline for c  programming Course outline for c  programming
Course outline for c programming
 
Pointer
PointerPointer
Pointer
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
Humanitarian task and its importance
Humanitarian task and its importanceHumanitarian task and its importance
Humanitarian task and its importance
 
Structure
StructureStructure
Structure
 
Pointers
 Pointers Pointers
Pointers
 
Loops
LoopsLoops
Loops
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Array
ArrayArray
Array
 
Constants, Variables, and Data Types
Constants, Variables, and Data TypesConstants, Variables, and Data Types
Constants, Variables, and Data Types
 
C Programming language
C Programming languageC Programming language
C Programming language
 
Numerical Method 2
Numerical Method 2Numerical Method 2
Numerical Method 2
 
Numerical Method
Numerical Method Numerical Method
Numerical Method
 
Data structures
Data structuresData structures
Data structures
 
Data structures
Data structures Data structures
Data structures
 
Data structures
Data structures Data structures
Data structures
 
Counting DM
Counting DMCounting DM
Counting DM
 

Kürzlich hochgeladen

Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
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
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
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
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Kürzlich hochgeladen (20)

Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
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
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
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
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 

User defined functions

  • 2. Introduction to Functions b A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself. b This is called structured programming. 2
  • 3. Introduction to Functions b These parts are sometimes made into functions in C. b main() then uses these functions to solve the original problem. 3
  • 4. Structured Programming b Keep the flow of control in a program as simple as possible. b Use top-down design. • Keep decomposing (also known as factoring) a problem into smaller problems until you have a collection of small problems that you can easily solve. 4
  • 5. Top-Down Design Using Functions b C programs normally consist of a collection of user- defined functions. • Each function solves one of the small problems obtained using top-down design. • Functions call or invoke other functions as needed. 5
  • 6. 6 Functions b A function is a block of code that performs a specific task. b A function is a black box that gets some input and produces some output b Functions provide reusable code b Functions simplify debugging
  • 7. Functions b Functions • Modularize a program • All variables declared inside functions are local variables –Known only in function defined • Parameters –Communicate information between functions –Local variables 7
  • 8. Advantages of Functions b Functions separate the concept (what is done) from the implementation (how it is done). b Functions make programs easier to understand. b Functions can be called several times in the same program, allowing the code to be reused. 8
  • 9. Advantages of Functions b 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 9
  • 10. Function Definitions b Function definition format return-value-type function- name( parameter-list ) { declarations and statements } 10
  • 11. Function Definitions • 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 11
  • 12. Function Definitions, Prototypes, and Calls #include <stdio.h> void prn_message(void); /* fct prototype */ /* tells the compiler that this */ /* function takes no arguments */ int main(void) /* and returns no value. */ { prn_message(); /* fct invocation */ } void prn_message(void) /* fct definition */ { printf(“A message for you: “); printf(“Have a nice day!n”); } 12
  • 13. Demo Program – Using a Function to Calculate the Minimum of 2 Values #include <stdio.h> int min(int a, int b); int main(void) { int j, k, m; printf(“Input two integers: “); scanf(“%d%d”, &j, &k); m = min(j, k); printf(“nOf the two values %d and %d, “ “the minimum is %d.nn”, j, k, m); return 0; } int min(int a, int b) { if (a < b) return a; else return b; } 13
  • 14. 14 Types of User-defined Functions in C Programming •Functions with no arguments and no return value •Functions with no arguments and a return value •Functions with arguments and no return value •Functions with arguments and a return value
  • 15. Scope and Lifetime of a variable Every variable in C programming has two properties: type and storage class. Type refers to the data type of a variable. And, storage class determines the scope and lifetime of a variable. 15
  • 16. Scope and Lifetime of a variable There are 4 types of storage class: 1. automatic 2. external 3. static 4. register 16
  • 17. Local Variable b The variables declared inside the function are automatic or local variables. b The local variables exist only inside the function in which it is declared. When the function exits, the local variables are destroyed. 17
  • 18. Global Variable Variables that are declared outside of all functions are known as external variables. External or global variables are accessible to any function. 18
  • 19. Register Variable b The register keyword is used to declare register variables. Register variables were supposed to be faster than local variables. b However, modern compilers are very good at code optimization and there is a rare chance that using register variables will make your program faster. 19
  • 20. Static Variable Static variable is declared by using keyword static. For example; static int i; The value of a static variable persists until the end of the program. 20
  • 21. Calling Functions: Call by Value and Call by Reference b Used when invoking functions b 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 21
  • 22. Calling Functions: Call by Value and Call by Reference b Call by reference • Passes original argument • Changes in function effect original • Only used with trusted functions b For now, we focus on call by value 22
  • 23. Recursion b 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 23
  • 24. Recursion b 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; 24
  • 25. Example Using Recursion: The Fibonacci Series b 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 ) { 25
  • 26. Function Prototypes b A function prototype tells the compiler: • The number and type of arguments that are to be passed to the function. • The type of the value that is to be returned by the function. b General Form of a Function Prototype type function_name( parameter type list); 26
  • 27. Examples of Function Prototypes double sqrt(double); b The parameter list is typically a comma-separated list of types. Identifiers are optional. void f(char c, int i); is equivalent to void f(char, int); 27
  • 28. The Keyword void b void is used if: • A function takes no arguments. • If no value is returned by the function. 28
  • 29. Function Invocation b As we have seen, a function is invoked (or called) by writing its name and an appropriate list of arguments within parentheses. • The arguments must match in number and type the parameters in the parameter list of the function definition. 29
  • 30. Call-by-Value b In C, all arguments are passed call-by-value. • This means that each argument is evaluated, and its value is used in place of the corresponding formal parameter in the called function. 30
  • 31. Demonstration Program for Call-by-Value #include <stdio.h> int compute_sum(int n); int main(void) { int n = 3, sum; printf(“%dn”, n); /* 3 is printed */ sum = compute_sum(n); printf(“%dn”, n); /* 3 is printed */ printf(“%dn”, sum); return 0; } int compute_sum(int n) { int sum = 0; for (; n > 0; --n) /* in main(), n is unchanged */ sum += n; printf(“%dn”, n); /* 0 is printed */ return sum; } 31