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

Unit 2 Functions

The document provides an overview of functions in C programming, detailing their definitions, types (standard library and user-defined), and various ways to define and call them. It explains concepts such as call by value and call by reference, along with examples of user-defined functions and their advantages. Additionally, it discusses the differences between call by value and call by reference, highlighting their respective benefits and drawbacks.

Uploaded by

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

Unit 2 Functions

The document provides an overview of functions in C programming, detailing their definitions, types (standard library and user-defined), and various ways to define and call them. It explains concepts such as call by value and call by reference, along with examples of user-defined functions and their advantages. Additionally, it discusses the differences between call by value and call by reference, highlighting their respective benefits and drawbacks.

Uploaded by

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

ADVANCED

COMPUTER
PROGRAMMING

PREPARED BY: NIDHI SONI


UNIT 3
FUNCTIONS
 Function definition
 Call by value and call by reference
 Recursive function
 Storage class
 Types of function
 Types of user define functions
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.
 Dividing a complex problem into smaller chunks makes our
program easy to understand and reuse.

TYPES OF FUNCTION
There are two types of function in C programming:
1. Standard library functions
2. User-defined functions

1. 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 funsctions
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.
 The clrscr() is a standard library function which is used to clear the
output screen.This function is defined in the conio.h header file.
 The strlen() function is used to find of the given string. This function
is defined in string.h header file.
2. 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 user of the system. User defined
functions often are seen as programming shortcuts as they define
functions that perform specific tasks within a larger system.
Syntax:
#include <stdio.h>
void functionName()
{
}
int main()
{
functionName();
}
Part of User-Defined Function
1. Function Prototype (function declaration)
2. Function Definition
3. Function Call
1. 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);

2. Calling a function
Whenever Compiler will call the Function , the Control of the
program is transferred to the user-defined function by calling it.
Syntax:
functionName(argument1, argument2, ...);
Example :
addition(a,b);
3. Function definition
 Function definition contains the block of code to perform a
specific task. In our example, adding two numbers and returning it.
 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 of function definition


returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
Example:
int add(int a,int b)
{
int sum=a+b;
}

Passing arguments to a function


 In programming, argument
refers to the variable passed to
the function.
 If two variables n1 and n2 are
passed during the function
call.The
parameters a and b accept the
passed arguments in the
function definition.

 These arguments (a and b) are called formal parameters of the


function. And arguments (n1 and b) are called formal parameters
of the function.
EXAMPLE OF USER DEFINE FUNCTION:
AIM: WRITE A PROGRAM TO PERFROM ADDITION OF TWO
VARIABLES USING USER DEFINE FUNCTION.
#include<stdio.h>
#include<conio.h>
int add(int a ,int b);
void main()
{
clrscr();
int n1=100;
int n2=200;
int sum;
sum = add(n1,n2);
printf("Addition of %d and %d is : %d ",n1,n2,sum);
getch();
}
int add(int a,int b)
{
int sum=a+b;
}
Output:

TYPES OF USER DEFINE 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. Like;
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
1. 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.
Example:
#include<stdio.h>
#include<conio.h>
void addition ();
void main (){
clrscr();
addition();
getch();
}
void addition(){
int sum,a=10,b=20;
sum=a+b;
printf("Addition of %d and %d is : %d",a,b,sum);
}
Output:
Addition of 10 and 20 is :30
2. 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 subfunction.
 The Data Type 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.
Example:
#include<stdio.h>
#include<conio.h>
int addition();
void main()
{
int sum;
clrscr();
sum=addition();
printf("Addition is : %d",sum);
getch();
}
int addition()
{
int sum,a=10,b=20;
sum=a+b;
return sum;
}
Output: Addition is :30

3. 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
subfunction.
 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.
Example
#include<stdio.h>
#include<conio.h>
void addition(int a,int b);
void main()
{
clrscr();
int a=10,b=20;
addition(a,b);
getch();
}
void addition(int a,int b)
{
int sum=a+b;
printf("Addition of %d and %d is : %d",a,b,sum);
}
Output:
Addition of 10 and 20 is: 30

4. 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 subfunction.
 Data Type 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.
Example
#include<stdio.h>
#include<conio.h>
int addition(int a,int b);
void main(){
clrscr();
int a=10,b=20;
int sum=addition(a,b);
printf("Addition of %d and %d is : %d",a,b,sum);
getch();
}
int addition(int a,int b){
int sum=a+b;
return sum;
}
Output:
Addition of 10 and 20 is: 30

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
2. Formal 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 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:
#include<stdio.h>
#include<conio.h>
int fun(int a,int b);
void main()
{
clrscr();
int a=10;
int b=20;
fun(a,b);
printf("Value of A is : %d",a);
printf("\nValue of B is : %d",b);
getch();
}
int fun(int a,int b)
{
a=20;
b=10;
}
Output:

Advantages of using 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 of using 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.
WAP TO SWAP TWO NUMBERS USING CALL BY VALUE METHOD
#include<stdio.h>
#include<conio.h>
int swap(int a,int b);
void main()
{
clrscr();
int a=10;
int b=20;
printf("Before Swapping:\n");
printf("Value of A is : %d",a);
printf("\nValue of B is : %d",b);
swap(a,b);
getch();
}
int swap(int a,int b)
{
printf("\n\nAfter Swapping:\n"); Output:
int temp;
temp=a;
a=b;
b=temp;
printf("Value of A is : %d",a);
printf("\nValue of B is : %d",b);
}
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.

To use call by reference we need to do two things:


1. Pass the addresses of the actual arguments instead of passing
values to the function.
2. Declare the formal arguments of the function as pointer
variables of an appropriate type.
Example:
#include<stdio.h>
#include<conio.h>
int fun(int *x,int *y);
void main()
{
clrscr();
int a=10;
int b=20;
fun(&a,&b);
printf("Value of A is : %d",a);
printf("\nValue of B is : %d",b);
getch();
}
int fun(int *x,int *y){
*x = 20;
*y = 10;
}
Output:

Advantages of using 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 of using 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.

WAPTO SWAP TO NUMBERS USING CALL BY REFERENCE.


#include<stdio.h>
#include<conio.h>
int swap(int *x,int *y);
void main(){
clrscr();
int a=10;
int b=20;
printf("Before Swapping:\n");
printf("Value of A is : %d",a);
printf("\nValue of B is : %d",b);
swap(&a,&b);
printf("\n\nAfter Swapping:\n");
printf("Value of A is : %d",a);
printf("\nValue of B is : %d",b);
getch();
}
int swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Output:
DIFFRENCE BETWEEN CALL BY
VALUE AND CALL BY REFERENCE
CALL BY VALUE CALL BY REFERENCE
While calling a function, when While calling a function, in
you pass values by copying programming language instead
variables, it is known as "Call By of copying the values of
Values." variables, the address of the
variables is used it is known as
"Call By References.
Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory
location location
Original value of Argument Original value of Argument can
cannotbe modified. be modified.
Values of variables are passed Pointer variables are required to
using a straightforward method. store the address of variables.
Actual arguments remain safe as Actual arguments are not Safe.
they cannot be modified They can be accidentally
accidentally modified
Default in many programming It is supported by most
languages like C++, PHP, Visual programming languages like
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 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.
For Example:
void MYFUNCTION()
{
MYFUNCTION();
}

int main()
{
MYFUNCTION();
}
How it works?

Standard Example of Recursion


AIM: C PROGRAM TO FIND FACTORIAL USING RECURSION.
 In this program, we will read a number and then find (calculate)
of factorial of that number using recursion.
 What is factorial: Factorial of a number is the product of that
number with their all below integers.For example (Factorial of 5)
is:
!5 = 5*4*3*2*1 = 120
Program:
#include<stdio.h>
#include<conio.h>
int factorial(int n)
{
if(n==1)
{
return 1;
}
else
{return n*factorial(n-1);
}
}
void main()
{
int n;
int fact=0;
printf("Enter the Number:");
scanf("%d",&n);
fact=factorial(n);
printf("Factorial of %d is : %d \n",n,fact);
getch();
}
Output:

AIM: C PROGRAM TO CALCULATE POWER OF A


NUMBER USING RECURSION
In this program we will read base and power and then calculate result
of that expression using recursion.
Program:
#include<stdio.h>
#include<conio.h>
int power(int b,int p)
{
if(p==0)
{
return 1;
}
else
{
result=b*(power(b,p-1));
}
}
void main()
{
int b,p;
int result;
clrscr();
printf("Enter value of base: ");
scanf("%d",&b);
printf("Enter value of power: ");
scanf("%d",&p);
result=power(b,p);
printf("%d to the power of %d is: %d\n",b,p,result);
getch();
}
Output:

AIM: C PROGRAM TO CALCULATE SUM OF ALL DIGITS


USING RECURSION
Given a number and we have to sum of all digits using C language
recursion function in C language.
for example:
Input number: 1230
Output:
Sum of all digits: 6
Program:
#include<stdio.h>
#include<conio.h>
int digits(int n)
{
static int sum=0;
if(n>0)
{
sum=sum + (n%10);
digits(n/10);
}
else
{
return sum;
}
}
int main()
{
int n,sum;
clrscr();
printf("Enter a positive integer number: ");
scanf("%d",&n);
sum=digits(n);
printf("Sum of all digits are: %d\n",sum);
getch();
}
Output:

AIM: C PROGRAM TO PRINT FIBONACCI SERIES FOR


FIRST N ELEMENTS USING RECURSION.
#include<stdio.h>
#include<conio.h>
int fibonacci(int);
void main ()
{
int n,f;
clrscr();
printf("Enter the value of n : ");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
Output:

ADVANTAGES OF 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 OF 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 what 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
1. 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.
2. 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" 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
that of the main memory.
3. 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.
4. 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.

SUMMERY

Storage Declaration Storage Default Initial Scope Lifetime


Class Value

auto Inside a Memory Unpredictable Within the Within the


function/block function/block function/block
register Inside a CPU Garbage Within the Within the
function/block Registers function/block function/block

extern Outside all Memory Zero Entire the file program


functions and other files. runtime

Static Inside a Memory Zero Within the program


(local) function/block function/block runtime

Static Outside all Memory Zero Global program


(global) functions runtime

BASIC PROGRAM OF USE OF STORAGE CLASSES:

#include<stdio.h>
#include<conio.h>
static int a = 5;
void main()
{
static int b=10;
register i = 15;
auto d = 20;
clrscr();
printf("Value of static global variable a is : %d",a);
printf("\nValue of static local variable b is : %d",b);
printf("\nValue of register variable i is : %d",i);
printf("\nValue of auto global variable d is : %d",d);
getch();
}
Output:
Value of static global variable a is :5
Value of static local variable b is :10
Value of register variable i is :15
Value of auto global variable d is : 20

You might also like