0% found this document useful (0 votes)
9 views

Module-2 Functions

PPT to learn C programming

Uploaded by

Parth Bhad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Module-2 Functions

PPT to learn C programming

Uploaded by

Parth Bhad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Functions

BASICS OF C
What will you learn?
 Functions
 Function Definition
 Calling Functions
 Recursion
 Function with Arrays
FUNCTIONS
 Functions break large computing tasks into smaller
ones.

 C has been designed to make functions efficient and easy to


use. C programs generally consist of many small functions
rather than a few big ones.

 A function is a block of code that can perform task which


can be executed independently from other parts of
the program as and when required by simply making
a call.
ADVANTAGES OF
FUNCTIONS
 It facilitates top-down modular programming: here the
problem can be factored into understandable and manageable
steps.

 Reusing of the code: The length of the source program can be


reduced by using functions at appropriate places. i.e writing
functions avoids rewriting of same code over and over.

 Using functions it becomes easier to write programs and keep track


of what they are doing.

 The functions are much easier to understand and test.

 C comes with rich and valuable set of library functions that makes
programmer’s work easier.
FUNCTION
DEFINITION:
When a function is defined, space is allocated for that function in
memory. A function definition includes the following elements:

1. Function header

 Function name – this can be used to invoke (call) a function


 Return type - it is used to return a value from the function
 Arguments list – it is list of arguments those are passed to the
function when it is called, and these are called formal
parameters.
2. Function body – it is a group of statements that together perform
some task.
THE SYNTAX OF THE FUNCTION
DEFINITION
return_type function_name (data_type arg1, data_type arg2
……………)
{
…………………
…………………
…………………
return statement;
}
FUNCTION DEFINITION EXAMPLE
FUNCTION DECLARATION (OR)
FUNCTION PROTOTYPE
Before using a function, the complier must know about the
number of parameters and the type of parameters that the
function expects to receive and the data type of the value that it
will return to the calling function.

The general format for declaring a function is given as follows:

return_type function_name (data_type argName1, data_type argName2 ……………);

Example:

int sum (int a ,int b);//function declaration with parameter names

Int sum(int, int);//function declaration without parameter names


FUNCTION DECLARATION
EXAMPLE
FUNCTION CALL
 To use a function, it can be called.

 Function that uses another function is known as the Calling


Function,

 And the function that is called by another function is known as


Called Function.

 Any function can call any function. When a function calls another
function, the program flow is transferred to the called function, after
the completion of the execution of the called function the program
flow is transferred back to the calling function.

 Function call statement has the following syntax:

Function_name( variable1, variable2 …….);


CONTINUED.,
 The inputs that a function can take are called
arguments/parameters.

 When a called function returns some value back to the calling


function, it is said to be return.

 When calling a function, the arguments that are passed, must


match with the number of parameters and the type of
parameters in the function header, otherwise, the complier
cannot bind the call and an error is generated.

 The arguments that are passed from the calling function are
called actual arguments and the arguments that receive
these values are called formal arguments.
FUNCTION CALLING EXAMPLE

Called Function Formal Parameters

Actual Parameters

//Calling Function

Note: Function call is necessary to bring the program


control to the function definition. If not called, the
function statements will not be executed.
C PROGRAM TO ADD TWO NUMBERS BY USING
FUNCTIONS
#include<stdio.h>
void sum( ) // function definition and called function
{
int x=5,y=10;
int sum =x+y;
printf(“The sum is %d”, sum);
}
int main( )
{
sum( ); // calling function
return 0;
}
FUNCTION RETURN
TYPE
 The return statement is used to terminate the execution of
a function and returns the control to the calling function.

 The syntax of the return statement is as follows:

return <expression>;

 Here the value of the expression is returned to the calling


function and the type of the value is the return type of the
function.

 If a function cannot return any value then its return type is


Note: Only one value can be returned from a C
function.
void. To return multiple values, we have to use
pointers or structures.
EXAMPLE: Function Declaration

#include<stdio.h> printf("\n product value


%d”,m );
int multiplication(int, int);
return 0;
int main()
}
{
int multiplication(int a, int b)
int a, b, m;
{
printf(" enter two integer values \
n"); int multi;

scanf("%d %d",&a, &b); multi = a * b;

//calling the function return multi;

m = multiplication(a, b); Function }


Call
TYPES OF FUNCTIONS
Depending on whether a function is defined by the user or
already included in C compilers, there are two types of
functions in C programming

There are two types of functions in C programming:

1. Standard library functions / Pre –Defined Functions / Built –


in Functions

2. User defined functions


STANDARD LIBRARY
FUNCTIONS
 The standard library functions are built-in functions in C programming to
handle tasks such as mathematical computations, I/O operations, string
handling etc.

 The user can only use these functions but can’t change or modify them.

 These functions are defined in the header file. When you include the
header file, these functions are available for use.

 Some header files are:

 Stdio.h---printf( ) , scanf( ) are defined in the C library header file


 Conio.h
 Math.h---sqrt( ), sin( ), cos( ), tan( ), pow( )
 String.h
 Stdlib.h
USER-DEFINED
FUNCTIONS
C allows programmers to define their own functions. Functions
created by the programmers are called user-defined functions.

These user defined functions can be defined in any of the


following ways:

1. Functions with no arguments and no return value

2. Functions with arguments but no return value

3. Functions that have no arguments but return a value

4. Functions that have arguments as well as return value


STRUCTURE OF USER-DEFINED
FUNCTIONS
Syntax: return-type function-name (arguments list)

argument declaration

Local variable declarations

Executable statement

……

…… ……

return (expression or value)

}
CONTD…
 In function structure all parts not essential, it is based on
the requirement of the program and some sections or
parts may be absent.

 Return-type is any data type.

 All functions by default return int type data.

 Function-name can be any name like variables which


follows naming conventions of identifiers.

 The arguments list and its associated declaration are


optional. These are any valid variable name separated by
commas.
CONTD…
 The declaration of local variables is required only when any
local variables are used in the function.

 A function can have any number of executable statements.

 The return is a keyword which is followed by some


expression or value.

 The return statement returns a value to the calling function


and is optional.

 When there is no return statement, then no value is being


returned to the calling function. We can return only one
value at a time
DIFFERENCE BETWEEN LIBRARY
FUNCTIONS AND USER DEFINED
FUNCTIONS
 The library functions are not required to written by the
user, where as user-defined functions have to develop by
the user at the time of writing of application.

 The user can’t modify the meaning of the library functions.


But user can modify the user defined functions.

 The library functions are already tested and debugged, but


the user-defined functions need to be test and debug.
FUNCTION WITH NO ARGUMENT

AND
void NO RETURN VALUE
addition()
{
int sum, a = 10, b = 20;
sum = a + b;
printf("\n sum of a = %d and b = %d is = %d", a,
b, sum);
}
FUNCTION WITH NO ARGUMENT

AND WITH RETURN VALUE


int multiplication()
{
int multi, a = 20, b = 40;
multi = a * b;
return multi;
}
FUNCTION WITH ARGUMENT
AND NO RETURN VALUE
void addition(int a, int b)
{
int sum;
sum = a + b;
printf("\n additiontion of %d and %d is = %d \n", a, b,
sum);
}
FUNCTION WITH
ARGUMENT AND RETURN
VALUE
int multiplication(int a, int b)
{
int multi;
multi = a * b;
return multi;
}
PARAMETER PASSING

METHODS

OR

TYPES OF FUNCTION CALLS


TYPES OF FUNCTION CALLS
When a function is called, the calling function may
have to pass some values to the called function. There are
two ways in which arguments or parameters are passed to
the called function. They include:

1. Call by Value

2. Call by Reference
CALL BY VALUE:
In this method, values of the variables are passed from the calling
function to the called function

1. In this method, the called creates the new variables to store the
values that are passed to it.

2. This means the called function uses a copy of the actual arguments
to perform the defined task.

3. If the called function is supposed to modify the value of the


parameters to modify the value of the parameters passed to it, then
the changes will be reflected in called function only but the changes
will not be reflected to the calling function.

4. This is because all the changes are made to the copy of the variables
but not to the actual variables.
EXAMPLE:
int main () void swap(int x, int y)
{ {
int a = 10; int z;
int b = 20; z = x;
printf(“%d%d”,a,b); x = y;
swap(a, b); y = z;
printf(“%d%d”,a,b); }
return 0;
X Y Z
} A B

10 20 10 20 10

2000 2100 2200


1000 1100
CALL BY REFERENCE:
 In this method, addresses of the variables are passed from the
calling function to the called function.

 In this method, while writing functions, the parameters of the


function are declared as references rather than normal variables.

 Since variable references are being passed instead of a copy of


variable values, any changes that are done in the called function
will be reflected to the calling function.

 In this method, a function receives the references as arguments


not the normal variables.

 So, in order to receive the references the function formal


arguments are of pointer type, which are declared using the
symbol *.
EXAMPLE:
int main () void swap(int *x, int *y)
{ {
int a = 10; int z;
int b = 20; z = *x;
printf(“%d%d”,a,b); *x = *y;
swap(&a, &b); *y = z;
printf(“%d%d”,a,b); }
return 0;
}
X A Y B Z

1000 10 1100 20
2000 1000 2100 1100 2200

z=*x; *x=*y; *y=z;


Z X A Y B

10 1000 20 1100 10
2200 2000 1000 2100 1100
RECURSIVE
FUNCTIONS
RECURSIVE
FUNCTIONS
 A Recursive function is defined as a function that calls itself to solve a
smaller part of its task repetitively to solve the whole problem. This process
is called Recursion.

 Recursive functions are used in those cases whenever a same task is to be


performed repeatedly. A repetitive function is defined recursively whenever
the function appears within the definition itself.

 Every recursive solution has two major cases:

 Base Case, in which problem is simple enough to be solved directly


without making any further calls to the same function.

 Recursive Case, in which first the problem at hand is divided into smaller
sub – parts. Second the function calls itself but with sub parts of the
problem obtained in the first step.
The following are the rules for designing a recursive function:
1. First determine the base case
2. Then determine the recursive case
3. Finally combine the base case and recursive case into a
function
To understand the recursive functions, take an example of
calculating the factorial of a number. The factorial of the number is
the product of the integral values from 1 to the number.
This means,
n! = n * (n – 1)!
Here, n! is obtained by multiplying n with (n – 1)!
Assume n=3 so 3! = 3 x 2 x 1
This can be written as
3! = 3 x 2!, where 2! = 2 x 1!
So, 3! = 3 x 2 x 1!, where 1! = 1
So, 3! = 3 x 2 x 1.
• If one should observe the problem carefully, here the product is

the repetitive task.

• So it is suitable to write a recursive function.

• As every recursive function has a base case and recursive case,

they are defined a follows for factorial function:

 Base Case is when n =0 will be 1 as 0! = 1

 Recursive Case is the factorial function itself but with a value of

n, this can be given as Factorial (n) = n x Factorial (n – 1)


FACTORIAL FUNCTION

int factorial ( int n )


{
if ( n == 0)
return 1;
else
return ( n * factorial (n – 1));
}
Factorial (3) = 3 * Factorial (2) Factorial (3) = 3 * 2 = 6

Factorial (2) = 2 * Factorial (1) Factorial (2) = 2 * 1 = 2

Factorial (1) = 1 * Factorial (0) Factorial (1) = 1 * 1 = 1

Factorial (0) = 1
FUNCTION WITH ARRAYS
#include<stdio.h> float findAverage(int marks[])
float findAverage(int marks[]); {
int i, sum = 0;
int main() float avg;
{ for (i = 0; i <= 4; i++)
float avg; {
int marks[] = {99, 90, 96, 93, 95}; sum += marks[i];
avg = findAverage(marks); }
printf("Average marks = %.1f", avg); avg = (sum / 5);
return 0; return avg;
} }

You might also like