0% found this document useful (0 votes)
6 views88 pages

Unit III - Part1 Function

The document outlines the fundamentals of programming in C, focusing on the concept of functions, including user-defined and library functions, parameter passing, recursion, storage class, and pointers. It explains the structure and purpose of functions, the need for user-defined functions, and the advantages of using functions for code reusability and organization. Additionally, it covers function declarations, definitions, calling functions, and the scope of variables, providing examples and categories of functions.

Uploaded by

Tanishq Ikhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views88 pages

Unit III - Part1 Function

The document outlines the fundamentals of programming in C, focusing on the concept of functions, including user-defined and library functions, parameter passing, recursion, storage class, and pointers. It explains the structure and purpose of functions, the need for user-defined functions, and the advantages of using functions for code reusability and organization. Additionally, it covers function declarations, definitions, calling functions, and the scope of variables, providing examples and categories of functions.

Uploaded by

Tanishq Ikhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Course: Fundamentals of

Programming

Course Code: 24CS01TP0101

UNIT III

P r o f . N I K I TA K ATA R I YA

D E PA R T M E N T O F C S E

R A M D E O B A B A U N I V E R S I T Y, N A G P U R
Contents
➢Concept of functions
➢User defined and Library Functions
➢ Parameter passing
➢Recursion
➢Storage class
➢Pointers
Function
➢A function is a block of code that performs a particular task.
➢There are many situations where we might need to write same line of
code for more than once in a program. This may lead to unnecessary
repetition of code, bugs and even becomes boring for the programmer.
➢So, C language provides an approach in which you can declare and
define a group of statements once in the form of a function and it can
be called and used whenever required.
➢These functions defined by the user are also know as User-defined
Functions.
➢A function can also be referred as a method or a sub-routine or a
procedure, etc.
Function
➢A function is a group of statements that together perform a task. Every C
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
➢You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division is
such that each function performs a specific task.
➢A function declaration tells the compiler about a function's name, return
type, and parameters. A function definition provides the actual body of the
function.
➢The C standard library provides numerous built-in functions that your
program can call.
➢For example, strcat() to concatenate two strings, memcpy() to copy one
memory location to another location, and many more functions.
Introduction
➢Every function in the program is supposed to perform a well defined task. Therefore,
the program code of one function is completely insulated from that of other functions.

➢Every function has a name which acts as an interface to the outside world in terms of
how information is transferred to it and how results generated by the function are
transmitted back from it.

In the fig, main() calls another function, func1() to perform a well defined task.
Introduction
➢It is not necessary that the main() can call only one function, it can call
as many functions as it wants and as many times as it wants.

➢For example, a function call placed within a for loop, and may call the
same function multiple times until the condition holds true.

➢It is not that only the main() can call another functions. Any function can
call any other function.
Introduction
➢main() is known as the calling function and func1() is known as the
called function.

➢When the compiler encounters a function call, instead of executing the


next statement in the calling function, the control jumps to the
statements that are a part of the called function.

➢After the called function is executed, the control is returned back to


the calling program.
Types of C function
C functions can be classified into two categories,
1. Library functions - these are those functions which are already
defined in C library, example printf(), scanf(), strcat() etc. You just
need to include appropriate header files to use these functions.
These are already declared and defined in C libraries. Library
functions are not required to be written by us.

2. A User-defined functions - these are those functions which are


defined by the user at the time of writing program. These functions
are made for code reusability and for saving time and space. User-
defined functions has to be developed by the user at the time of
writing a program. A user-defined functions can later become a part
of the program library. main() is an example of user-definedfunctions
Types of C function
Advantage of functions in C
➢By using functions, we can avoid rewriting same logic/code
again and again in a program.
➢We can call C functions any number of times in a program
and from any place in a program.
➢We can track a large C program easily when it is divided
into multiple functions.
➢Reusability is the main achievement of C functions.
➢However, Function calling is always a overhead in a C
program.
NEED FOR USER-DEFINED
FUNCTIONS
• Every program must have a main function.
• It is possible to code any program utilizing only main function, but it
leads to a number of problems.
• The program may become too large and complex and as a result
the task of debugging, testing, and maintaining becomes
difficult.
• If a program is divided into functional parts, then each part
may be independently coded and later combined into a single
unit.
• These subprograms called ‘functions’ are much easier to
understand, debug, and test.
NEED FOR USER-DEFINED
FUNCTIONS
• There are times when some types of operation or calculation is
repeated at many points through out a
program.
• In such situations, we may repeat the program statements
whenever they are needed.
• Another approach is to design a function that can be called and
used whenever required this saves both time and space.
FUNCTION
Terminology of Functions
➢A function, f that uses another function g, is known as the calling function
and g is known as the called function.

➢The inputs that the function takes are known as arguments.

➢When a called function returns some result back to the calling function, it
is said to return that result.

➢The calling function may or may not pass parameters to the called
function. If the called function accepts arguments, the calling function will
pass parameters, else not.

➢main() is the function that is called by the operating system and therefore,
it is supposed to return the result of its processing to the operating system.
ELEMENTS OF USER-DEFINED FUNCTIONS
There are three elements related to functions
– Function definition
– Function call
– Function declaration
➢ The function definition is an independent program module that is specially
written to implement the requirements of the function
➢ To use this function we need to invoke it at a required place in the
program. This is known as the function call.
➢ The program that calls the function is referred to as the calling program or
calling function.
➢ The calling program should declare any function that is to be used later in
the program. This is known as the function declaration or function
prototype.
Defining a Function
The general form of a function definition in C programming
language is as follows −

return_type function_name( parameter list )


{
body of the function
}
Defining a Function
A function definition in C programming consists of a function header and
a function body. Here are all the parts of a function −
◦ Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
◦ Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
◦ Parameters − A parameter is like a placeholder. When a function is invoked,
you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
◦ Function Body − The function body contains a collection of statements that
define what the function does.
Example
Given below is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum value between the two −

/* function returning the max between two numbers */


int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Function Declarations
➢A function declaration tells the compiler about a function name and how to
call the function. The actual body of the function can be defined separately.
➢A function declaration has the following parts −
return_type function_name( parameter list );
➢For the above defined function max(), the function declaration is as follows
int max(int num1, int num2);
➢Parameter names are not important in function declaration only their type is
required, so the following is also a valid declaration −
int max(int, int);
➢Function declaration is required when you define a function in one source file
and you call that function in another file. In such case, you should declare the
function at the top of the file calling the function.
Calling a Function
➢While creating a C function, you give a definition of what the function
has to do. To use a function, you will have to call that function to
perform the defined task.
➢When a program calls a function, the program control is transferred to
the called function.
➢A called function performs a defined task and when its return
statement is executed or when its function-ending closing brace is
reached, it returns the program control back to the main program.
➢To call a function, you simply need to pass the required parameters
along with the function name, and if the function returns a value, then
you can store the returned value.
C - Scope Rules
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 −
1. Inside a function or a block which is called local variables.
2. Outside of all functions which is called global variables.
3. In the definition of function parameters which are
called formal parameters.
Local Variables
Variables that are declared inside a function or block are called local
variables.
They can be used only by statements that are inside that function or
block of code.
Local variables are not known to functions outside their own.
The following example shows how local variables are used. Here all
the variables a, b, and c are local to main() function.
Global Variables
Global variables are defined outside a function, usually on top of the
program.
Global variables hold their values throughout the lifetime of your
program and they can be accessed inside any of the functions defined
for the program.
A global variable can be accessed by any function.
That is, a global variable is available for use throughout your entire
program after its declaration.
The following example shows how local variables and global variables are used. Here
the variables a, b, and c are local to main() function and g is global variable.
Formal Parameters
Formal parameters, are treated as local variables with-in a
function and they take precedence over global variables.
Passing Arguments to a function
➢Arguments are the values specified
during the function call, for which
the formal parameters are declared
while defining the function.
➢It is possible to have a function
with parameters but no return type.
➢It is not necessary, that if a
function accepts parameter(s), it
must return a result too.
Passing Arguments to a function
➢While declaring the function, we have
declared two parameters a and b of
type int. Therefore, while calling that
function, we need to pass two
arguments, else we will get compilation
error.
➢And the two arguments passed should
be received in the function definition,
which means that the function header in
the function definition should have the
two parameters to hold the argument
values.
➢These received arguments are also
known as formal parameters.
➢The name of the variables while
declaring, calling and defining a function
can be different.
Returning a value from function
➢A function may or may not return a
result. But if it does, we must use
the return statement to output the
result.
➢return statement also ends the
function execution, hence it must be
the last statement of any function. If
you write any statement after
the return statement, it won't be
executed.
➢The data type of the value returned
using the return statement should be
same as the return type mentioned at
function declaration and definition. If
any of it mismatches, you will get
compilation error.
Return Statement
➢The return statement is used to terminate the execution of a function and return control
to the calling function. When the return statement is encountered, the program execution
resumes in the calling function at the point immediately following the function call.

➢Programming Tip: It is an error to use a return statement in a function that has void as its
return type.

➢A return statement may or may not return a value to the calling function. The syntax of
return statement can be given as

➢ return <expression> ;

➢Here expression is placed in between angular brackets because specifying an expression


is optional. The value of expression, if present, is returned to the calling function.
However, in case expression is omitted, the return value of the function is undefined.
Return Statement
➢Programmer may or may not place the expression within parentheses.

➢By default, the return type of a function is int.

➢For functions that has no return statement, the control automatically


returns to the calling function after the last statement of the called
function is executed.
Example
#include<stdio.h>
➢ A function is a self void printline()
contained block of {
code that performs a int i;
particular task for(i=1; i<40; i++)
➢ Once a function has been printf("-");
designed and packed, it can printf("\n");
}
➢ be treated as a ‘black box’ void main()
that takes some data from {
the main program and printline();
returns a value printf("This illustrated the use of C functions \n");
➢ The inner details are invisible to printline();
the rest of the program }
WAP to accept any numbers from the user and return it to the
calling function. Here the calling function will print the entered
number.
CALLING A FUNCTION
• Afunction can be called by simply using the function name in astatement
• When the function encounters a function call,the control is transferred to
the function mul(x,y)
void main()
{
int p;
p = mul(10,5);
printf("%d\n", p);
}
int mul(int x,inty)
{
int p; /*local variables*/
p = x * y;/* x = 10, y = 5*/
return(p);
}
Program that uses Function
Write a program using functions to add two numbers

#include<stdio.h>
// FUNCTION DEFNITION
int sum(int a, int b);// FUNCTION DECLARATION int sum ( int a, int b)
void main() {
{ // FUNCTION BODY
int num1, num2, total = 0; return (a + b);
printf(“\n Enter the first number : “); }

scanf(“%d”, &num1);
printf(“\n Enter the second number : “);
scanf(“%d”, &num2);
total = sum(num1, num2); // FUNCTION CALL
printf(“\n Total = %d”, total);
}
CATEGORY OF FUNCTIONS
➢ Category 1: Functions with no arguments and no return values
➢ Category 2: Functions with arguments and no return values
➢ Category 3: Functions with arguments and one return values
➢ Category 4: Functions with no arguments but return a value
➢ Category 5: Functions that return multiple values
NO ARGUMENTS AND NO
RETURN VALUES
➢ When a function has no arguments, it does not receive
any data from the calling function
➢ When it does not return a value, the calling function
does not receive any data from the called function
➢ There is no data transfer between the calling function
and the called function
➢ There is only a transfer of control but not data
EXAMPLE
#include<stdio.h>
#include<conio.h> OUTPUT:
void add(void); Enter two number:3
void main() //calling function 4
{
add(); Sum is:7
}
void add() //called function
{
int a,b,c;
printf("\nEnter two number:");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nSum is:%d",c);
}
ARGUMENTS BUT NO
RETURN VALUES
➢ The calling function read data from the terminal and pass it on to
the called function.
➢ It is a one way data communication, i.e. the called program
receives data from calling program but it does not return any
value to the calling program.
➢ This approach is wiser because the calling function can check for the
validity of data, if necessary, before it is handed over to the called
function.
➢ Called function with arguments
➢ value(p,r,n)
ARGUMENTS BUT NO
RETURN VALUES
➢The function call
value(500,0.12,5)
➢Would send the value 500, 0.12, 5 to the function
value(float p, float r, int n)
➢and assign 500 to p, 0.12 to r and 5 to n
➢The values 500, 0.12, 5 are the actual arguments The
arguments p, r, n are the formal arguments
➢The actual and formal arguments should match in number,
type, and order
➢The values of actual arguments are assigned to the formal
arguments on a one to one basis
ARGUMENTS BUT NO
RETURN VALUES
➢ If the actual arguments are more than the formal arguments, the extra
actual arguments are discarded

➢ If the actual arguments are less than the formal arguments, the
unmatched formal arguments are initialized to some garbage values
➢ No error message will be generated
➢ The formal arguments must be valid variable names
➢ The actual arguments my be variable names, expression, or
constants

➢ When a function call is made, only a copy of the values of actual


arguments is passed into the called function
EXAMPLE
#include <stdio.h> void add(int x, int y)
#include<conio.h> //function with arguments
void add(int, int); {
void main() int z;
{ z=x+y;
int a,b; printf("\nSum is:%d",z);
printf("\nEnter two number:"); }
scanf("%d%d",&a,&b);
add(a,b); OUTPUT:
} Enter two number:2
4

Sum is:6
ARGUMENTS WITH RETURN
VALUES
➢ Here data transfer take place between the calling function
and the called function as well as between called function and
calling function .
➢ It is a two way data communication, i.e. the called program
receives data from calling program and it return some value to
the calling program.
➢ A self-contained and independent function should behave like
a ‘black box’ that receives a predefined form of input and
outputs a desired value
EXAMPLE
#include <stdio.h> int int add(int x, int y)
add(int, int); {
void main() int z;
{ z=x+y/3;
return(z);
int a,b; int
}
c;
printf("\nEnter two number:");
OUTPUT:
scanf("%d%d",&a,&b); Enter two number:6 7
c=add(a,b); printf("\nSum
is:%d",c); Sum is:13
}
TASK Write a function to find if the greater number out of
two or equal. This function returns int values. Check
these values in the main function and print the answer
NO ARGUMENTS BUT
RETURNS A VALUE
There could be occasions where we may need a design
functions that may not take any arguments but returns a value to
the calling function.
Example
#include<stdio.h>
int get_number(void);
int main()
{
int m =get_number();
printf(“%d”,m);
}
int get_number(void)
{
int number; scanf(“%d”, &number);
return(number);
}
Methods to pass arguments
Arguments can generally be passed to functions in one of the two ways:
(a) sending the values of the arguments: CALL BY VALUE
(b) sending the addresses of the arguments: CALL BY REFERENCE
Call by value
➢ ‘value’ of each of the actual
arguments in the calling function
is copied into corresponding
formal arguments of the called
function
➢ changes made to the formal
arguments in the called function
have no effect on the values of
actual arguments in the calling
function
Call by value
Program to swap two numbers using call by value

Output
TASK Program to add two numbers using call by
value and display the values in calling and
called function
Call by Reference
➢ The addresses of actual arguments in the calling
function are copied into formal arguments of the called
function.
➢ Using these addresses we would have an access to the
actual arguments and hence we would be able to
manipulate them.
➢ Using a call by reference intelligently we can make a
function return more than one value at a time, which is
not possible ordinarily.
Call by Reference
a b
10
20 20
10
65000 60000

x y
65000 60000

t
10
20
TASK Program to add 10 to a number using call by
reference and display the values in calling
and called function
Call by reference
WAP to read the radius value from user and
calculate the area and perimeter of circle using Call by refernece
What is the output?
What will be the output?
What will be the output?
FUNCTIONS THAT RETURN
MULTIPLE VALUES
➢ A return statement can return only one value.
➢ To get more information from a function, we can achieve
this in C using the arguments not only to receive
information but also to send back information to the
calling function.
➢ The arguments that are used to “send out”
information are called output parameters.
➢ The mechanism of sending back information through
arguments is achieved using what are known as the address
operator (&) and indirection operator (*).
Example PROGRAM
void mathoperation(int x, int y, int *s, int *d); • x and y – input arguments
main()
• s and d – output arguments
{
int x = 20, y = 10, s, d; • We pass
mathoperation(x,y,&s,&d); – Value of x to a
printf("s=%d\n d=%d\m", s,d); – Value of y to b
– Address of S to sum
}
– Address of d to diff
void mathoperation(int a, int b, int*sum, int
*diff) • The body of the function
{ when executed add the
*sum =a+b; value and find difference
*diff =a-b; and store the result in
} memory location pointed
by sum and diff.
FUNCTIONS THAT RETURN
MULTIPLE VALUES
➢ The indirection operator * indicates the variables are to store
addresses, not actual values of variables
➢ The operator * is known as indirection operator because it
gives an indirect reference to a variable through its address
➢ The variables *sum and *diff are known as pointers and
sum and diff as pointer variables
➢ They are declared as int, they can point to locations of int type
data
➢ The use of pointer variables as actual parameters for
communicating data between functions is called “pass
by pointers” or “call by address or reference”.
MORE EXAMPLE FOR REFERENCE
1. Function with no arguments and no
return value
Such functions can either be used to display information or
they are completely dependent on user inputs.
1. Function with no arguments and no return
value
2. Function without argument and with return value
2. Function without argument and with return value
3. Function with argument and without
return value
[Link] with argument and without return
value
4. Function with argument and with return
value
4. Function with argument and with return
value
Call by value and Call by
reference in C
There are two methods to pass the data into the function in C language
◦ call by value
◦ call by reference
Call by value in C
➢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.
➢The actual parameter is the argument which is used in
the function call whereas formal parameter is the
argument which is used in the function definition.
Call by value in C
Call by Value Example: Swapping the values of the two variables
Call by reference in C
In call by reference, the address of the variable is passed into the
function call as the actual parameter.
The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal
parameters and actual parameters.
All the operations in the function are performed on the value stored at
the address of the actual parameters, and the modified value gets
stored at the same address.
Call by reference in C
Call by reference Example: Swapping the values of the two variables

You might also like