SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
USER-DEFINED
FUNCTIONS IN C
FUNCTION
What is a function in C?
A function is a group of statements that together perform
a task.
How many types of functions are there in C?
There are two kinds of functions in C:
a. Library functions (e.g. main(), printf(), scanf(), etc)
b. User defined functions
In this presentation we are going to complete user-defined
functions in C.
What is a “user-defined function” in C?
A user defined function is a programmed routine that has
its parameters set by the user of the system. User defined
functions often are seen as programming shortcuts as they
define functions that perform specific tasks within a larger
system, such as a database or a spreadsheet program.
Parts of a function:
There are three parts in a function. They are as follows:
a. Function Prototype
b. Function Call
c. Function Definition
Function Prototype:
In computer programming, a function prototype is a declaration of a
function that specifies the function’s name and the type signature(data
types of parameters and return type), but omits the function body.
What is the purpose of a function prototype?
The function prototype serves the following purposes:
1. It tells the return type of the data that the function will return.
2. It tells the number of arguments passed to the function.
3. It tells the data type of each of the passed arguments.
4. It tells the order in which the arguments are passed to the
function.
The function prototype is usually written over the main statement if
function definition is after function usage.
Function Call:
A function call is a request made by a program or script that
performs a predefined function.
What is the purpose of a function call?
A function call is used to call the definition of a particular
function to perform a task or calculation in a particular
program.
Function Definition:
A function definition tells the compiler about a function’s
name, return type and parameters. A function definition
provides the actual body of the function.
What is the purpose of a function definition?
It is used to define what the function will do in the program
i.e. the calculations and tasks that has to be done or
calculated and shown as output by the program.
Syntax of user-defined function in C
 Prototype
int mult(int,int)
 Function Call
int c=mult(10,20);
int d=mult(a,b);
 Definition
int mult(int fa,int fb)
{
int temp;
temp=fa*fb;
return temp;
}
Here is a program to show what a user-defined
program looks like:
Write a program in C to implement addition of two numbers using user-defined function.
#include<stdio.h>
void add(int,int); //function prototype
int main()
{
int a,b,c;
printf(“n Enter first no: ”);
scanf(“%d”,&a);
printf(“n Enter second no: ”);
scanf(“%d”,&b);
c=add(a,b); //function call
return 0;
}
void add(int x,int y) //function definition
{
int z;
z=x+y;
printf(“n The addition is: ”,z);
}
Types of user-defined functions
There are four kinds of user-defined functions in C:
1. Function with no arguments and no return value.
2. Function with no arguments but with return value.
3. Function with arguments but no return value.
4. Function with arguments and return value.
Function with no arguments and no return value.
Function with no arguments but with return value.
Function with arguments but no return value.
Function with arguments and return value.
Arguments:
An argument is an expression which is passed to a function by
its caller (or macro by its invoker) in order for the function (or
macro) to perform the task. It is an expression in the comma-
separated list bound by the parameters in a function call
expression.
In user-defined function, there can be two types of parameters
or arguments present. They are as follows:
a. Actual Parameters/Arguments
b. Formal Parameters/Arguments
Actual Arguments:
The arguments that are passed in a function call are called
actual arguments. These arguments are defined in the calling
function.
Formal Arguments:
The formal arguments are the parameters/arguments in a
function declaration. The scope of formal arguments is local to
the function definition in which they are used. Formal
arguments belong to the called function. Formal arguments
are a copy of the actual arguments. A change in the formal
arguments would not be reflected in the actual arguments.
Here is an example showing the actual and formal
parameters in a function.
#include<stdio.h>
void sum(int i,int j,int k);
int main()
{
int a=5;
sum(3,2*a,b); //Actual Arguments
return 0;
}
void sum(int i,int j,int k) //Formal Arguments
{
int s;
s=i+j+k;
printf(“n sum= %d”,s);
}
Passing parameters in a function:
There are two ways in which arguments can be passed to the called function.
Call-by-value in which values if the variables are passed by the calling function to
the called function.
Call-by-reference in which address of the variables are passed by the calling
function to the called function.
Passing parameters to a function
Call-by-value Call-by-reference
Call by value:
 In this method, the called function creates new
variables to store the value of the arguments passed
to it. Therefore, the called function uses a copy of
the actual arguments to perform its intended task.
 If the called function is supposed to modify the value
of the parameters passed to it, then the change will
be reflected only in the called function. In the calling
function no change will be made to the value of the
variables.
Example of what happens in “Call-by-value”.
#include<stdio.h>
void funct(int);
int main()
{
int num=2;
printf(“n Value of ‘num’ before calling the function=%d”,num);
funct(num);
printf(“n The value of num after calling the function=%d”,num);
return 0;
}
void funct(int n)
{
n=n*10;
printf(“n value of ‘num’ in called function=%d”,n);
}
Output:
Value of ‘num’ before calling the function=2
Value of ‘num’ in the called function=20
Value of ‘num’ after calling the function=2
Call by reference:
 When the calling function passes arguments to the called function
using call by value method, the only way to return the modified value
of the argument to the caller is explicitly using the return statement.
The better option when a function can modify the value of the
argument is to pass arguments using call by reference technique.
 In Call by reference, we declare the function parameters as
references rather than normal variables. When this is done, any
changes made by the function to the arguments it received are visible
by the calling program.
 To indicate that an argument is passed using Call by reference, an
ampersand sign(&) is placed after the type in the parameter list. This
way, changes made to that parameter in the called function body will
then be reflected in its value in the calling program.
Example of what happens in “Call-by-reference”:
#include<stdio.h>
void funct(int &n);
int main()
{
int num=2;
printf(“n Value of ‘num’ before calling the function=%d”,num);
funct(num);
printf(“n The value of num after calling the function=%d”,num);
return 0;
}
void funct(int &n)
{
n=n*10;
printf(“n value of ‘num’ in called function=%d”,n);
}
Output:
Value of ‘num’ before calling the function=2
Value of ‘num’ in the called function=20
Value of ‘num’ after calling the function=20
Variables due to user-defined functions in C:
In C, due to user-defined functions, we geet two
types of variables depending on their lifetime and
scope in a function. They are as follows:
a. Local Variables
b. Global Variables
Local Variables:
Variables that are declared inside a function or block are called local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not known to
functions outside their own.
The following program shows how to use local variables in a program:
#include<stdio.h>
int main()
{
int a,b; //Local Variable declaration
int c;
a=10; //actual initialisation
b=20;
c=a+b;
printf(“n Value of a=%d, b=%d and c=%d”,a,b,c);
return 0;
}
Global Variables:
Global Variables are defined outside a function, usually on top of the program. Global Variables
hold their values throughout the lifetime of the program and they can be accessed inside any of the
functions designed for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout the entire program after its declaration.
The following program shows how to use global variables in a program:
#include<stdio.h>
int g; //Global Variable declared
int main()
{
int a,b; //Local Variables declared
a=10; //actual initialization
b=20;
g=a+b;
printf(“n The value of g is=%d”,g);
return 0;
}
Scope and Lifetime of a variable:
Life Time: Life time of any variable is the time for which the particular variable outlives in
memory during running of the program.
Scope: The scope of any variable is actually a subset of life time. A variable may be in
the memory but may not be accessible though. So, the area of our program
where we can actually access our entity(variable in this case) is scope of that
variable.
The scope of any variable can be categorised into three categories:
Global Scope: When variable is defined outside all functions. It is then available to
all the functions of the program and all the blocks program contains.
Local Scope: When variable is defined inside a function or a block, then it is
locally accessible within the block and hence it is a local variable.
Function Scope: When variable is passed as formal arguments, it is said to have
function scope.
Recursion:
What is a “recursive function” in C?
A recursive function is a function that calls itself to solve a smaller version of its
task until a final call is made which does not require a call to itself.
Every recursive function has two major cases which are:
 Base Case in which the problem is simple enough to be solved directly without
making further calls to the same function.
 Recursive Case in which,
First, the problem at hand is divided into simpler sub-parts.
Second, the function calls itself but sub-parts of the problem
obtained in the first step.
Third, the result is obtained by combining the solutions of the
simpler sub-parts.
Syntax and flowchart of recursive function:
Syntax:
returntype recursive_func ([argument
list])
{
statements;
... ... ...
recursive_func ([actual
argument]);
... ... ...
}
Flowchart:
How recursion works:
C Program to show infinite recursive function:
#include<stdio.h>
int main()
{
printf(“n Hello World”);
main();
return 0;
}
There are two types of recursion:
Direct Recursion
A function is said to be direct recursive
if it calls itself directly.
Indirect Recursion
A function is said to be indirect
recursive if it calls another function and
this new function calls the first calling
function again.
C Program to calculate factorial of a number using recursion:
#include<stdio.h>
int fact(int);
Int main()
{
int n,t;
printf(“n Enter the number whose factorial you want: ”);
scanf(“%d”,&n);
t=fact(n);
printf(“n Factorial of the given number is: ”);
return 0;
}
int fact(int num)
{
int p;
if(num==1)
return 1;
else
{
p=num*fact(num-1);
return p;
}
}
Disadvantages of Recursion:
 Recursive programs are generally slower than non
recursive programs because it needs to make a function
call so the program must save all its current state and
retrieve them again later. This consumes more time
making recursive programs slower.
 Recursive programs requires more memory to hold
intermediate states in a stack. Non recursive programs
don't have any intermediate states, hence they don't
require any extra memory.
Advantages of user-defined functions:
1. The sub-program are easier to write, understand
and debug.
2. Reduction in size of program due to program code
of a function can be used again and again by calling
it.
3. The complexity of the entire program can be divided
into simple subtask and the function sub-programs
can be written for each task.

Contenu connexe

Tendances (20)

C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 
Functions in C
Functions in CFunctions in C
Functions in C
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
String in c programming
String in c programmingString in c programming
String in c programming
 
Storage Class in C Progrmming
Storage Class in C Progrmming Storage Class in C Progrmming
Storage Class in C Progrmming
 
self_refrential_structures.pptx
self_refrential_structures.pptxself_refrential_structures.pptx
self_refrential_structures.pptx
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
C functions
C functionsC functions
C functions
 
Linked list
Linked listLinked list
Linked list
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Selection sort
Selection sortSelection sort
Selection sort
 
C Language
C LanguageC Language
C Language
 
358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3
 
Data Representation of Strings
Data Representation of StringsData Representation of Strings
Data Representation of Strings
 
GDG Helwan Introduction to python
GDG Helwan Introduction to pythonGDG Helwan Introduction to python
GDG Helwan Introduction to python
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
 
Recursion
RecursionRecursion
Recursion
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
Function in c
Function in cFunction in c
Function in c
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 

Similaire à USER DEFINED FUNCTIONS IN C.pdf

CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfJAVVAJI VENKATA RAO
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxvekariyakashyap
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Presentation on function
Presentation on functionPresentation on function
Presentation on functionAbu Zaman
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
 

Similaire à USER DEFINED FUNCTIONS IN C.pdf (20)

CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Function in c
Function in cFunction in c
Function in c
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
C functions list
C functions listC functions list
C functions list
 
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 

Dernier

عناصر نباتية PDF.pdf architecture engineering
عناصر نباتية PDF.pdf architecture engineeringعناصر نباتية PDF.pdf architecture engineering
عناصر نباتية PDF.pdf architecture engineeringmennamohamed200y
 
The Art of Cloud Native Defense on Kubernetes
The Art of Cloud Native Defense on KubernetesThe Art of Cloud Native Defense on Kubernetes
The Art of Cloud Native Defense on KubernetesJacopo Nardiello
 
Governors ppt.pdf .
Governors ppt.pdf                              .Governors ppt.pdf                              .
Governors ppt.pdf .happycocoman
 
The Journey of Process Safety Management: Past, Present, and Future Trends
The Journey of Process Safety Management: Past, Present, and Future TrendsThe Journey of Process Safety Management: Past, Present, and Future Trends
The Journey of Process Safety Management: Past, Present, and Future Trendssoginsider
 
Evaluation Methods for Social XR Experiences
Evaluation Methods for Social XR ExperiencesEvaluation Methods for Social XR Experiences
Evaluation Methods for Social XR ExperiencesMark Billinghurst
 
Final PPT.ppt about human detection and counting
Final PPT.ppt  about human detection and countingFinal PPT.ppt  about human detection and counting
Final PPT.ppt about human detection and countingArbazAhmad25
 
First Review Group 1 PPT.pptx with slide
First Review Group 1 PPT.pptx with slideFirst Review Group 1 PPT.pptx with slide
First Review Group 1 PPT.pptx with slideMonika860882
 
Road to GDSC (Become the next GDSC lead)
Road to GDSC (Become the next GDSC lead)Road to GDSC (Become the next GDSC lead)
Road to GDSC (Become the next GDSC lead)GDSCNiT
 
عناصر نباتية PDF.pdfbotanical elements..
عناصر نباتية PDF.pdfbotanical elements..عناصر نباتية PDF.pdfbotanical elements..
عناصر نباتية PDF.pdfbotanical elements..mennamohamed200y
 
Research paper publications: Meaning of Q1 Q2 Q3 Q4 Journal
Research paper publications: Meaning of Q1 Q2 Q3 Q4 JournalResearch paper publications: Meaning of Q1 Q2 Q3 Q4 Journal
Research paper publications: Meaning of Q1 Q2 Q3 Q4 JournalDr. Manjunatha. P
 
Injection Power Cycle - The most efficient power cycle
Injection Power Cycle - The most efficient power cycleInjection Power Cycle - The most efficient power cycle
Injection Power Cycle - The most efficient power cyclemarijomiljkovic1
 
Artificial organ courses Hussein L1-C2.pptx
Artificial organ courses Hussein  L1-C2.pptxArtificial organ courses Hussein  L1-C2.pptx
Artificial organ courses Hussein L1-C2.pptxHusseinMishbak
 
introduction to python, fundamentals and basics
introduction to python, fundamentals and basicsintroduction to python, fundamentals and basics
introduction to python, fundamentals and basicsKNaveenKumarECE
 
A brief about Jeypore Sub-station Presentation
A brief about Jeypore Sub-station PresentationA brief about Jeypore Sub-station Presentation
A brief about Jeypore Sub-station PresentationJeyporess2021
 
0950_Rodriguez_200520_Work_done-GEOGalicia_ELAB-converted.pptx
0950_Rodriguez_200520_Work_done-GEOGalicia_ELAB-converted.pptx0950_Rodriguez_200520_Work_done-GEOGalicia_ELAB-converted.pptx
0950_Rodriguez_200520_Work_done-GEOGalicia_ELAB-converted.pptxssuser886c55
 
PhD summary of Luuk Brederode, presented at 2023-10-17 to Veitch Lister Consu...
PhD summary of Luuk Brederode, presented at 2023-10-17 to Veitch Lister Consu...PhD summary of Luuk Brederode, presented at 2023-10-17 to Veitch Lister Consu...
PhD summary of Luuk Brederode, presented at 2023-10-17 to Veitch Lister Consu...Luuk Brederode
 

Dernier (20)

عناصر نباتية PDF.pdf architecture engineering
عناصر نباتية PDF.pdf architecture engineeringعناصر نباتية PDF.pdf architecture engineering
عناصر نباتية PDF.pdf architecture engineering
 
Industry perspective on cold in-place recycling
Industry perspective on cold in-place recyclingIndustry perspective on cold in-place recycling
Industry perspective on cold in-place recycling
 
The Art of Cloud Native Defense on Kubernetes
The Art of Cloud Native Defense on KubernetesThe Art of Cloud Native Defense on Kubernetes
The Art of Cloud Native Defense on Kubernetes
 
Governors ppt.pdf .
Governors ppt.pdf                              .Governors ppt.pdf                              .
Governors ppt.pdf .
 
FOREST FIRE USING IoT-A Visual to UG students
FOREST FIRE USING IoT-A Visual to UG studentsFOREST FIRE USING IoT-A Visual to UG students
FOREST FIRE USING IoT-A Visual to UG students
 
Caltrans view on recycling of in-place asphalt pavements
Caltrans view on recycling of in-place asphalt pavementsCaltrans view on recycling of in-place asphalt pavements
Caltrans view on recycling of in-place asphalt pavements
 
The Journey of Process Safety Management: Past, Present, and Future Trends
The Journey of Process Safety Management: Past, Present, and Future TrendsThe Journey of Process Safety Management: Past, Present, and Future Trends
The Journey of Process Safety Management: Past, Present, and Future Trends
 
Evaluation Methods for Social XR Experiences
Evaluation Methods for Social XR ExperiencesEvaluation Methods for Social XR Experiences
Evaluation Methods for Social XR Experiences
 
Final PPT.ppt about human detection and counting
Final PPT.ppt  about human detection and countingFinal PPT.ppt  about human detection and counting
Final PPT.ppt about human detection and counting
 
First Review Group 1 PPT.pptx with slide
First Review Group 1 PPT.pptx with slideFirst Review Group 1 PPT.pptx with slide
First Review Group 1 PPT.pptx with slide
 
Road to GDSC (Become the next GDSC lead)
Road to GDSC (Become the next GDSC lead)Road to GDSC (Become the next GDSC lead)
Road to GDSC (Become the next GDSC lead)
 
Update on the latest research with regard to RAP
Update on the latest research with regard to RAPUpdate on the latest research with regard to RAP
Update on the latest research with regard to RAP
 
عناصر نباتية PDF.pdfbotanical elements..
عناصر نباتية PDF.pdfbotanical elements..عناصر نباتية PDF.pdfbotanical elements..
عناصر نباتية PDF.pdfbotanical elements..
 
Research paper publications: Meaning of Q1 Q2 Q3 Q4 Journal
Research paper publications: Meaning of Q1 Q2 Q3 Q4 JournalResearch paper publications: Meaning of Q1 Q2 Q3 Q4 Journal
Research paper publications: Meaning of Q1 Q2 Q3 Q4 Journal
 
Injection Power Cycle - The most efficient power cycle
Injection Power Cycle - The most efficient power cycleInjection Power Cycle - The most efficient power cycle
Injection Power Cycle - The most efficient power cycle
 
Artificial organ courses Hussein L1-C2.pptx
Artificial organ courses Hussein  L1-C2.pptxArtificial organ courses Hussein  L1-C2.pptx
Artificial organ courses Hussein L1-C2.pptx
 
introduction to python, fundamentals and basics
introduction to python, fundamentals and basicsintroduction to python, fundamentals and basics
introduction to python, fundamentals and basics
 
A brief about Jeypore Sub-station Presentation
A brief about Jeypore Sub-station PresentationA brief about Jeypore Sub-station Presentation
A brief about Jeypore Sub-station Presentation
 
0950_Rodriguez_200520_Work_done-GEOGalicia_ELAB-converted.pptx
0950_Rodriguez_200520_Work_done-GEOGalicia_ELAB-converted.pptx0950_Rodriguez_200520_Work_done-GEOGalicia_ELAB-converted.pptx
0950_Rodriguez_200520_Work_done-GEOGalicia_ELAB-converted.pptx
 
PhD summary of Luuk Brederode, presented at 2023-10-17 to Veitch Lister Consu...
PhD summary of Luuk Brederode, presented at 2023-10-17 to Veitch Lister Consu...PhD summary of Luuk Brederode, presented at 2023-10-17 to Veitch Lister Consu...
PhD summary of Luuk Brederode, presented at 2023-10-17 to Veitch Lister Consu...
 

USER DEFINED FUNCTIONS IN C.pdf

  • 2. FUNCTION What is a function in C? A function is a group of statements that together perform a task. How many types of functions are there in C? There are two kinds of functions in C: a. Library functions (e.g. main(), printf(), scanf(), etc) b. User defined functions In this presentation we are going to complete user-defined functions in C.
  • 3. What is a “user-defined function” in C? A user defined function is a programmed routine that has its parameters set by the user of the system. User defined functions often are seen as programming shortcuts as they define functions that perform specific tasks within a larger system, such as a database or a spreadsheet program. Parts of a function: There are three parts in a function. They are as follows: a. Function Prototype b. Function Call c. Function Definition
  • 4. Function Prototype: In computer programming, a function prototype is a declaration of a function that specifies the function’s name and the type signature(data types of parameters and return type), but omits the function body. What is the purpose of a function prototype? The function prototype serves the following purposes: 1. It tells the return type of the data that the function will return. 2. It tells the number of arguments passed to the function. 3. It tells the data type of each of the passed arguments. 4. It tells the order in which the arguments are passed to the function. The function prototype is usually written over the main statement if function definition is after function usage.
  • 5. Function Call: A function call is a request made by a program or script that performs a predefined function. What is the purpose of a function call? A function call is used to call the definition of a particular function to perform a task or calculation in a particular program.
  • 6. Function Definition: A function definition tells the compiler about a function’s name, return type and parameters. A function definition provides the actual body of the function. What is the purpose of a function definition? It is used to define what the function will do in the program i.e. the calculations and tasks that has to be done or calculated and shown as output by the program.
  • 7. Syntax of user-defined function in C  Prototype int mult(int,int)  Function Call int c=mult(10,20); int d=mult(a,b);  Definition int mult(int fa,int fb) { int temp; temp=fa*fb; return temp; }
  • 8. Here is a program to show what a user-defined program looks like: Write a program in C to implement addition of two numbers using user-defined function. #include<stdio.h> void add(int,int); //function prototype int main() { int a,b,c; printf(“n Enter first no: ”); scanf(“%d”,&a); printf(“n Enter second no: ”); scanf(“%d”,&b); c=add(a,b); //function call return 0; } void add(int x,int y) //function definition { int z; z=x+y; printf(“n The addition is: ”,z); }
  • 9. Types of user-defined functions There are four kinds of user-defined functions in C: 1. Function with no arguments and no return value. 2. Function with no arguments but with return value. 3. Function with arguments but no return value. 4. Function with arguments and return value.
  • 10. Function with no arguments and no return value.
  • 11. Function with no arguments but with return value.
  • 12. Function with arguments but no return value.
  • 13. Function with arguments and return value.
  • 14. Arguments: An argument is an expression which is passed to a function by its caller (or macro by its invoker) in order for the function (or macro) to perform the task. It is an expression in the comma- separated list bound by the parameters in a function call expression. In user-defined function, there can be two types of parameters or arguments present. They are as follows: a. Actual Parameters/Arguments b. Formal Parameters/Arguments
  • 15. Actual Arguments: The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function. Formal Arguments: The formal arguments are the parameters/arguments in a function declaration. The scope of formal arguments is local to the function definition in which they are used. Formal arguments belong to the called function. Formal arguments are a copy of the actual arguments. A change in the formal arguments would not be reflected in the actual arguments.
  • 16. Here is an example showing the actual and formal parameters in a function. #include<stdio.h> void sum(int i,int j,int k); int main() { int a=5; sum(3,2*a,b); //Actual Arguments return 0; } void sum(int i,int j,int k) //Formal Arguments { int s; s=i+j+k; printf(“n sum= %d”,s); }
  • 17. Passing parameters in a function: There are two ways in which arguments can be passed to the called function. Call-by-value in which values if the variables are passed by the calling function to the called function. Call-by-reference in which address of the variables are passed by the calling function to the called function. Passing parameters to a function Call-by-value Call-by-reference
  • 18. Call by value:  In this method, the called function creates new variables to store the value of the arguments passed to it. Therefore, the called function uses a copy of the actual arguments to perform its intended task.  If the called function is supposed to modify the value of the parameters passed to it, then the change will be reflected only in the called function. In the calling function no change will be made to the value of the variables.
  • 19. Example of what happens in “Call-by-value”. #include<stdio.h> void funct(int); int main() { int num=2; printf(“n Value of ‘num’ before calling the function=%d”,num); funct(num); printf(“n The value of num after calling the function=%d”,num); return 0; } void funct(int n) { n=n*10; printf(“n value of ‘num’ in called function=%d”,n); } Output: Value of ‘num’ before calling the function=2 Value of ‘num’ in the called function=20 Value of ‘num’ after calling the function=2
  • 20. Call by reference:  When the calling function passes arguments to the called function using call by value method, the only way to return the modified value of the argument to the caller is explicitly using the return statement. The better option when a function can modify the value of the argument is to pass arguments using call by reference technique.  In Call by reference, we declare the function parameters as references rather than normal variables. When this is done, any changes made by the function to the arguments it received are visible by the calling program.  To indicate that an argument is passed using Call by reference, an ampersand sign(&) is placed after the type in the parameter list. This way, changes made to that parameter in the called function body will then be reflected in its value in the calling program.
  • 21. Example of what happens in “Call-by-reference”: #include<stdio.h> void funct(int &n); int main() { int num=2; printf(“n Value of ‘num’ before calling the function=%d”,num); funct(num); printf(“n The value of num after calling the function=%d”,num); return 0; } void funct(int &n) { n=n*10; printf(“n value of ‘num’ in called function=%d”,n); } Output: Value of ‘num’ before calling the function=2 Value of ‘num’ in the called function=20 Value of ‘num’ after calling the function=20
  • 22. Variables due to user-defined functions in C: In C, due to user-defined functions, we geet two types of variables depending on their lifetime and scope in a function. They are as follows: a. Local Variables b. Global Variables
  • 23. Local Variables: Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following program shows how to use local variables in a program: #include<stdio.h> int main() { int a,b; //Local Variable declaration int c; a=10; //actual initialisation b=20; c=a+b; printf(“n Value of a=%d, b=%d and c=%d”,a,b,c); return 0; }
  • 24. Global Variables: Global Variables are defined outside a function, usually on top of the program. Global Variables hold their values throughout the lifetime of the program and they can be accessed inside any of the functions designed for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout the entire program after its declaration. The following program shows how to use global variables in a program: #include<stdio.h> int g; //Global Variable declared int main() { int a,b; //Local Variables declared a=10; //actual initialization b=20; g=a+b; printf(“n The value of g is=%d”,g); return 0; }
  • 25. Scope and Lifetime of a variable: Life Time: Life time of any variable is the time for which the particular variable outlives in memory during running of the program. Scope: The scope of any variable is actually a subset of life time. A variable may be in the memory but may not be accessible though. So, the area of our program where we can actually access our entity(variable in this case) is scope of that variable. The scope of any variable can be categorised into three categories: Global Scope: When variable is defined outside all functions. It is then available to all the functions of the program and all the blocks program contains. Local Scope: When variable is defined inside a function or a block, then it is locally accessible within the block and hence it is a local variable. Function Scope: When variable is passed as formal arguments, it is said to have function scope.
  • 26. Recursion: What is a “recursive function” in C? A recursive function is a function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself. Every recursive function has two major cases which are:  Base Case in which the problem is simple enough to be solved directly without making further calls to the same function.  Recursive Case in which, First, the problem at hand is divided into simpler sub-parts. Second, the function calls itself but sub-parts of the problem obtained in the first step. Third, the result is obtained by combining the solutions of the simpler sub-parts.
  • 27. Syntax and flowchart of recursive function: Syntax: returntype recursive_func ([argument list]) { statements; ... ... ... recursive_func ([actual argument]); ... ... ... } Flowchart:
  • 29. C Program to show infinite recursive function: #include<stdio.h> int main() { printf(“n Hello World”); main(); return 0; }
  • 30. There are two types of recursion: Direct Recursion A function is said to be direct recursive if it calls itself directly. Indirect Recursion A function is said to be indirect recursive if it calls another function and this new function calls the first calling function again.
  • 31. C Program to calculate factorial of a number using recursion: #include<stdio.h> int fact(int); Int main() { int n,t; printf(“n Enter the number whose factorial you want: ”); scanf(“%d”,&n); t=fact(n); printf(“n Factorial of the given number is: ”); return 0; } int fact(int num) { int p; if(num==1) return 1; else { p=num*fact(num-1); return p; } }
  • 32. Disadvantages of Recursion:  Recursive programs are generally slower than non recursive programs because it needs to make a function call so the program must save all its current state and retrieve them again later. This consumes more time making recursive programs slower.  Recursive programs requires more memory to hold intermediate states in a stack. Non recursive programs don't have any intermediate states, hence they don't require any extra memory.
  • 33. Advantages of user-defined functions: 1. The sub-program are easier to write, understand and debug. 2. Reduction in size of program due to program code of a function can be used again and again by calling it. 3. The complexity of the entire program can be divided into simple subtask and the function sub-programs can be written for each task.