SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in CHarendra Singh
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)Ritika Sharma
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)VC Infotech
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structureshaibal sharif
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programmingprogramming9
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variablessangrampatil81
 
Type casting in java
Type casting in javaType casting in java
Type casting in javaFarooq Baloch
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
Storage class in c
Storage class in cStorage class in c
Storage class in ckash95
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C ProgrammingQazi Shahzad Ali
 
Basic Data Types in C++
Basic Data Types in C++ Basic Data Types in C++
Basic Data Types in C++ Hridoy Bepari
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
 

Tendances (20)

User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Basic Data Types in C++
Basic Data Types in C++ Basic Data Types in C++
Basic Data Types in C++
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 

Similaire à User defined functions

Similaire à 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
 

Plus de 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++
 
Functions in c++
Functions in c++Functions in c++
Functions 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
 

Dernier

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 

Dernier (20)

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 

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