Vous êtes sur la page 1sur 41

Unit 1.

Functions

By: Prof. Arpankumar G. Raval


Assistant Professor, FITCS
PICA-BCA, Parul University.
Introduction to Function
• A function is a self contained block of code that performs a
particular task.
• Any C program can be seen as a collection/group of these
functions.
• A functions takes some data as input, perform some
operation on that data and then may return a value.
• Any C program must contain at least one function, which is
main().
• There is no limit on the number of functions that might be
present in a C program.
Definition
• A set of statements working together with
common goal is known as function.
• Also known as subprograms which are used to
compute a value or perform a specific task.
• They can’t run independently and are always
called by the main() program or by some
other function.
Why we need User Defined
Functions or Functions in C
• Functions are used because of following
reasons
To improve the readability of code.
To Improve the reusability of the code, same
function can be used in any program rather than
writing the same code from scratch.
Debugging of the code would be easier if you use
functions, as errors are easy to be traced.
Reduces the size of the code, duplicate set of
statements are replaced by function calls.
Types of functions
Library functions: These are also known as Pre
defined functions.
Examples are scanf(), printf(), getch(), strlen(),
strcmp(), strcat(), sqrt(), pow()

User-Defined functions: User defined functions


are self-contained blocks of statements which are
written by the user to compute or perform a task.
They can be called by the main program
repeatedly as per the requirement.
Advantages of User Defined Functions
• They are very much useful when a block of
statements has to be written/executed again
and again.
• They are useful when program size are too
large and complex.
• It works like top-down modular programming
technique to solve a problem.
• They are also used to reduce the difficulties
during debugging a program.
ELEMENTS OF USER-DEFINED
FUNCTION
• In order to make use of user-defined functions, we
need to establish three elements or steps that are
required for user defined functions.

1. Function declaration or Function prototype


2. Function definition or Function implementation
3. Function Call
1. Function Declaration or Prototype
• All Identifiers in C must be declared before they are used. This
is true for functions as well as variables.
• For functions, the declarations needs to be done before the
first call of the function.
• A function declaration specifies the name, return type, and
arguments of a function. This is also called the function
prototype.
• To be a prototype, a function declaration must establish types
for the function’s arguments.
• Having the prototype available before the first use of the
function allows the compiler to check that the correct number
and types of arguments are used in the function call.
• The function prototype must have :
– A return type indicating the variable that the
function will be return. It may be int, float, double,
char, short, void etc.
– How to declare or create prototype of the
Function:
Syntax:
Return_type function_name(arguments list);
Ex.
int add(int , int); or int add(int a, int b);
2. Function definition or Function
implementation
• It is the actual function that contains the code that
will be executed.
• Should be identical (same) to the function
prototype.
• Syntax :
return-type function_name ( arg-type name-1,...,arg-type name-n)
{
declarations; Function Body
statements;
return(expression);
}
• General form of any function definition is:
return-type function-name(argument declarations)
{
declarations and statements
}
• Return-type refers to the data type of the value being
returned from the function. If the return type is omitted, int is
assumed.
• The values provided to a function for processing are the
arguments.
• The set of statements between the braces is called as the
function body.
Example:
int add(int a, int b)
{
int c;
c = a + b;
return c;
}
• The function name is add
• This function accepts arguments a and b of integer type formal arguments
. The function returns sum of a and b as integer type.
• So, when this function is called in the program, it will perform its task
which is to add two numbers passed as actual parameters and it will
returns the sum of both.
• Note that if the function is returning a value, it needs to use the keyword
return and if not returning value then use void data type.
3. Function call
• The program that calls the function is referred
to as the calling program or calling functions.
Syntax:
function_name(actual parameters);
Ex.
c=add(a,b); or add(); or; or c=add(); or add(a,b);
Types of arguments(parameters)
1. Formal parameter (argument)
2. Actual parameter (argument)
• Argument: An argument is an expression
which is passed to a function by its caller in
order for the function to perform its task. It is
an expression in the comma-separated list
bound by the parentheses in a function call
expression. It may be value or variable.
1. Formal arguments:
• The formal arguments are the parameters/arguments in a function
declaration or definition.
• The scope of formal arguments is local to the function definition in
which they are used.
• Formal arguments belong to the called function.
• Formal arguments are a copy of the actual arguments.
• A change in formal arguments would not be reflected in the actual
arguments.
• Formal are when we define the function
• Example:
• Int add (int a , int b)
{
return a + b;
}

Here, in this example a and b are the formal parameters.


2. Actual arguments:
• The arguments that are passed in a function call
are called actual arguments.
• These arguments are defined in the calling
function.
• The declared variables or the direct values can be
passed at the calling of the function is called the
actual parameters.
• Example:
ans = add(a , b);
ans =add(10 , 20);
Here, the variable a, b, 10 and 20 are the actual
parameters or arguments.
Categories of functions
1) Function with return value & with arguments
2) Function with no return value & no arguments
3) Function with return value & no argument
4) Function with no return value & with
arguments
Return Value Argument
Simple: YES YES
NO NO
YES NO
NO YES
1. Function with return value &
with arguments
• Argument are passed by calling function to the
called function
• Called function return value to the calling function
• Mostly used in programming because it can two
way communication
• Data returned by the function can be used later in
our program for further calculation.
• Example of Function with return value & with
arguments.
2. Function with no return value
& no arguments
• Called function does not have any arguments
• Not able to get any value from the calling
function
• Not returning any value
• There is no data transfer between the calling
function and called function.
• Example of Function with no return value
& no arguments
3. Function with return value & no
argument
• Here in this function the function will return
the value.
• The arguments are not provided from the
calling function but receives the value
returned from the function.
• Arguments are decided by the called function.
• Example of Function with return value & no
argument
4. Function with no return value &
with arguments
• In this function the function is passing the
arguments but will not receive any returned
value.
• Calling function will only send the arguments
but not accepts the returned value as it is not
returned from the called function.
• Example of Function with no return value &
with arguments
Some Possibilities for the function with
return values
 In some cases function may return conditional values from the return. In
recursion function is returning the values based on the base condition of
the function. The following example shows the same.
int check( )
{
int n;
printf(“Enter a number”);
scanf(“%d”,&n);
if(n%2==0);
return(1);
else
return(0);
}

 This above example of function may return 1 or 0, based on the inputted


value.
Recursion
 Recursion defines a function in terms of itself.
 It is a programming technique in which a function calls itself.
 A recursive function calls itself repeatedly, with different
argument values each time.
 Some argument values cause the recursive method to return
without calling itself. This is the base case.
 Either omitting the base case or writing the recursion step
incorrectly will cause infinite recursion (stack overflow error).
Examples for Recursion
1. Factorial of Number
2. Fibonacci Series
Recursion to find the factorial of any number:
int factorial(int x)
{
if(x<=1)
return 1;
else
return(x*factorial(x-1));
}
Recursion to find the Fibonacci series up to 10 numbers:

#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t\n", fibonaci(i));
}
return 0;
}
The Scope, Visibility and Lifetime of
variable:
• The scope of a variable is the range of
program statements that can access that
variable.
• The lifetime of a variable is the interval of
time in which storage is bound to the variable.
• A variable is visible within its scope and
invisible or hidden outside it.
Scope
• A scope in any programming is a region of the
program where a defined variable can have its
existence and beyond that variable it cannot be
accessed.
• There are three places where variables can be
declared in C programming language −
 Inside a function or a block which is
called local variables.
 Outside of all functions which is
called global variables.
 In the definition of function parameters which are
called formal parameters.
Local and Global Variable Example
Lifetime of the Variable
The lifetime of a variable is the period of time in
which the variable is allocated a space (i.e., the
period of time for which it “lives”).
There are four lifetimes in C:
Or Storage Classes :
It is required when we declare any variable
Four Types of Classes are there:
1) Automatic
2) Register
3) Static
4) External
• Automatic : Keyword is auto, Local Variable,
RAM, Default value: garbage Value, declare in
function or main, Life time when block
execution completed.
Auto int a; incorrect
void main()
{
auto int a=10; correct

}
• Register: Keyword is Register, Local Variable, CPU
registers, Default value: garbage Value, declare in
function or main, Life time when block execution
completed. It is very less memory so we don’t
use. Its 8 to 16 kb
Register int a; incorrect
Void main()
{
Register int a=10; correct

}
 Static: Fixed Memory, Cant increase or
decrease the size, Constant, Memory allocated
at run time.
int a[5];
• External or Dynamic Memory allocation: Initial
memory, at Insert and Delete of data the
memory size will increase and decrease.
• Not Constant, Memory allocated at run time.
• Char name[];
• Dynamic: In the dynamic memory allocation
user can allocate and delete the memory to
the identifiers. Some functions are available
for the dynamic memory allocation.
• Dynamic objects are stored in "the heap".
1. Malloc: for structures
2. Calloc: for arrays
3. Realloc: for increase and decrease the memory
4. Free: for deleting the memory of the variable
Visibility
• Visibility is the “accessibility” of the variable
declared. It is the result of hiding a variable in
outer scopes.
• One function local variable is invisible or not
accessible by the other function because of
not visible.
• The scope bound the visibility of variable.
Example
int main(int argc, char *argv[]) float f(float x)
{ {
... CANNOT access any variable
... CANNOT access any variable
int var1; <--------- var1 starts to exist int var3; <--------- var3 starts to exist
.. var3 accessible
.. var1 accessible
{ {
.. var3 accessible
.. var1 accessible
float var2; <--- var2 starts to exist float var4; <--- var4 starts to exist

var1 and var2 are accessible var3 and var4 are accessible
} <--- var2 ends to exist } <--- var4 ends to exist

.. only var3 accessible...


.. only var1 accessible... } <--------- var3 ends to exist
} <--------- var1 ends to exist
Thank You…

Vous aimerez peut-être aussi