SlideShare une entreprise Scribd logo
1  sur  51
Télécharger pour lire hors ligne
USER DEFINED FUNCTIONS
REFERENCE: PROGRAMMING IN C BY BALAGURUSWAMY
MRS. SOWMYAJYOTHI, SDMCBM,MANGALORE
User defined functions :
C functions can be classified into two categories,
namely, library functions and user-defined
functions.
The functions which are developed by user at the
time of writing a program are called user defined
functions.
So, user-defined functions are functions created
and developed by user.
Here function01( ) is an user defined function.
main( )
{
=======
=======
function01( );
=======
}
function01( )
{
========
========
}
Necessity of user defined functions :
When not using user defined functions, for a
large program the tasks of debugging, compiling
etc. may become difficult in general.
That’s why user defined functions are extremely
necessary for complex programs.
The necessities or advantages are as follows,
01. It facilitates top-down modular programming. In this
programming style, the high level logic of the overall problem is
solved first while the details of each lower-level function are
addressed later.
02. The length of a source program can be reduced by using
functions at appropriate places.
03. It is easy to locate and isolate a faulty function for further
investigations.
04. A function may be used by many other programs. This means
that a C programmer can build on what others have already done,
instead of starting all over again from scratch.
Multifunction program :
A function is a self-contained block of code that performs a
particular task.
Once a function has been designed and packed, it can be
treated as a ‘black box’ that takes some data from the main
program and returns a value.
Thus a program, which has been written using a number of
functions, is treated as a multifunction program.
Elements of user defined functions :
In order to make use of a user-defined function, we
need to establish three elements that are related to
functions.
1. Function definition
2. Function call
3. Function declaration
The function definition is an independent program
module that is specially written to implement to the
requirements of the function.
In order to use the function we need to invoke it at a
required place in the program. This is known as the
function call.
The program or a function that has called a function is
referred to as the calling function or calling program.
The calling program should declare any function that is to
be used later in the program. This is known as the
function declaration.
1. Function name
2. Function type
3. List of parameters
4. Local variable declarations
5. Function statements
6. A return statement
All the six elements are grouped into two
parts; namely,
•Function header (First three elements)
•Function body (Second three elements)
Function Definition : The function definition is an independent
program module that is specially written to implement to the
requirements of the function. A function definition, also known as
function implementation shall include the following elements
Function Header
The function header consists of three parts; function type, function name and list of parameter.
(a) Function Type
The function type specifies the type of value (like float or double) that the function is expected
to return to the calling program. If the return type is not explicitly specified, C will assume that it
is an integer type.
(b) Function name
The function name is any valid C identifier and therefore must follow the same rules of formation
as other variable names in C. The name should be appropriate to the task performed by the
function.
(c) List of Parameter
The parameter list declares the variables that will receive the data sent by the calling program.
They serve as input data to the function to carry out the specified task.
Example :
float mul (float x, float y)
{
….
}
int sum (int a, int b)
{
….
}
Function body
The function body is enclosed in braces, contains three parts,
in the order given below:
1. Local variable declaration : Local variable declarations are
statements that specify the variables needed by the
function.
2. Function Statements : Function statements are
statements that perform the task of the function.
3. Return Statements : A return statement is a statement
that returns the value evaluated by the function to the calling
program. If a function does not return any value, one can
omit the return statement.
Function call :
In order to use functions user need to invoke it at a
required place in the program. This is known as the
function call.
A function can be called by simply using the function
name followed by a list of actual parameters, if any,
enclosed in parentheses.
Example : Here in the main() program the mul(10,5)
function has been called.
main()
{
int y;
y=mul(10,5); /*Function Call*
printf(“%dn”,y);
}
Function declaration :
The program or a function that called a function is referred to as the calling
function or calling program. The calling program should declare any function that
is to be used later in the program. This is known as the function declaration.
A function declaration consists of four parts. They are,
1. Function type
2. Function name
3. Parameter list
4. Terminating semicolon
They are coded in the following format :
function_type function_name(parameter list);
1. The parameter list must be separated by commas.
2. If the function has no formal parameters, the list is
written as void.
3. The return type is optional when the function returns
int type data.
4. When the declared type does not match the types in
the function definition compiler will produce an error.
Parameter list :
The parameter list contains declaration of variables
separated by commas and surrounded by
parentheses.
float quadratic (int a, int b, int c)
{….
}
Prototype :
The declaration of a function is known as function
prototype. The function prototype is coded in the
following format,
Function_type function_name(parameter list);
Nesting of functions :
In C, each function can contain one or more than one function in it. There is no limit as to how
deeply functions can be nested.
Consider the following example,
main()
{
function1();
}
function1()
{
function2();
}
function2()
{
...............;
}
In the above example,
The main() function contains function01(), the
function01() contains function02 and so on. This is
nesting of functions.
Program to find sum of 2 numbers using function
#include<stdio.h>
#include<conio.h>
int sum(int a, int b); //function declaration
void main()
{
int a,b,c;
clrscr();
printf(“Enter 2 numbers:”);
scanf(“%d%d”,&a,&b);
c=sum(a,b); //function call
printf(“nSum=%d”,c);
getch();
//function definition
int sum(int a, int b)
{
int c=0;
c=a+b;
return c;
}
Recursion:
Recursive function is a function that calls itself.
When a function calls another function and that second function calls
the third function then this kind of a function is called nesting of
functions. But a recursive function is the function that calls itself
repeatedly.
main()
{
printf(“this is an example of recursive function”);
main();
}
When this program is executed. The line is printed repeatedly and indefinitely. We
might have to abruptly terminate the execution.
Factorial Function
a) If N = 0, then N! = 1.
b) If N > 0, then N! = N*(N-1)!
Example:
5! = 5 * 4!
= 5 * 4 * 3!
= 5 * 4 * 3 * 2!
= 5 * 4 * 3 * 2 * 1!
= 5 * 4 * 3 * 2 * 1* 0!
= 5 * 4 * 3 * 2 * 1 * 1
Program to display factorial of a number using recursive function
#include<stdio.h>
#include<conio.h>
long fact(int n);
void main()
{
int n;
long int f;
clrscr();
printf(“enter a number”);
scanf(“%d”, &n);
f=fact(n);
printf(“nFactorial =%ld”),f);
}
long fact(int n)
{
if (n==0)
return 1;
else
return (n*fact(n-1));
}
i=1
n=1
f=n*fact(n-1)
1* fact(1-1)
1* fact(0) = 1*1=1
i=3
f=3*fact(3-1)
=3*fact(2)
=3*2*fact(1-1)
=3*2*fact(0)
=3*2*1
=6
◦n=153
r= 3 5 1
STEP 1: arm=0
r=153%10=3
arm=0+(3*3*3)=27
n=153/10=15
STEP 2:
r=15%10=5
arm=27+(5*5*5)=27+125=152
n=15/10=1
STEP 3:
r=1%10=1
while(n!=0)
r=n%10
arm=arm+(r*r*r)
n=n/10
arm=152+(1*1*1)=153
The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
...
Fibonacci Series is a pattern of numbers where each number is the
result of addition of the previous two consecutive numbers .
First 2 numbers start with 0 and 1.
The third numbers in the sequence is 0+1=1. The 4th number is the
addition of 2nd and 3rd number i.e. 1+1=2 and so on.
The next number is found by adding up the two numbers before it:
the 2 is found by adding the two numbers before it (1+1),
the 3 is found by adding the two numbers before it (1+2),
the 5 is (2+3),
and so on!
f1 f2 f3
f1 f2
f3
{
f3 = f1 + f2;
printf(" %d", f3);
f1 = f2;
f2 = f3;
}
How to reverse a number mathematically.
Step 1 — Isolate the last digit(rem) in number.
rem = number % 10
The modulo operator (%) returns the remainder of a divison.
Step 2 — Append lastDigit(rem) to reverse.
reverse = (reverse * 10) + rem
Step 3-Remove last digit from number.
number = number / 10.
Function Arguments
If a function is to use arguments, it must declare
variables that accept the values of the arguments.
These variables are called the formal parameters of the
function.
Formal parameters behave like other local variables
inside the function and are created upon entry into the
function and destroyed upon exit.
1
Function
declaration
return_type function_name (argument list);
2
Function call function_name (argument_list)
3
Function
definition
return_type function_name (argument list)
{
function body;
}
While calling a function, there are two ways in which
arguments can be passed to a function −
Call by value This method copies the actual value of an
argument into the formal parameter of the function. In
this case, changes made to the parameter inside the
function have no effect on the argument.
Call by reference This method copies the address of an
argument into the formal parameter. Inside the function,
the address is used to access the actual argument used in
the call. This means that changes made to the parameter
affect the argument.
Categories of User defined functions
A function may or may not accept any argument. It may or
may not return any value.
Based on these facts, There are four different aspects of
function calls.
1. Function without arguments and without return value
2. Function without arguments and with return value
3. Function with arguments and without return value
4. Function with arguments and with return value
Example for Function without argument and return value
Example 1
#include<stdio.h>
void printmsg();
void main ()
{
printf("Hello ");
printmsg();
}
void printmsg()
{
printf(“Welcome");
}
#include<stdio.h>
void sum();
void main()
{
printf("nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Example for Function without argument and
with return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("nThe sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Example for Function with argument and without return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b;
printf("nGoing to calculate the sum of two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("nThe sum is %d",a+b);
}
Example for Function with argument and with return value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("nGoing to calculate the sum of two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Call by value and Call by reference in C
◦ There are two methods to pass the data into the function in C
language, i.e., call by value and call by reference.
Call by value in C
In call by value method, the value of the actual parameters is copied
into the formal parameters. In other words, we can say that the value
of the variable is used in the function call in the call by value method.
In call by value method, we can not modify the value of the actual
parameter by the formal parameter.
In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the
formal parameter.
The actual parameter is the argument which is used in the function
call whereas formal parameter is the argument which is used in the
function definition.
Call by value in C -cannot modify the value of the actual
parameter by the formal parameter
#include<stdio.h>
void change(int num)
{
printf("Before adding value inside function num=%d n",num);
num=num+100;
printf("After adding value inside function num=%d n", num);
}
void main()
{
int x=100;
printf("Before function call x=%d n", x);
change(x);//passing value in function
printf("After function call x=%d n", x);
// x=100 , no modification in x value
}
#include<stdio.h>
void change(int num)
{
printf("Before adding value inside function num=%d n",num);
num=num+100;
printf("After adding value inside function num=%d n", num);
}
void main()
{
int x=100;
printf("Before function call x=%d n", x);
change(x);//passing value in function
printf("After function call x=%d n", x);
}
Call by Value Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %dn",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %dn",a, b);
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %dn",a,b);
// Formal parameters, a = 20, b = 10
}
Call by reference in C
In call by reference, the address of the variable is passed into the
function call as the actual parameter.
The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is
passed.
In call by reference, the memory allocation is similar for both formal
parameters and actual parameters.
All the operations in the function are performed on the value stored
at the address of the actual parameters, and the modified value gets
stored at the same address.
#include<stdio.h>
void change(int *num)
{
printf("Before adding value inside function num=%d n",*num);
(*num) += 100;
printf("After adding value inside function num=%d n", *num);
}
int main()
{
int x=100;
printf("Before function call x=%d n", x);
change(&x); //passing reference in function
printf("After function call x=%d n", x);
return 0;
}
Call by reference Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %dn",a,b);
// printing the value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %dn",a,b);
// The values of actual parameters do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %dn",*a,*b);
// Formal parameters, a = 20, b = 10
}
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf

Contenu connexe

Tendances

Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cSowmya Jyothi
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and StringTasnima Hamid
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in CRAJ KUMAR
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
Strings in c
Strings in cStrings in c
Strings in cvampugani
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c languageTanmay Modi
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c languagetanmaymodi4
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements Tarun Sharma
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programmingprogramming9
 
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptxC-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptxSKUP1
 

Tendances (20)

Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in c
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
 
Enums in c
Enums in cEnums in c
Enums in c
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
C functions
C functionsC functions
C functions
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Strings in c
Strings in cStrings in c
Strings in c
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
C Token’s
C Token’sC Token’s
C Token’s
 
Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Storage class
Storage classStorage class
Storage class
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptxC-Programming  C LIBRARIES AND USER DEFINED LIBRARIES.pptx
C-Programming C LIBRARIES AND USER DEFINED LIBRARIES.pptx
 
Strings
StringsStrings
Strings
 

Similaire à USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf

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

Functions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiFunctions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothi
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
C functions list
C functions listC functions list
C functions list
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
Functions
FunctionsFunctions
Functions
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
 
Function
FunctionFunction
Function
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
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
 

Dernier

Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 

Dernier (20)

Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 

USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf

  • 1. USER DEFINED FUNCTIONS REFERENCE: PROGRAMMING IN C BY BALAGURUSWAMY MRS. SOWMYAJYOTHI, SDMCBM,MANGALORE
  • 2. User defined functions : C functions can be classified into two categories, namely, library functions and user-defined functions. The functions which are developed by user at the time of writing a program are called user defined functions. So, user-defined functions are functions created and developed by user.
  • 3. Here function01( ) is an user defined function. main( ) { ======= ======= function01( ); ======= } function01( ) { ======== ======== }
  • 4. Necessity of user defined functions : When not using user defined functions, for a large program the tasks of debugging, compiling etc. may become difficult in general. That’s why user defined functions are extremely necessary for complex programs.
  • 5. The necessities or advantages are as follows, 01. It facilitates top-down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later. 02. The length of a source program can be reduced by using functions at appropriate places. 03. It is easy to locate and isolate a faulty function for further investigations. 04. A function may be used by many other programs. This means that a C programmer can build on what others have already done, instead of starting all over again from scratch.
  • 6. Multifunction program : A function is a self-contained block of code that performs a particular task. Once a function has been designed and packed, it can be treated as a ‘black box’ that takes some data from the main program and returns a value. Thus a program, which has been written using a number of functions, is treated as a multifunction program.
  • 7. Elements of user defined functions : In order to make use of a user-defined function, we need to establish three elements that are related to functions. 1. Function definition 2. Function call 3. Function declaration
  • 8. The function definition is an independent program module that is specially written to implement to the requirements of the function. In order to use the function we need to invoke it at a required place in the program. This is known as the function call. The program or a function that has called a function is referred to as the calling function or calling program. The calling program should declare any function that is to be used later in the program. This is known as the function declaration.
  • 9.
  • 10. 1. Function name 2. Function type 3. List of parameters 4. Local variable declarations 5. Function statements 6. A return statement All the six elements are grouped into two parts; namely, •Function header (First three elements) •Function body (Second three elements) Function Definition : The function definition is an independent program module that is specially written to implement to the requirements of the function. A function definition, also known as function implementation shall include the following elements
  • 11. Function Header The function header consists of three parts; function type, function name and list of parameter. (a) Function Type The function type specifies the type of value (like float or double) that the function is expected to return to the calling program. If the return type is not explicitly specified, C will assume that it is an integer type. (b) Function name The function name is any valid C identifier and therefore must follow the same rules of formation as other variable names in C. The name should be appropriate to the task performed by the function. (c) List of Parameter The parameter list declares the variables that will receive the data sent by the calling program. They serve as input data to the function to carry out the specified task.
  • 12. Example : float mul (float x, float y) { …. } int sum (int a, int b) { …. }
  • 13. Function body The function body is enclosed in braces, contains three parts, in the order given below: 1. Local variable declaration : Local variable declarations are statements that specify the variables needed by the function. 2. Function Statements : Function statements are statements that perform the task of the function. 3. Return Statements : A return statement is a statement that returns the value evaluated by the function to the calling program. If a function does not return any value, one can omit the return statement.
  • 14. Function call : In order to use functions user need to invoke it at a required place in the program. This is known as the function call. A function can be called by simply using the function name followed by a list of actual parameters, if any, enclosed in parentheses.
  • 15. Example : Here in the main() program the mul(10,5) function has been called. main() { int y; y=mul(10,5); /*Function Call* printf(“%dn”,y); }
  • 16. Function declaration : The program or a function that called a function is referred to as the calling function or calling program. The calling program should declare any function that is to be used later in the program. This is known as the function declaration. A function declaration consists of four parts. They are, 1. Function type 2. Function name 3. Parameter list 4. Terminating semicolon They are coded in the following format : function_type function_name(parameter list);
  • 17. 1. The parameter list must be separated by commas. 2. If the function has no formal parameters, the list is written as void. 3. The return type is optional when the function returns int type data. 4. When the declared type does not match the types in the function definition compiler will produce an error.
  • 18. Parameter list : The parameter list contains declaration of variables separated by commas and surrounded by parentheses. float quadratic (int a, int b, int c) {…. }
  • 19. Prototype : The declaration of a function is known as function prototype. The function prototype is coded in the following format, Function_type function_name(parameter list);
  • 20. Nesting of functions : In C, each function can contain one or more than one function in it. There is no limit as to how deeply functions can be nested. Consider the following example, main() { function1(); } function1() { function2(); } function2() { ...............; } In the above example, The main() function contains function01(), the function01() contains function02 and so on. This is nesting of functions.
  • 21. Program to find sum of 2 numbers using function #include<stdio.h> #include<conio.h> int sum(int a, int b); //function declaration void main() { int a,b,c; clrscr(); printf(“Enter 2 numbers:”); scanf(“%d%d”,&a,&b); c=sum(a,b); //function call printf(“nSum=%d”,c); getch(); //function definition int sum(int a, int b) { int c=0; c=a+b; return c; }
  • 22. Recursion: Recursive function is a function that calls itself. When a function calls another function and that second function calls the third function then this kind of a function is called nesting of functions. But a recursive function is the function that calls itself repeatedly. main() { printf(“this is an example of recursive function”); main(); } When this program is executed. The line is printed repeatedly and indefinitely. We might have to abruptly terminate the execution.
  • 23. Factorial Function a) If N = 0, then N! = 1. b) If N > 0, then N! = N*(N-1)! Example: 5! = 5 * 4! = 5 * 4 * 3! = 5 * 4 * 3 * 2! = 5 * 4 * 3 * 2 * 1! = 5 * 4 * 3 * 2 * 1* 0! = 5 * 4 * 3 * 2 * 1 * 1
  • 24. Program to display factorial of a number using recursive function #include<stdio.h> #include<conio.h> long fact(int n); void main() { int n; long int f; clrscr(); printf(“enter a number”); scanf(“%d”, &n); f=fact(n); printf(“nFactorial =%ld”),f); } long fact(int n) { if (n==0) return 1; else return (n*fact(n-1)); }
  • 25.
  • 26. i=1 n=1 f=n*fact(n-1) 1* fact(1-1) 1* fact(0) = 1*1=1 i=3 f=3*fact(3-1) =3*fact(2) =3*2*fact(1-1) =3*2*fact(0) =3*2*1 =6
  • 27. ◦n=153 r= 3 5 1 STEP 1: arm=0 r=153%10=3 arm=0+(3*3*3)=27 n=153/10=15 STEP 2: r=15%10=5 arm=27+(5*5*5)=27+125=152 n=15/10=1 STEP 3: r=1%10=1 while(n!=0) r=n%10 arm=arm+(r*r*r) n=n/10 arm=152+(1*1*1)=153
  • 28. The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... ... Fibonacci Series is a pattern of numbers where each number is the result of addition of the previous two consecutive numbers . First 2 numbers start with 0 and 1. The third numbers in the sequence is 0+1=1. The 4th number is the addition of 2nd and 3rd number i.e. 1+1=2 and so on. The next number is found by adding up the two numbers before it: the 2 is found by adding the two numbers before it (1+1), the 3 is found by adding the two numbers before it (1+2), the 5 is (2+3), and so on!
  • 29. f1 f2 f3 f1 f2 f3 { f3 = f1 + f2; printf(" %d", f3); f1 = f2; f2 = f3; }
  • 30.
  • 31. How to reverse a number mathematically. Step 1 — Isolate the last digit(rem) in number. rem = number % 10 The modulo operator (%) returns the remainder of a divison. Step 2 — Append lastDigit(rem) to reverse. reverse = (reverse * 10) + rem Step 3-Remove last digit from number. number = number / 10.
  • 32. Function Arguments If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
  • 33. 1 Function declaration return_type function_name (argument list); 2 Function call function_name (argument_list) 3 Function definition return_type function_name (argument list) { function body; }
  • 34. While calling a function, there are two ways in which arguments can be passed to a function − Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by reference This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
  • 35. Categories of User defined functions A function may or may not accept any argument. It may or may not return any value. Based on these facts, There are four different aspects of function calls. 1. Function without arguments and without return value 2. Function without arguments and with return value 3. Function with arguments and without return value 4. Function with arguments and with return value
  • 36. Example for Function without argument and return value Example 1 #include<stdio.h> void printmsg(); void main () { printf("Hello "); printmsg(); } void printmsg() { printf(“Welcome"); }
  • 37. #include<stdio.h> void sum(); void main() { printf("nGoing to calculate the sum of two numbers:"); sum(); } void sum() { int a,b; printf("nEnter two numbers"); scanf("%d %d",&a,&b); printf("The sum is %d",a+b); }
  • 38. Example for Function without argument and with return value #include<stdio.h> int sum(); void main() { int result; printf("nThe sum of two numbers:"); result = sum(); printf("%d",result); } int sum() { int a,b; printf("nEnter two numbers"); scanf("%d %d",&a,&b); return a+b; }
  • 39. Example for Function with argument and without return value #include<stdio.h> void sum(int, int); void main() { int a,b; printf("nGoing to calculate the sum of two numbers:"); printf("nEnter two numbers:"); scanf("%d %d",&a,&b); sum(a,b); } void sum(int a, int b) { printf("nThe sum is %d",a+b); }
  • 40. Example for Function with argument and with return value #include<stdio.h> int sum(int, int); void main() { int a,b,result; printf("nGoing to calculate the sum of two numbers:"); printf("nEnter two numbers:"); scanf("%d %d",&a,&b); result = sum(a,b); printf("nThe sum is : %d",result); } int sum(int a, int b) { return a+b; }
  • 41. Call by value and Call by reference in C ◦ There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.
  • 42. Call by value in C In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method. In call by value method, we can not modify the value of the actual parameter by the formal parameter. In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter. The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.
  • 43. Call by value in C -cannot modify the value of the actual parameter by the formal parameter #include<stdio.h> void change(int num) { printf("Before adding value inside function num=%d n",num); num=num+100; printf("After adding value inside function num=%d n", num); } void main() { int x=100; printf("Before function call x=%d n", x); change(x);//passing value in function printf("After function call x=%d n", x); // x=100 , no modification in x value }
  • 44. #include<stdio.h> void change(int num) { printf("Before adding value inside function num=%d n",num); num=num+100; printf("After adding value inside function num=%d n", num); } void main() { int x=100; printf("Before function call x=%d n", x); change(x);//passing value in function printf("After function call x=%d n", x); }
  • 45. Call by Value Example: Swapping the values of the two variables #include <stdio.h> void swap(int , int); //prototype of the function int main() { int a = 10; int b = 20; printf("Before swapping the values in main a = %d, b = %dn",a,b); swap(a,b); printf("After swapping values in main a = %d, b = %dn",a, b); }
  • 46. void swap (int a, int b) { int temp; temp = a; a=b; b=temp; printf("After swapping values in function a = %d, b = %dn",a,b); // Formal parameters, a = 20, b = 10 }
  • 47. Call by reference in C In call by reference, the address of the variable is passed into the function call as the actual parameter. The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed. In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.
  • 48. #include<stdio.h> void change(int *num) { printf("Before adding value inside function num=%d n",*num); (*num) += 100; printf("After adding value inside function num=%d n", *num); } int main() { int x=100; printf("Before function call x=%d n", x); change(&x); //passing reference in function printf("After function call x=%d n", x); return 0; }
  • 49. Call by reference Example: Swapping the values of the two variables #include <stdio.h> void swap(int *, int *); //prototype of the function int main() { int a = 10; int b = 20; printf("Before swapping the values in main a = %d, b = %dn",a,b); // printing the value of a and b in main swap(&a,&b); printf("After swapping values in main a = %d, b = %dn",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20 }
  • 50. void swap (int *a, int *b) { int temp; temp = *a; *a=*b; *b=temp; printf("After swapping values in function a = %d, b = %dn",*a,*b); // Formal parameters, a = 20, b = 10 }