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

PPT
RECURSION IN C
PPTX
Function in c
PPTX
PPTX
Functions in c
PPTX
User defined functions in C
PPTX
Function in c program
PPT
user defined function
PPT
Memory allocation in c
RECURSION IN C
Function in c
Functions in c
User defined functions in C
Function in c program
user defined function
Memory allocation in c

What's hot (20)

PPTX
Control structures in c++
PDF
Pointers in C
PPTX
Functions in C
PPSX
Function in c
PPTX
Constructor and Types of Constructors
PPTX
Control statements in c
PPTX
classes and objects in C++
PPT
User defined functions in C programmig
PPTX
Operators and expressions in c language
PPTX
File in C language
ODP
Function
PPTX
Control Flow Statements
PPTX
Printf and scanf
PPTX
C decision making and looping.
PPTX
Dynamic memory allocation in c
PPT
File handling in c
PPSX
C lecture 4 nested loops and jumping statements slideshare
PPTX
Type casting in c programming
PPTX
Functions in C
PPTX
Storage class in C Language
Control structures in c++
Pointers in C
Functions in C
Function in c
Constructor and Types of Constructors
Control statements in c
classes and objects in C++
User defined functions in C programmig
Operators and expressions in c language
File in C language
Function
Control Flow Statements
Printf and scanf
C decision making and looping.
Dynamic memory allocation in c
File handling in c
C lecture 4 nested loops and jumping statements slideshare
Type casting in c programming
Functions in C
Storage class in C Language
Ad

Similar to User defined functions (20)

PPTX
CHAPTER THREE FUNCTION.pptx
PPTX
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
PDF
PSPC-UNIT-4.pdf
PPT
Material 3 (4).ppt this ppt is about the
PPTX
unit_2 (1).pptx
PPTX
Function oneshot with python programming .pptx
PPTX
Lecture 1_Functions in C.pptx
PPTX
Funtions of c programming. the functions of c helps to clarify all the tops
PPTX
CH.4FUNCTIONS IN C (1).pptx
PPTX
Functions
PPT
PPTX
Presentation on Function in C Programming
PPTX
C functions by ranjan call by value and reference.pptx
PPTX
unit_2.pptx
PPT
Lecture 4
PDF
PPTX
Unit 7. Functions
PDF
Functions
PPTX
The function contains the set of programming statements enclosed by {}  when ...
PPT
arrays.ppt
CHAPTER THREE FUNCTION.pptx
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
PSPC-UNIT-4.pdf
Material 3 (4).ppt this ppt is about the
unit_2 (1).pptx
Function oneshot with python programming .pptx
Lecture 1_Functions in C.pptx
Funtions of c programming. the functions of c helps to clarify all the tops
CH.4FUNCTIONS IN C (1).pptx
Functions
Presentation on Function in C Programming
C functions by ranjan call by value and reference.pptx
unit_2.pptx
Lecture 4
Unit 7. Functions
Functions
The function contains the set of programming statements enclosed by {}  when ...
arrays.ppt
Ad

More from Rokonuzzaman Rony (20)

PPTX
Course outline for c programming
PPTX
PPTX
Operator Overloading & Type Conversions
PPTX
Constructors & Destructors
PPTX
Classes and objects in c++
PPTX
Functions in c++
PPTX
Object Oriented Programming with C++
PPTX
Humanitarian task and its importance
PPTX
PPTX
PPTX
Introduction to C programming
PPTX
Constants, Variables, and Data Types
PPTX
C Programming language
PPTX
Numerical Method 2
PPT
Numerical Method
PPTX
Data structures
PPT
Data structures
PPTX
Data structures
Course outline for c programming
Operator Overloading & Type Conversions
Constructors & Destructors
Classes and objects in c++
Functions in c++
Object Oriented Programming with C++
Humanitarian task and its importance
Introduction to C programming
Constants, Variables, and Data Types
C Programming language
Numerical Method 2
Numerical Method
Data structures
Data structures
Data structures

Recently uploaded (20)

PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
RMMM.pdf make it easy to upload and study
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
01-Introduction-to-Information-Management.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Pharma ospi slides which help in ospi learning
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Supply Chain Operations Speaking Notes -ICLT Program
RMMM.pdf make it easy to upload and study
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Pre independence Education in Inndia.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPH.pptx obstetrics and gynecology in nursing
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
01-Introduction-to-Information-Management.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Pharma ospi slides which help in ospi learning
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Microbial disease of the cardiovascular and lymphatic systems
Final Presentation General Medicine 03-08-2024.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
FourierSeries-QuestionsWithAnswers(Part-A).pdf

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