SlideShare a Scribd company logo
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

More Related Content

What's hot

classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
DevoAjit Gupta
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
ppd1961
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Nilesh Dalvi
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
sangrampatil81
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++

What's hot (20)

Function in C program
Function in C programFunction in C program
Function in C program
 
Functions in C
Functions in CFunctions in C
Functions in C
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
C language unit-1
C language unit-1C language unit-1
C language unit-1
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Function in c
Function in cFunction in c
Function in c
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Function in c
Function in cFunction in c
Function in c
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 

Similar to User defined functions

CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
Functions
Functions Functions
Functions
Praneeth960856
 
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
Shuvongkor Barman
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
Venkatesh Goud
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
Mohammed Saleh
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
Ashim Lamichhane
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
Bharath904863
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
LadallaRajKumar
 
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
imtiazalijoono
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Functions
FunctionsFunctions
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 

Similar to 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
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
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++
 

More from Rokonuzzaman Rony

Course outline for c programming
Course outline for c  programming Course outline for c  programming
Course outline for c programming
Rokonuzzaman Rony
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
Rokonuzzaman Rony
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
Rokonuzzaman Rony
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
Rokonuzzaman Rony
 
Humanitarian task and its importance
Humanitarian task and its importanceHumanitarian task and its importance
Humanitarian task and its importance
Rokonuzzaman Rony
 
Pointers
 Pointers Pointers
Loops
LoopsLoops
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
Rokonuzzaman Rony
 
Array
ArrayArray
Constants, Variables, and Data Types
Constants, Variables, and Data TypesConstants, Variables, and Data Types
Constants, Variables, and Data Types
Rokonuzzaman Rony
 
C Programming language
C Programming languageC Programming language
C Programming language
Rokonuzzaman Rony
 

More from 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
 

Recently uploaded

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 

Recently uploaded (20)

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 

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