0% found this document useful (0 votes)
17 views44 pages

6 Functions in C

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views44 pages

6 Functions in C

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 44

23CSE201

PROCEDURAL PROGRAMMING USING C


INTRODUCTION OF FUNCTION
• A function is a block of code that performs a specific task. In c, we can
divide a large program into the basic building blocks known as function.
• The function contains the set of programming statements enclosed by {}.
• A function can be called multiple times to provide reusability and
modularity to the C program.
• In other words, we can say that the collection of functions creates a program.
• The function is also known as procedure or subroutine in other
programming languages.
FUNCTIONS

• There are two types of function in C programming:

Standard Library Functions/ Built In Function


User-Defined Functions
STANDARD LIBRARY FUNCTIONS/ BUILT-IN FUNCTIONS
• A function that is built into an application and can be accessed by end-users is
called Built-in functions and the standard library functions are built-in functions
in C programming. These functions are defined in header files.
• For example;
• The printf() is a standard library function to send formatted output to the
screen (display output on the screen). This function is defined in the stdio.h
header file.
• The sqrt() function calculates the square root of a number. The function is
defined in the math.h header file.
USER-DEFINED FUNCTION
• You can also create functions as per your
need. Such functions created by the user are
known as user-defined functions. And These
functions are defined by the user at the time
of writing the program.
• A user defined function is a programmed
routine that has its parameters set by the users.
PARTS OF USER-DEFINED FUNCTION

1. Function Prototype / Function Declaration


2. Function Definition / Function Body
3. Function Calling
Function prototype
• A function prototype is simply the declaration of a function that specifies
function's name, parameters and return type.
• It doesn't contain function body.
• A function prototype gives information to the compiler that the function may later
be used in the program.
• It is always placed in Global declaration section.
• Syntax: DataType FunctionName (ParameterList);
• Example: int addition (int a, int b);
Function Calling
• Whenever Compiler will call the function , the Control of the program is
transferred to the user-defined function body by calling it.
• Function calling placed inside the main function (mostly)

• Syntax: FunctionName (argument1, argument2, ...);

• Example : Addition(a,b);
Function Definition
• Function definition contains the block of code to perform a specific task.
• When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a
function.
• Syntax: ReturnType FunctionName (type1 argument1, type2 argument2, ...) {
//body of the function
}
• Example: int add(int a, int b) {
int sum = a + b;
return sum;
}
Write a program to perform addition of two variables using
user define function.
#include<stdio.h> int add(int a, int b)
int add(int a ,int b); {
void main() int sum=a+b;
{ return sum;
int n1=100; }
int n2=200;
int sum;
Output:
sum = add(n1,n2);
100 + 200 = 300
printf("%d + %d = %d"
,n1,n2,sum);
}
TYPES OF USER DEFINED FUNCTIONS IN C

• A function in C may define with or without parameters, and a function may or


may not return a value. It entirely depends upon the user requirement. And as per
our requirement, we can define the User-defined functions in multiple ways. i.e.;
1. Function with No Argument and No Return type
2. Function with No Argument and with a Return type
3. Function with Argument and No Return type
4. Function with Argument and Return type
FUNCTION WITH NO ARGUMENT AND NO RETURN TYPE

• In this method, we would not pass any arguments to the function while
defining, declaring, or calling the function.

• This type of functions in C will not return any value when we call the
function from main().

• When we are not expecting any return value, but we need some
statements to print as output. Then, this type of function in C is very
useful.
Write a program to perform addition of two variables using
user define function.
#include<stdio.h>
void addition ();
void main ()
{ Output:
addition(); 10 + 20 = 30
}

void addition() {
int sum, a=10, b=20;
sum=a+b;
printf("%d + %d = %d“ ,a,b,sum);
}
FUNCTION WITH NO ARGUMENT AND WITH RETURN TYPE

• In this method, we would not pass any arguments to the function while
defining, declaring, or calling the function.

• This type of function will return some value when we call the function
from main() or any sub function.

• The Datatype of the return value will depend upon the return type of
function declaration. For example, if the return type is int then return
value will be int.
Write a program to perform addition of two variables using
user define function.
#include<stdio.h>
int addition();
void main() {
int sum; Output:
sum = addition(); 10 + 20 = 30
printf("Addition is : %d",sum);
}
int addition() {
int sum, a=10,b=20;
sum=a + b;
return sum;
}
FUNCTION WITH ARGUMENTS AND NO RETURN TYPE
• If you observe the above two methods, we don’t have any control over the
values of the variables because they are fixed values.

• In real-time, we mostly deal with dynamic data means we have to allow the user
to enter their own values rather than fixed ones.

• This method allows us to pass the arguments to the function while calling the
function. But, this type of function will not return any value when we call the
function from main () or any sub function.

• If we want to allow the user to pass their data to the function arguments, but we
are not expecting any return value, this type of function is very useful.
Write a program to perform addition of two variables using
user define function.
#include<stdio.h>
void addition(int a,int b);
void main()
{ Output:
int a=10,b=20; 10 + 20 = 30
addition(a,b);
}
void addition(int a,int b)
{
int sum=a+b;
printf("%d + %d = %d",a,b,sum);
}
FUNCTION WITH ARGUMENT AND RETURN TYPE
• This method allows us to pass the arguments to the function while calling the
function. This type of function will return some value when we call the function
from main () or any sub function.

• Datatype of the return value will depend upon the return type of function
declaration. For instance, if the return type is int then return value will be int.

• This type of user-defined function is called a fully dynamic function, and it


provides maximum control to the end-user.
Write a program to perform addition of two variables using
user define function.
#include<stdio.h>
int addition(int a, int b);
void main() {
int a=10,b=20;
int sum = addition(a,b); Output:
10 + 20 = 30
printf("%d + %d = %d",a,b,sum);
}

int addition(int a,int b){


int sum=a+b;
return sum;
}
ADVANTAGES OF FUNCTIONS
• Avoid repetition of codes and Increases program readability.
• Divide a complex problem into simpler ones.
• Reduces chances of error.
• Modifying a program becomes easier by using function.
• There is no limit in calling C functions to make use of same functionality
wherever required. We can call functions any number of times in a program and
from any place in a program.
• Program development become easy.
• A function can call other functions & also itself.
TYPES OF FUNCTION ARGUMENTS IN C
• Basically, there are two types of arguments:

1. Actual arguments: The values that are passed to the called function from the
main function are known as Actual arguments.

2. Formal Arguments: The variables declared in the function prototype or


definition are known as Formal arguments or Dummy arguments.

• These arguments are used to just hold the value that is sent by calling function.

• Formal arguments are like other local variables of the function which are created
when function call starts and destroyed at the end of function
TYPES OF FUNCTION ARGUMENTS IN C
TYPES OF FUNCTION CALLS IN C

• we can call a function in two different ways, based on how we specify the
arguments, and these two ways are:

1. Call by Value
2. Call by Reference
CALL BY VALUE

• 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 cannot 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.
EXAMPLE - CALL BY VALUE
#include<stdio.h> int MyFunction (int a,int b)
int MyFunction(int a,int b); {
void main() { a=200;
int a=10; b=100;
int b=20; }
MyFunction (a,b);
printf("Value of A is : %d",a); Output:
Value of A is : 10
printf("\nValue of B is : %d",b); Value of B is : 20
}
Advantages - Call by value method

• The method doesn't change the original variable, so it is preserving data.

• Whenever a function is called it, never affect the actual contents of the actual
arguments.

• Value of actual arguments passed to the formal arguments, so any changes made in
the formal argument does not affect the real cases.
Disadvantages - Call by value method

• Changes to actual parameters can also modify corresponding formal argument


variables.

• In this method, arguments must be variables.

• You can't directly change a variable in a function body.

• Sometime argument can be complex expressions.

• There are two copies created for the same variable which is not memory efficient.
CALL BY REFERENCE

• In call by reference, the memory allocation is similar for both formal parameters and
actual parameters.

• Now formal and actual arguments both points to the same data (because they contain the
same address). As a result, any changes made by called function also affect the actual
arguments.

• To pass a value by reference, in argument pointers are passed to the functions just like
any other value. So accordingly, you need to declare the function parameters as pointer
types.

• Pass the addresses of the actual arguments instead of passing values to the function.
EXAMPLE - CALL BY REFERENCE
#include<stdio.h>
int fun(int *x, int *y); int fun(int *x,int *y)
void main() {
{ *x = 20;
int a=10; *y = 10;
int b=20; }
fun(&a,&b); Output:
Value of A is : 20
printf("Value of A is : %d",a); Value of B is : 10
printf("\nValue of B is : %d",b);
}
Advantages - Call by reference method

• The function can change the value of the argument, which is quite useful.

• It does not create duplicate data for holding only one value which helps you to
save memory space.

• In this method, there is no copy of the argument made. Therefore, it is processed


very fast.
Disadvantages - Call by reference method

• Strong non-null guarantee. A function taking in a reference need to make sure that
the input is non-null.

• Passing by reference makes the function not pure theoretically.

• A lifetime guarantee is a big issue with references.


CALL BY VALUE CALL BY REFERENCE
While calling a function, in programming language
While calling a function, when you pass values by instead of copying the values of variables, the address
copying variables, it is known as "Call By Values" of the variables is used it is known as "Call By
References"
Actual and formal arguments are created at the Actual and formal arguments are created at the same
different memory location memory location

Original value of Argument cannot be modified. Original value of Argument can be modified

Values of variables are passed using a straightforward Pointer variables are required to store the address of
method variables.

Actual arguments remain safe as they cannot be Actual arguments are not Safe. They can be
modified accidentally accidentally modified

Default in many programming languages like C++, It is supported by most programming languages like
PHP, Visual Basic , .NET, and C#. JAVA, but not as default.
RECURSION IN C

• A function that calls itself again and again is known as a recursive function.
And, this technique is known as recursion.

• The process in which a function calls itself directly or indirectly is called


recursion and the corresponding function is called as recursive function.

• Recursion cannot be applied to all the problem, but it is more useful for the tasks
that can be defined in terms of similar subtasks.

• For Example, recursion may be applied to sorting, searching, and traversal


problems.
RECURSION IN C

• Recursion involves several numbers of recursive calls. However, it is important to


write a termination condition of recursion.
• Recursion code is shorter than iterative code
however it is difficult to understand.

• A recursive function performs the tasks by dividing it


into the subtasks. There is a termination condition
defined in the function which is satisfied by some
specific subtask. After this, the recursion stops and
the final result is returned from the function.
EXAMPLE – Factorial Using Recursive Function
#include<stdio.h> void main() {
int factorial(int n) int n;
{ int fact=0;
if(n==1) printf("Enter the Number:");
return 1; scanf("%d",&n);
else fact=factorial(n);
return n*factorial(n-1); printf("Factorial of %d is : %d \n",n,fact);
} }

Output:
Enter the Number: 5
Factorial of 5 is : 120
Advantages - RECURSION

• Reduce unnecessary calling of function.

• Through Recursion we can Solve problems in easy way while its iterative solution
is very big and complex.

• Recursion function required less coding.

• Recursion adds clarity and reduces the time needed to write and debug code.
Disadvantages - RECURSION

• Recursive solution is always logical and it is very difficult to trace.

• In recursive we must have an if statement to force the function for termination of


calling, otherwise the function goes in infinite state.

• Recursion uses more processor time.

• If proper coding is not done then also Recursive function may lead to infinite loop.
STORAGE CLASSES
• A storage class represents the visibility and a location of a variable. It tells from
which part of code we can access a variable. A storage class in C is used to
describe the following things:
• The variable scope.
• The location where the variable will be stored.
• The initialized value of a variable.
• A lifetime of a variable.
• Who can access a variable?
We have four different storage classes in a C program;
1. auto 2. register 3. static 4. extern
The auto Storage Class
• The auto storage class is the default storage class for all local variables.
• Example:
{
int a;
auto int b;
}
• The example above defines two variables with in the same storage class.
• 'auto' can only be used within functions, i.e., local variables.
The register Storage Class
• You can use the register storage class when you want to store local variables
within functions or blocks in CPU registers instead of RAM to have quick access
to these variables.
• For example, "counters“ or “i” are a good candidate to be stored in the register.
• Example: register int age;
• The keyword register is used to declare a register storage class. The variables
declared using register storage class has lifespan throughout the program.
• It is similar to the auto storage class. The only difference is that the variables
declared using register storage class are stored inside CPU registers instead of a
memory. Register has faster access than the main memory.
The static Storage Class

• The static variables are used within function/ file as local static variables. They
can also be used as a global variable.

• Static local variable is a local variable that retains and stores its value between
function calls or block in which it is defined.

• Example: static int count = 10;

• Static variable has a default initial value zero and is initialized only once in its
lifetime.
The extern Storage Class

• Extern stands for external storage class. Extern storage class is used when we have
global functions or variables which are shared between two or more files.

Example: extern i;

• Keyword extern is used to declaring a global variable or function in another file to


provide the reference of variable or function which have been already defined in
the original file.
Summary – Storage Classes
THANK YOU

You might also like