Unit - 05 - Functions - 02
Unit - 05 - Functions - 02
Marks :12
14
Unit - 04 Functions
1
5.1 Concept and need of Functions
4.1
A function is a self-contained block of statements that perform a logically isolated task of some
kind.
Or
A function is a self-contained block of statements that perform particular task of some kind.
A function in C language is a block of code that performs a specific task. It has a name and it is
reusable i.e. it can be executed from as many different parts in a C Program as required. It also
optionally returns a value to the calling program
Need of Function:
Every function has a unique name. This name is used to call function from “main()” function.
A function can be called from within another function.
A function is independent and it can perform its task without intervention from or interfering
with other parts of the program.
A function performs a specific task. A task is a distinct job that your program must perform as
a part of its overall operation, such as adding two or more integer, sorting an array into
numerical order, or calculating a cube root etc.
A function returns a value to the calling program. This is optional and depends upon the task
your function is going to accomplish. Suppose you want to just show few lines through
function then it is not necessary to return a value. But if you are calculating area of rectangle
and wanted to use result somewhere in program then you have to send back (return) value to
the calling function.
Like variables, function names and their types must be declared and defined before they can
be used in a program.
Structure of a Function
A general form of a C function looks like this:
return_type FunctionName (Argument1, Argument2, Argument3……)
{
Statement1;
Statement2;
Statement3;
}
An example of function.
int sum (int x, int y)
{
int result; //holds the answer that will be returned
result = x + y; //calculate the sum
return (result); //return the answer
}
Three basic elements that are required in order to make use of a user defined function
1. Function definition
2. Function call
3. Function declaration
Function Definition
The definition contains the actual code for the function i.e. logic of task that function will perform.
Here‟s the definition for sum( ) .
int sum (int x, int y)
{
2
int result; //holds the answer that will be returned
result = x + y; //calculate the sum
return (result); //return the answer
}
There are two main parts of the function. The function header and the function body.
Function Header
In the first line of the above code is called as function header.
return_type FunctionName (Argument1, Argument2, Argument3……)
return type specifies the type of value that the function is expected to return to the program
calling the function. If no return type is mentioned then default return type will be integer type.
If function is not returning anything then its return type is void.
The function name is any valid C identifier and therefore must follow the same rules of
formation as other variable names. Function name must be meaningful.
Formal parameter list declares the variables that will receive the data values sent by the calling
program. They serve as input data to the function. Here (int x, int y) is list of formal parameters.
If parameter list is empty then keyword void is used between parentheses. E.g. void printline
(void)
{
}
Even void printline () will work.
Function body contains statements that form logic of function. Body is written within { }.
return statement returns value back to calling function. Any number of return statements may
be present but a function can return only one value at a time.
Function Call
When the function is called, control is transferred to the first statement in the functions body. The
other statements in the function body are then executed, and when the closing brace is encountered,
control returns to the calling program.
A function can be called by using function name with list of actual parameter ( or arguments ) if
any enclosed in parenthesis. A semicolon terminates the call.
e.g. sum( 5 ,7);
Function Declaration
Like variables, all functions in a C program must be declared before they are called.
A general form of a C function declaration looks like this:
return_type FunctionName (Argument1, Argument2, Argument3……);
3
int sum(int, int);
The declaration tells the compiler that at some later point we plan to present a function called
sum(). The keyword int specifies that the function returns a value of integer data type, and the list
of parameters indicate that it takes 2 arguments of integer data type.
Notice that the functions declarations is terminated with a semicolon. It is a complete statement in
itself.
Function declarations are also called prototypes, since they provide a model or blueprint for the
function. They tell the compiler,” a function that looks like this is coming up later in the program,
so it‟s all right if you see references to it before you see the function itself.”
Types of functions:
A function may belong to any one of the following categories:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.
1. Functions with no arguments and no return value.
A C function without any arguments means you cannot pass data (values like int, char etc) to the
called function. Similarly, function with no return type does not pass back data to the calling
function.
e.g.
void main()
{
void add( void ); // function declaration, void means function will not return any data value
add(); // function call
getch();
}
void add( void ) // function definition
{
int x, y, sum;
printf(“Enter two values”);
scanf(“%d %d”, &x,&y);
sum = x+y;
printf(“Sum is %d”, sum);
}
The above C program example illustrates that how to declare a function with no argument and no return type
4
Logic of the functions with no arguments and no return value.
If function is not retuning anything then its return type is void.
As function is not retuning any value return statement is not necessary.
As no arguments are passed so list of parameters is empty.
Here functions takes its own values from user and perform addition and prints the result and
then control is returned back to calling function.
main() function has no control over add(),it cannot control its output. Whenever “main()” calls
“add()”, the result remains the same.
2. #include<conio.h>
4. {
5. int result;
6. result = x+y;
8. }
9. void main()
10. {
13. add(63,49);
5
14. add(952,321);
15. getch();
16. }
Line 9-16: This code block is a “main()” function but only line no. 12, 13, 14 is important for us
now. In these three lines we have called same function “add()” three times but with different values
and each function call gives different output. So, you can see, we can control function‟s output by
providing different integer parameters which was not possible in function type 1. This is the
difference between “function with no argument” and “function with argument”.
2. #include<conio.h>
4. {
5. int result;
6. result = x+y;
7. return(result);
8. }
9. void main()
6
10. {
11. int z;
12. clrscr();
13. z = add(952,321);
16. getch();
17. }
7
2. #include<conio.h>
3. int send()
4. {
5. int no1;
6. printf("Enter a no : ");
7. scanf("%d",&no1);
8. return(no1);
9. }
11. {
12. int z;
13. clrscr();
14. z = send();
16. getch();
17. }
CALL BY VALUE
The „value‟ of each of the actual arguments of the calling function is copied into corresponding
formal arguments of the called function. With this method the changes made to the formal
arguments in the called function have no effect on the values of actual arguments in the calling
function. example of call by value are shown below;
In this method the value of each of the actual arguments in the calling function is copied into
corresponding formal arguments of the called function. With this method the changes made to the
8
formal arguments in the called function have no effect on the values of actual argument in the
calling function. The following program illustrates this:
main ( )
{
int a = 10, b=20;
swapy (a,b);
printf ("\na = % d b = % d", a, b);
}
swapy (int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf ( "\n x = % d y = % d" , x, y);
}
The output of the above program would be; x = 20 y = 10 a =10 b =20
Note that values of a and b remain unchanged even after exchanging the values of x and y.
Remember that it is a copy of the value of the argument that is passed into a function. What occurs
inside the function has no effect on the variable used in the call.
CALL BY REFERENCE
In the second method the addresses of actual arguments in the calling function are copied in to
formal arguments of the called function. This means that using these addresses we would have an
access to the actual arguments and hence we would be able to manipulate them the following
program illustrates this.
main ( )
{
int a = 10, b =20,
swapv (&a, &b);
printf ("\n a = %d b= %d", a, b);
}
swapr (int *x, int *y)
{
int t;
t = *x
*x = *y;
*y = t;
}
The output of the above program would be a = 20 b =10
The swap( ) function is able to exchange the values of the two variables pointed to by x and y
because their addresses (not their values) are passed. Within the function, the contents of the
variables are accessed using standard pointer operations, and their values are swapped. Remember
that swap( ) (or any other function that uses pointer parameters) must be called with the addresses
of the arguments.
9
Recursion Function:
In C, it is possible for the functions to call themselves. A function is called „recursive‟ if a
statement within the body of a function calls the same function. Sometimes called „circular
definition‟, recursion is thus the process of defining something in terms of itself.
Let us now see a simple example of recursion. Suppose we want to calculate the factorial
value of an integer. As we know, the factorial of a number is the product of all the integers
between 1 and that number. For example, 4 factorial is 4 * 3 * 2 * 1. This can also be expressed as
4! = 4 * 3! where „!‟ stands for factorial. Thus factorial of a number can be expressed in the form of
itself. Hence this can be programmed using recursion.
main( )
{
int a, fact ;
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
rec ( int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
f = x * rec ( x - 1 ) ;
return ( f ) ;
}
10
11
Scope of Variables:
A scope is a region of a program. Variable Scope is a region in a program where a variable is
declared and used. So, we can have three types of scopes depending on the region where these are
declared and used –
Local Variables
Variables that are declared inside a function or a block are called local variables and are said to
have local scope. These local variables can only be used within the function or block in which
these are declared. We can use (or access) a local variable only in the block or function in which it
is declared. It is invalid outside it.
Local variables are created when the control reaches the block or function containg the local
variables and then they get destroyed after that.
#include <stdio.h>
void fun1()
{
/*local variable of function fun1*/
int x = 4;
printf("%d\n",x);
}
int main()
{
/*local variable of function main*/
int x = 10;
{
/*local variable of this block*/
int x = 5;
printf("%d\n",x);
}
printf("%d\n",x);
fun1();
}
Output
12
5
10
4
The value of the variable „x‟ is 5 in the block of code ({ }) defined inside the function „main‟ and
the value of this variable „x‟ in the „main‟ function outside this block of code ({ }) is 10. The value
of this variable „x‟ is 4 in the function „fun1‟.
Global Variables
Variables that are defined outside of all the functions and are accessible throughout the program
are global variables and are said to have global scope. Once declared, these can be accessed and
modified by any function in the program. We can have the same name for a local and a global
variable but the local variable gets priority inside a function.
#include <stdio.h>
/*Global variable*/
int x = 10;
void fun1()
{
/*local variable of same name*/
int x = 5;
printf("%d\n",x);
}
int main()
{
printf("%d\n",x);
fun1();
}
Output
10
5
You can see that the value of the local variable „x‟ was given priority inside the function „fun1‟
over the global variable have the same name „x‟.
13