SlideShare a Scribd company logo
1 of 57
User Defined Function in C
Functions
• Functions
– Modularize a program
– All variables declared inside functions are local variables
• Known only in function defined
– Parameters
• Communicate information between functions
• Local variables
• 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
Function Definition
• Using functions we can structure our programs in a more
modular way, accessing all the potential that structured
programming can offer to us in C.
A function is a group of statements that is executed when it is
called from some point of the program. The following is its
format:
type name ( parameter1, parameter2, ...)
{
statements
}
where:
• type is the data type specifier of the data returned by the function.
• name is the identifier by which it will be possible to call the function.
• parameters (as many as needed): Each parameter consists of a data
type specifier followed by an identifier, like any regular variable
declaration (for example: int x) and which acts within the function as
a regular local variable. They allow to pass arguments to the function
when it is called. The different parameters are separated by commas.
• statements is the function's body. It is a block of statements
surrounded by braces { }.
Function Definition
Functions - Definition Structure
• Function 'header'
– Return data type
(if any)
– Name
• Descriptive
– Arguments (or parameter
list)
• Notice: data type and name
• Statements
– Variable declaration
– Operations
– Return value (if any)
type function_name (type arg1, type arg2 )
{
statements;
}
double product(double x, double y)
{
double result;
result = x * y;
return result;
}
A function that calculates the product of two numbers
User Defined Function involve following step
• Function prototype/ Declaration
• Function Call
• Function initialization.
• Function prototype
– Like a variable declaration
• Tells compiler that the function will be defined later
• Function definition
– This potion involve the actual code that will be executed.
– Note, NO semicolon
• Function return
– return statement terminates execution of the current function
– Control returns to the calling function
– if return expression;
• then value of expression is returned as the value of the
function call
• Only one value can be returned this way
• Function call
– Should be inside main() function
– Control transferred to the function code
– Code in function definition is executed
Functions - Example
• Function prototype
• Function definition
• Function return
• Function call
#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
ans = product(var1, var2);
printf("var1 = %.2fn"
"var2 = %.2fn",var1,var2);
printf("var1*var2 = %gn", ans);
}
/* function definition */
double product(double x, double y)
{
double result;
result = x * y;
return result;
}
Example
• Write a function
named 'sum'
– sums two integers
– returns the sum
Steps
1.Function header
• return data type
• function name
• argument list with data types
2.Statements in function definition
• variable declaration
• operations
• return value
Function - sum()
int sum_int(int x, int y)
{
int result;
result = x + y;
return result;
}
 C program does not execute the statements in a
function until the function is called.
 When it is called, the program can send information
to the function in the form of one or more
arguments although it is not a mandatory.
 Argument is a program data needed by the function
to perform its task.
 When the function finished processing, program
returns to the same location which called the
function.
How the Used defined Function works ?
function declaration
Syntax of function declaration
return_type function_name( parameter_list );
Return type - Return type defines the data type of value returned by the
function. A function does some calculation and may return a resultant
value. So that the result of one function can be used by another function.
You must mention return type as void if your function does not return any
value.
Function name - Function name is a valid C identifier that uniquely identifies
the function. Which must follow identifier naming rules while naming a
function.
Parameter list - A function may accept input. Parameter list contains input
type and variable name given to the function. Multiple inputs are
separated using comma ,
An example of function prototype,
– long cube(long);
 Function prototype provides the C compiler the name and
arguments of the functions and must appear before the function is
used or defined.
 From the previous prototype example, 'we' know the function is
named cube, it requires a variable of the type long, and it will
return a value of type long.
 A function prototype need not exactly match the function header.
 The optional parameter names can be different, as long as they are
the same data type, number and in the same order.
 But, having the name identical for prototype and the function
header makes source code easier to understand.
C FUNCTIONS
 Normally placed before the start of main() but must be
before the function definition.
 Provides the compiler with the description of a function that
will be defined at a later point in the program.
 Includes a return type which indicates the type of variable that
the function will return.
 Also contains the variable types of the arguments that will be
passed to the function.
 A prototype should always end with a semicolon ( ; ).
C FUNCTIONS
Is the actual function body, which contains the code that will
be executed. Function definition can be placed anywhere in
the program, below its declaration.
However, I recommend you to put all declarations
below main()function
Function Definition
int cube(int fCubeSide)
{
int fCubeVol;
fCubeVol = fCubeSide * fCubeSide * fCubeSide;
return fCubeVol;
}
Syntax of function definition
return_type function_name(parameter
list) { // Function body }
 First line of a function definition is called the function header,
should be identical to the function prototype/ decleration,
except the semicolon.
 Function body, containing the statements, which the function
will perform, should begin with an opening brace and end with a
closing brace.
 If the function returns data type is anything other than void
(nothing to be returned),
a return statement should be included, returning a value
matching the return data type (int in this case).
C FUNCTIONS
 The first line of every function definition is called function
header. It has 3 components, as shown below,
The Function header
Function name - Can have any name as long as the rules for C variable
names are followed and must be unique.
Parameter list - Many functions use arguments, the value passed to the
function when it is called. A function needs to know the data type of
each argument. Argument type is provided in the function header by
the parameter list. Parameter list acts as a placeholder.
The Function header
Function return type - Specifies the data type that the function should
returns to the caller program. Can be any of C data types: char,
float, int, long, double, pointers etc. If there is no return value,
specify a return type of void. For example,
int calculate_yield(…) // returns an int type
float mark(…) // returns a float type
void calculate_interest(…) // returns nothing
 For each argument that is passed to the function, the parameter
list must contain one entry, which specifies the type and the
name.
 For example,
void myfunction(int x, float y, char z)
int ourfunction(long size)
 The first line specifies a function with three arguments:
type int named x, type float named y and type char named z.
 Some functions take no arguments, so the parameter list should
be void or empty such as,
long thefunction(void)
void testfunct(void)
int zerofunct()
Function Argument
Function calling
The most important part of function is its calling. Calling of a
function in general is execution of the function. It transfers
program control from driver (current) function to called
function. We can optionally pass input to the calling function.
Syntax of function call
function_name( parameter_list );
Function name - Name of the function to execute.
Parameter list - Comma separated input given to the function.
Parameter list must match type and order mentioned in
function declaration. Leave parameter list as blank if function
does not accept any input.
For the first function call:
Then, the second function call:
 Each time a function is called, the different arguments are passed to
the function’s parameter.
 z = half_of(y) and z = half_of(x), each send a different
argument to half_of() through the k parameter.
 The value of x and y are passed (copied) into the parameter k of
half_of().
 Same effect as copying the values from x to k, and then y to k.
C FUNCTIONS
 Enclosed in curly braces, immediately follows the function header.
 When a function is called execution begins at the start of the function
body and terminates (returns to the calling program) when a
return statement is encountered or when execution reaches the
closing braces (}).
 Variable declaration can be made within the body of a function,
Which are called local variables.
 Local variables are the variables apply only to that particular function,
are distinct from other variables of the same name (if any) declared
elsewhere in the program outside the function.
 It is declared, initialized and use like any other variable.
The Function Body
 A function may or may not return a value.
 If function does not return a value, then the function return
type is said to be of type void.
 To return a value from a function, use return keyword,
followed by C expression.
 The value is passed back to the caller.
 The return value must match the return data type.
 A function can contain multiple return statements.
Returning a Value
#include <stdio.h>
int add(int num1, int num2); // Function Declare
int main()
{
int n1, n2, su;
printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
su = add(n1, n2); //Function Call
printf("Sum = %d", su);
return 0;
}
int add(int num1, int num2) // Function define
{
int s = num1 + num2;
return s;
}
Types of functions in C
• No return no argument
• No return but arguments
• Return but no argument
• Return with arguments
Function with no return no argument
Function with no return no argument, neither returns a
value nor accepts any argument. This type of function
does not communicate with the caller function. It
works as an independent working block. Use this type
of function when you have some task to do
independent of the caller function.
Note: You must add void as function return type for this
type of function.
Syntax to define function with no return no argument
void function_name()
{ // Function body }
#include <stdio.h>
void generateFibo();
int main()
{
generateFibo();
return 0;
}
void generateFibo()
{
int a, b, c, i, terms;
printf("Enter number of terms:
");
scanf("%d", &terms);
a = 0;
b = 1;
c = 0;
printf("Fibonacc terms: n");
for(i=1; i<=terms; i++)
{
printf(“ %d, ", c);
a = b;
b = c;
c = a + b;
}
}
Write a C function to input a number and generate Fibonacci series.
Function with no return but with arguments
Function with no return but with arguments, does not
return a value but accepts arguments as input. For this
type of function you must define function return type
as void.
Syntax to define function with no return but with
arguments
void function_name(type arg1, type arg2, ...)
{ // Function body }
Where type is a valid C data type and argN is a valid C
identifier.
#include <stdio.h>
void printNatural(int, int);
void main()
{
int s, e;
printf("Enter lower range to
print natural numbers: ");
scanf("%d", &s);
printf("Enter upper limit to
print natural numbers: ");
scanf("%d", &e);
printNatural(s, e);
}
void printNatural(int x ,int y)
{
printf("Natural numbers from
%d to %d are: n", x, y);
while(x <= y)
{
printf("%d, ", x);
x++;
}
}
Write a C function to accept two arguments start and end.
Print all natural numbers between start to end.
Function with return but no arguments
Function with return but no arguments, returns a value
but does not accept any argument. This type of
function communicates with the caller function by
returning value back to the caller.
Syntax to define function with return but no arguments
return_type function_name()
{ // Function body return some_value; }
Where return_type and some_value must be declared
with same type.
Function with return and arguments
Function with return and arguments, returns a value and
may accept arguments. Since the function accepts input
and returns a result to the caller, hence this type of
functions are most used and best for modular
programming.
Syntax to define function with return and arguments
return_type function_name(type arg1, type arg2, ...)
{ // Function body
return some_variable; }
#include <stdio.h>
int evenOdd(int num);
int main()
{
int num, x;
printf("Enter a number: ");
scanf("%d", &num);
x = evenOdd(num);
if(x == 0)
printf("The given number is
EVEN.");
else
printf("The given number is ODD.");
return 0;
}
int evenOdd(int num)
{
if(num % 2 == 0)
return 0;
else
return 1;
}
Write a C program to input a number and check the input is even or odd.
Define a function that accepts the number and return a value 0 or 1.
Return 0 if argument is even, otherwise return 1.
Do not pass argument Do pass arguments
No return
void main(void)
{
TestFunct();
...
}
void TestFunct(void)
{
// receive nothing
// and nothing to be
// returned
}
void main(void)
{
TestFunct(123);
...
}
void TestFunct(int i)
{
// receive something and
// the received/passed
// value just
// used here. Nothing
// to be returned.
}
With a return
void main(void)
{
x = TestFunct();
...
}
int TestFunct(void)
{
// received/passed
// nothing but need to
// return something
return 123;
}
void main(void)
{
x = TestFunct(123);
...
}
int TestFunct(int x)
{
// received/passed something
// and need to return something
return (x + x);
}
C FUNCTIONS
Recursion
• Recursive functions
– Functions that call themselves
– 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
Recursion
Recursion is the process of repeating items in a self-similar
way.
In programming languages, if a program allows you to call a
function inside the same function, then it is called a recursive
call of the function.
Return_type recursion( )
{
recursion(); /* function calls itself */
}
int main( )
{
recursion();
}
Recursion
• 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;
Example Using Recursion: The
Fibonacci Series
• 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 )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1) +
fibonacci( n – 2 );
}
Things to consider while using recursion
#include <stdio.h>
void print(int);
int main()
{
print(5);
return 0;
}
void print(int n)
{
printf("%d ", n);
if(n <= 1)
{
return;
}
print(n - 1);
}
The C programming language supports recursion, i.e., a function to
call itself. But while using recursion, programmers need to be
careful to define an exit condition from the function, otherwise it
will go into an infinite loop.
Factorial using Recursion
#include <stdio.h>
int factorial(int);
void main()
{
int n ;
Printf(“enter the no”);
Scanf(“%d”,&n);
printf("Factorial of %d is
%dn", n, factorial(n));
}
int factorial(int i)
{
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
#include <stdio.h>
int sum(int );
void main()
{
int num, s;
printf("Enter any number : ");
scanf("%d", &num);
s = sum(num);
printf("Sum of digits of %d =
%d", num, s);
}
int sum(int n)
{
if(n == 0)
return 0;
return ((n % 10) + sum(n/10));
}
Program to find sum of digits using recursion
Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance
– Choice between performance (iteration) and good
software engineering (recursion)
Basically, there are two ways how we can pass something to
function parameters,
1. Passing by value.
2. Passing by reference using array and pointer.
FUNCTIONS Call
Function Call
Actual parameters: The parameters that appear in
function calls.
Formal parameters: The parameters that appear in
function declarations.
For example: We have a function declaration like this:
int sum(int a, int b);The a and b parameters are formal
parameters.
We are calling the function like this:
int s = sum(10, 20); //Here 10 and 20 are actual
parameters
int s = sum(n1, n2); //Here n1 and n2 are actual
parameters
Function – Call by value method
In the call by value method the actual arguments are
copied to the formal arguments, hence any operation
performed by function on arguments doesn’t affect
actual parameters.
Function – Call by reference method
Unlike call by value, in this method, address of actual
arguments (or parameters) is passed to the formal
parameters, which means any operation performed on
formal parameters affects the value of actual
parameters.
Function call by value
When we pass the actual parameters while
calling a function then this is known as
function call by value.
In this case the values of actual parameters
are copied to the formal parameters. Thus
operations performed on the formal
parameters don’t reflect in the actual
parameters.
CALL BY VALUE
Until now, in all the functions we have seen, the
arguments passed to the functions have been passed by
value. This means that when calling a function with
parameters, what we have passed to the function were
copies of their values but never the variables themselves.
For example,
int x=5, y=3, z;
z = addition ( x , y );
What we did in this case was to call to function addition
passing the values of x and y, i.e. 5 and 3 respectively, but
not the variables x and y themselves.
What we did in this case was to call to function
addition passing the values of x and y, i.e. 5 and 3
respectively, but not the variables x and y themselves.
This way, when the function addition is called, the value of
its local variables a and b become 5 and 3 respectively.
Any modification to either a or b within the function addition
will not have any effect in the values of x and y outside it,
because variables x and y were not themselves passed to the
function, but only copies of their values called.
#include <stdio.h>
void swapnum( int , int);
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping:
%d, %d", num1, num2);
swapnum(num1, num2);
printf("nAfter swapping: %d,
%d", num1, num2);
}
void swapnum( int var1, int
var2 )
{
int tempnum ;
tempnum = var1 ;
var1 = var2 ;
var2 = tempnum ;
Output:
Before swapping: 35,
45
After swapping: 35,
45
Why variables remain unchanged even after
the swap?
The reason is same – function is called by
value for num1 , num2. So actually var1 and
var2 gets swapped (not num1 & num2). As in
call by value actual parameters are just copied
into the formal parameters.
CALL BY REFERENCE
When we call a function by passing the addresses of
actual parameters then this way of calling the function
is known as call by reference.
In call by reference, the operation performed on formal
parameters, affects the value of actual parameters
because all the operations performed on the value
stored in the address of actual parameters.
#include <stdio.h>
void increment(int *var)
{
*var = *var+1;
}
void main( )
{
int num=20;
// passing the address of
variable num
increment(&num);
printf("Value of num is:
%d", num);
}
Output:
Value of num is: 21
CALL BY REFERENCE
In this function call the declaration of duplicate the
type of each parameter was followed by an ampersand sign
(&). This ampersand is what specifies that their
corresponding arguments are to be passed by reference
instead of by value.
When a variable is passed by reference we are
not passing a copy of its value, but we are somehow
passing the variable itself to the function and any
modification that we do to the local variables will have an
effect in their counterpart variables passed as
arguments in the call to the function.
CALL BY REFERENCE
CALL BY REFERENCE
// passing parameters by reference
#include <stdio.h>
void duplicate (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
printf(“"x= %d y= %d z= %d”, x,y,z) ;
return 0;
}
CALL BY REFERENCE
To explain it in another way, we associate a, b and c
with the arguments passed on the function call (x, y and
z) and any change that we do on a within the function will
affect the value of x outside it. Any change that we do on
b will affect y, and the same with c and z.
That is why our program's output, that shows the values
stored in x, y and z after the call to duplicate, shows the
values of all the three variables to be doubled.
#include <stdio.h>
void swap ( int *, int *);
void main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping:num1
is %d num2 is %d", num1,
num2);
swap( &num1, &num2 );
printf("nAfter
swapping:num1 is %d num2
is %d", num1, num2);
}
void swap( int *var1, int *var2 )
{
int temp;
temp= *var1 ;
*var1 = *var2 ;
*var2 = temp;
}
Output:
Before swapping:num1 is 35 num2 is 45
After swapping: num1 is 45 num2 is 35
Here we are swapping the numbers using call
by reference.
As you can see the values of the variables
have been changed after calling the swap( )
function because the swap happened on the
addresses of the variables num1 and num2.

More Related Content

Similar to User defined function in C.pptx

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
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfRITHIKA R S
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Functions
FunctionsFunctions
Functionszeeshan841
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdfNirmalaShinde3
 
C programming language working with functions 1
C programming language working with functions 1C programming language working with functions 1
C programming language working with functions 1Jeevan Raj
 
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
 
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
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptxMehul Desai
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 

Similar to User defined function in C.pptx (20)

arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
4. function
4. function4. function
4. function
 
C functions
C functionsC functions
C functions
 
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)
 
Functions
FunctionsFunctions
Functions
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions
FunctionsFunctions
Functions
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Functions
Functions Functions
Functions
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
 
C programming language working with functions 1
C programming language working with functions 1C programming language working with functions 1
C programming language working with functions 1
 
C functions list
C functions listC functions list
C functions list
 
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
 
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
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Recently uploaded

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
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
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
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
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
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
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 

Recently uploaded (20)

Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
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
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
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 🔝✔️✔️
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
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
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 

User defined function in C.pptx

  • 2. Functions • Functions – Modularize a program – All variables declared inside functions are local variables • Known only in function defined – Parameters • Communicate information between functions • Local variables • 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
  • 3. Function Definition • Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C. A function is a group of statements that is executed when it is called from some point of the program. The following is its format:
  • 4. type name ( parameter1, parameter2, ...) { statements } where: • type is the data type specifier of the data returned by the function. • name is the identifier by which it will be possible to call the function. • parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas. • statements is the function's body. It is a block of statements surrounded by braces { }. Function Definition
  • 5. Functions - Definition Structure • Function 'header' – Return data type (if any) – Name • Descriptive – Arguments (or parameter list) • Notice: data type and name • Statements – Variable declaration – Operations – Return value (if any) type function_name (type arg1, type arg2 ) { statements; } double product(double x, double y) { double result; result = x * y; return result; } A function that calculates the product of two numbers
  • 6. User Defined Function involve following step • Function prototype/ Declaration • Function Call • Function initialization.
  • 7. • Function prototype – Like a variable declaration • Tells compiler that the function will be defined later • Function definition – This potion involve the actual code that will be executed. – Note, NO semicolon • Function return – return statement terminates execution of the current function – Control returns to the calling function – if return expression; • then value of expression is returned as the value of the function call • Only one value can be returned this way • Function call – Should be inside main() function – Control transferred to the function code – Code in function definition is executed
  • 8. Functions - Example • Function prototype • Function definition • Function return • Function call #include <stdio.h> /* function prototype */ double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2fn" "var2 = %.2fn",var1,var2); printf("var1*var2 = %gn", ans); } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; }
  • 9. Example • Write a function named 'sum' – sums two integers – returns the sum Steps 1.Function header • return data type • function name • argument list with data types 2.Statements in function definition • variable declaration • operations • return value
  • 10. Function - sum() int sum_int(int x, int y) { int result; result = x + y; return result; }
  • 11.  C program does not execute the statements in a function until the function is called.  When it is called, the program can send information to the function in the form of one or more arguments although it is not a mandatory.  Argument is a program data needed by the function to perform its task.  When the function finished processing, program returns to the same location which called the function. How the Used defined Function works ?
  • 12. function declaration Syntax of function declaration return_type function_name( parameter_list ); Return type - Return type defines the data type of value returned by the function. A function does some calculation and may return a resultant value. So that the result of one function can be used by another function. You must mention return type as void if your function does not return any value. Function name - Function name is a valid C identifier that uniquely identifies the function. Which must follow identifier naming rules while naming a function. Parameter list - A function may accept input. Parameter list contains input type and variable name given to the function. Multiple inputs are separated using comma , An example of function prototype, – long cube(long);
  • 13.  Function prototype provides the C compiler the name and arguments of the functions and must appear before the function is used or defined.  From the previous prototype example, 'we' know the function is named cube, it requires a variable of the type long, and it will return a value of type long.  A function prototype need not exactly match the function header.  The optional parameter names can be different, as long as they are the same data type, number and in the same order.  But, having the name identical for prototype and the function header makes source code easier to understand. C FUNCTIONS
  • 14.  Normally placed before the start of main() but must be before the function definition.  Provides the compiler with the description of a function that will be defined at a later point in the program.  Includes a return type which indicates the type of variable that the function will return.  Also contains the variable types of the arguments that will be passed to the function.  A prototype should always end with a semicolon ( ; ). C FUNCTIONS
  • 15. Is the actual function body, which contains the code that will be executed. Function definition can be placed anywhere in the program, below its declaration. However, I recommend you to put all declarations below main()function Function Definition int cube(int fCubeSide) { int fCubeVol; fCubeVol = fCubeSide * fCubeSide * fCubeSide; return fCubeVol; } Syntax of function definition return_type function_name(parameter list) { // Function body }
  • 16.  First line of a function definition is called the function header, should be identical to the function prototype/ decleration, except the semicolon.  Function body, containing the statements, which the function will perform, should begin with an opening brace and end with a closing brace.  If the function returns data type is anything other than void (nothing to be returned), a return statement should be included, returning a value matching the return data type (int in this case). C FUNCTIONS
  • 17.  The first line of every function definition is called function header. It has 3 components, as shown below, The Function header
  • 18. Function name - Can have any name as long as the rules for C variable names are followed and must be unique. Parameter list - Many functions use arguments, the value passed to the function when it is called. A function needs to know the data type of each argument. Argument type is provided in the function header by the parameter list. Parameter list acts as a placeholder. The Function header Function return type - Specifies the data type that the function should returns to the caller program. Can be any of C data types: char, float, int, long, double, pointers etc. If there is no return value, specify a return type of void. For example, int calculate_yield(…) // returns an int type float mark(…) // returns a float type void calculate_interest(…) // returns nothing
  • 19.  For each argument that is passed to the function, the parameter list must contain one entry, which specifies the type and the name.  For example, void myfunction(int x, float y, char z) int ourfunction(long size)  The first line specifies a function with three arguments: type int named x, type float named y and type char named z.  Some functions take no arguments, so the parameter list should be void or empty such as, long thefunction(void) void testfunct(void) int zerofunct() Function Argument
  • 20. Function calling The most important part of function is its calling. Calling of a function in general is execution of the function. It transfers program control from driver (current) function to called function. We can optionally pass input to the calling function. Syntax of function call function_name( parameter_list ); Function name - Name of the function to execute. Parameter list - Comma separated input given to the function. Parameter list must match type and order mentioned in function declaration. Leave parameter list as blank if function does not accept any input.
  • 21. For the first function call: Then, the second function call:  Each time a function is called, the different arguments are passed to the function’s parameter.  z = half_of(y) and z = half_of(x), each send a different argument to half_of() through the k parameter.  The value of x and y are passed (copied) into the parameter k of half_of().  Same effect as copying the values from x to k, and then y to k. C FUNCTIONS
  • 22.  Enclosed in curly braces, immediately follows the function header.  When a function is called execution begins at the start of the function body and terminates (returns to the calling program) when a return statement is encountered or when execution reaches the closing braces (}).  Variable declaration can be made within the body of a function, Which are called local variables.  Local variables are the variables apply only to that particular function, are distinct from other variables of the same name (if any) declared elsewhere in the program outside the function.  It is declared, initialized and use like any other variable. The Function Body
  • 23.  A function may or may not return a value.  If function does not return a value, then the function return type is said to be of type void.  To return a value from a function, use return keyword, followed by C expression.  The value is passed back to the caller.  The return value must match the return data type.  A function can contain multiple return statements. Returning a Value
  • 24. #include <stdio.h> int add(int num1, int num2); // Function Declare int main() { int n1, n2, su; printf("Enter two numbers: "); scanf("%d%d", &n1, &n2); su = add(n1, n2); //Function Call printf("Sum = %d", su); return 0; } int add(int num1, int num2) // Function define { int s = num1 + num2; return s; }
  • 25. Types of functions in C • No return no argument • No return but arguments • Return but no argument • Return with arguments
  • 26. Function with no return no argument Function with no return no argument, neither returns a value nor accepts any argument. This type of function does not communicate with the caller function. It works as an independent working block. Use this type of function when you have some task to do independent of the caller function. Note: You must add void as function return type for this type of function. Syntax to define function with no return no argument void function_name() { // Function body }
  • 27. #include <stdio.h> void generateFibo(); int main() { generateFibo(); return 0; } void generateFibo() { int a, b, c, i, terms; printf("Enter number of terms: "); scanf("%d", &terms); a = 0; b = 1; c = 0; printf("Fibonacc terms: n"); for(i=1; i<=terms; i++) { printf(“ %d, ", c); a = b; b = c; c = a + b; } } Write a C function to input a number and generate Fibonacci series.
  • 28. Function with no return but with arguments Function with no return but with arguments, does not return a value but accepts arguments as input. For this type of function you must define function return type as void. Syntax to define function with no return but with arguments void function_name(type arg1, type arg2, ...) { // Function body } Where type is a valid C data type and argN is a valid C identifier.
  • 29. #include <stdio.h> void printNatural(int, int); void main() { int s, e; printf("Enter lower range to print natural numbers: "); scanf("%d", &s); printf("Enter upper limit to print natural numbers: "); scanf("%d", &e); printNatural(s, e); } void printNatural(int x ,int y) { printf("Natural numbers from %d to %d are: n", x, y); while(x <= y) { printf("%d, ", x); x++; } } Write a C function to accept two arguments start and end. Print all natural numbers between start to end.
  • 30. Function with return but no arguments Function with return but no arguments, returns a value but does not accept any argument. This type of function communicates with the caller function by returning value back to the caller. Syntax to define function with return but no arguments return_type function_name() { // Function body return some_value; } Where return_type and some_value must be declared with same type.
  • 31. Function with return and arguments Function with return and arguments, returns a value and may accept arguments. Since the function accepts input and returns a result to the caller, hence this type of functions are most used and best for modular programming. Syntax to define function with return and arguments return_type function_name(type arg1, type arg2, ...) { // Function body return some_variable; }
  • 32. #include <stdio.h> int evenOdd(int num); int main() { int num, x; printf("Enter a number: "); scanf("%d", &num); x = evenOdd(num); if(x == 0) printf("The given number is EVEN."); else printf("The given number is ODD."); return 0; } int evenOdd(int num) { if(num % 2 == 0) return 0; else return 1; } Write a C program to input a number and check the input is even or odd. Define a function that accepts the number and return a value 0 or 1. Return 0 if argument is even, otherwise return 1.
  • 33. Do not pass argument Do pass arguments No return void main(void) { TestFunct(); ... } void TestFunct(void) { // receive nothing // and nothing to be // returned } void main(void) { TestFunct(123); ... } void TestFunct(int i) { // receive something and // the received/passed // value just // used here. Nothing // to be returned. } With a return void main(void) { x = TestFunct(); ... } int TestFunct(void) { // received/passed // nothing but need to // return something return 123; } void main(void) { x = TestFunct(123); ... } int TestFunct(int x) { // received/passed something // and need to return something return (x + x); } C FUNCTIONS
  • 34. Recursion • Recursive functions – Functions that call themselves – 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
  • 35. Recursion Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. Return_type recursion( ) { recursion(); /* function calls itself */ } int main( ) { recursion(); }
  • 36. Recursion • 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;
  • 37. Example Using Recursion: The Fibonacci Series • 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 ) { if (n == 0 || n == 1) // base case return n; else return fibonacci( n - 1) + fibonacci( n – 2 ); }
  • 38. Things to consider while using recursion #include <stdio.h> void print(int); int main() { print(5); return 0; } void print(int n) { printf("%d ", n); if(n <= 1) { return; } print(n - 1); } The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.
  • 39. Factorial using Recursion #include <stdio.h> int factorial(int); void main() { int n ; Printf(“enter the no”); Scanf(“%d”,&n); printf("Factorial of %d is %dn", n, factorial(n)); } int factorial(int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); }
  • 40. #include <stdio.h> int sum(int ); void main() { int num, s; printf("Enter any number : "); scanf("%d", &num); s = sum(num); printf("Sum of digits of %d = %d", num, s); } int sum(int n) { if(n == 0) return 0; return ((n % 10) + sum(n/10)); } Program to find sum of digits using recursion
  • 41. Recursion vs. Iteration • Repetition – Iteration: explicit loop – Recursion: repeated function calls • Termination – Iteration: loop condition fails – Recursion: base case recognized • Both can have infinite loops • Balance – Choice between performance (iteration) and good software engineering (recursion)
  • 42. Basically, there are two ways how we can pass something to function parameters, 1. Passing by value. 2. Passing by reference using array and pointer. FUNCTIONS Call
  • 43. Function Call Actual parameters: The parameters that appear in function calls. Formal parameters: The parameters that appear in function declarations. For example: We have a function declaration like this: int sum(int a, int b);The a and b parameters are formal parameters. We are calling the function like this: int s = sum(10, 20); //Here 10 and 20 are actual parameters int s = sum(n1, n2); //Here n1 and n2 are actual parameters
  • 44. Function – Call by value method In the call by value method the actual arguments are copied to the formal arguments, hence any operation performed by function on arguments doesn’t affect actual parameters. Function – Call by reference method Unlike call by value, in this method, address of actual arguments (or parameters) is passed to the formal parameters, which means any operation performed on formal parameters affects the value of actual parameters.
  • 45. Function call by value When we pass the actual parameters while calling a function then this is known as function call by value. In this case the values of actual parameters are copied to the formal parameters. Thus operations performed on the formal parameters don’t reflect in the actual parameters.
  • 46. CALL BY VALUE Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This means that when calling a function with parameters, what we have passed to the function were copies of their values but never the variables themselves. For example, int x=5, y=3, z; z = addition ( x , y ); What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.
  • 47. What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves. This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively. Any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values called.
  • 48. #include <stdio.h> void swapnum( int , int); int main( ) { int num1 = 35, num2 = 45 ; printf("Before swapping: %d, %d", num1, num2); swapnum(num1, num2); printf("nAfter swapping: %d, %d", num1, num2); } void swapnum( int var1, int var2 ) { int tempnum ; tempnum = var1 ; var1 = var2 ; var2 = tempnum ; Output: Before swapping: 35, 45 After swapping: 35, 45
  • 49. Why variables remain unchanged even after the swap? The reason is same – function is called by value for num1 , num2. So actually var1 and var2 gets swapped (not num1 & num2). As in call by value actual parameters are just copied into the formal parameters.
  • 50. CALL BY REFERENCE When we call a function by passing the addresses of actual parameters then this way of calling the function is known as call by reference. In call by reference, the operation performed on formal parameters, affects the value of actual parameters because all the operations performed on the value stored in the address of actual parameters.
  • 51. #include <stdio.h> void increment(int *var) { *var = *var+1; } void main( ) { int num=20; // passing the address of variable num increment(&num); printf("Value of num is: %d", num); } Output: Value of num is: 21
  • 52. CALL BY REFERENCE In this function call the declaration of duplicate the type of each parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value. When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local variables will have an effect in their counterpart variables passed as arguments in the call to the function.
  • 54. CALL BY REFERENCE // passing parameters by reference #include <stdio.h> void duplicate (int& a, int& b, int& c) { a*=2; b*=2; c*=2; } int main () { int x=1, y=3, z=7; duplicate (x, y, z); printf(“"x= %d y= %d z= %d”, x,y,z) ; return 0; }
  • 55. CALL BY REFERENCE To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on b will affect y, and the same with c and z. That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables to be doubled.
  • 56. #include <stdio.h> void swap ( int *, int *); void main( ) { int num1 = 35, num2 = 45 ; printf("Before swapping:num1 is %d num2 is %d", num1, num2); swap( &num1, &num2 ); printf("nAfter swapping:num1 is %d num2 is %d", num1, num2); } void swap( int *var1, int *var2 ) { int temp; temp= *var1 ; *var1 = *var2 ; *var2 = temp; } Output: Before swapping:num1 is 35 num2 is 45 After swapping: num1 is 45 num2 is 35
  • 57. Here we are swapping the numbers using call by reference. As you can see the values of the variables have been changed after calling the swap( ) function because the swap happened on the addresses of the variables num1 and num2.

Editor's Notes

  1. The function definition declares the return data type, its name, and the data types of its parameters. Any parameter names included in the list are actually ignored by the compiler. The names are included to help document the function. Contrast this with the function prototype.
  2. Show structure from the template: miles_to_kilometers.c The function prototype declares the return data type, the function's name, and the data types of its parameters. Any parameter names included in the list are actually ignored by the compiler. The names are included to help document the function. Function prototype helps reduce program errors, because by using it, the compiler can then detect the wrong number or the wrong type of data items that are passed to the function