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

Unit - 05 - Functions - 02

The document provides an overview of functions in C programming, detailing their structure, types, and advantages. It explains the concept of functions, including function definition, declaration, and calling, as well as different types of functions based on arguments and return values. Additionally, it covers call by value, call by reference, and recursion, illustrating these concepts with code examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit - 05 - Functions - 02

The document provides an overview of functions in C programming, detailing their structure, types, and advantages. It explains the concept of functions, including function definition, declaration, and calling, as well as different types of functions based on arguments and return values. Additionally, it covers call by value, call by reference, and recursion, illustrating these concepts with code examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit 5: Functions Marks:

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……)

int sum (int x, int y)


It has three main parts
1. The name of the function i.e. sum
2. The list parameters of the function enclosed in parenthesis
3. Return value type i.e. int

 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……);

the functions sum() is declared in the line.

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.”

Advantages of using functions:


There are many advantages in using functions in a program they are:
1. It makes possible top down modular programming. In this style of programming, the high level
logic of the overall problem is solved first while the details of each lower level functions is
addressed later.
2. The length of the source program can be reduced by using functions at appropriate places.
3. It becomes easier to debug the errors and for testing.
4. A function may be reused later by many other programs this means that a c programmer can use
function written by others, instead of starting over from scratch.

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. Functions with arguments and no return value.


A C function with arguments can perform much better than previous function type. This type of
function can accept data from calling function. In other words, you send data to the called function
from calling function but you cannot send result data back to the calling function. Rather, it
displays the result on the terminal. But we can control the output of function by providing various
values as arguments. Let‟s have an example to get it better.
1. #include<stdio.h>

2. #include<conio.h>

3. void add(int x, int y) // formal parameters

4. {

5. int result;

6. result = x+y;

7. printf("Sum of %d and %d is %d.\n\n",x,y,result);

8. }

9. void main()

10. {

11. void add(int , int )

12. add(30,15); // actual arguments

13. add(63,49);

5
14. add(952,321);

15. getch();

16. }

Logic of the function with arguments and no return value.


Source Code Explanation:
This program simply sends two integer arguments to the UDF “add()” which, further, calculates its
sum and stores in another variable and then prints that value.
Line 3-8: This C code block is “add()” which accepts two integer type arguments. This UDF also
has a integer variable “result” which stores the sum of values passed by calling function (in this
example “main()”). And line no. 7 simply prints the result along with argument variable values.

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”.

3. Functions with arguments and return value.


This type of function can send arguments (data) from the calling function to the called function and
wait for the result to be returned back from the called function back to the calling function. And
this type of function is mostly used in programming world because it can do two way
communications; it can accept data as arguments as well as can send back data as return value. The
data returned by the function can be used later in our program for further calculations.
1. #include<stdio.h>

2. #include<conio.h>

3. int add(int x, int y)

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);

14. printf("Result %d.\n\n",add(30,55));

15. printf("Result %d.\n\n",z);

16. getch();

17. }

Logic of the function with arguments and return value.


Source Code Explanation:
This program sends two integer values (x and y) to the UDF “add()”, “add()” function adds these
two values and sends back the result to the calling function (in this program to “main()” function).
Later result is printed on the terminal.
Line No. 3-8: Look line no. 3 carefully, it starts with int. This int is the return type of the function,
means it can only return integer type data to the calling function. If you want any function to return
character values then you must change this to char type. On line no. 7 you can see return statement,
return is a keyword and in bracket we can give values which we want to return. You can assign any
integer value to experiment with this return which ultimately will change its output.
Line No. 9-17: In this code block only line no. 13, 14 and 15 is important. We have declared an
integer “z” which we used in line no. 13. Why we are using integer variable “z” here? You know
that our UDF “add()” returns an integer value on calling. To store that value we have declared an
integer value. We have passed 952, 321 to the “add()” function, which finally return 1273 as result.
This value will be stored in “z” integer variable. Now we can use “z” to print its value or to other
function.
You will also notice some strange statement in line no. 14. Actually line no. 14 and 15 does the
same job, in line no. 15 we have used an extra variable whereas on line no. 14 we directly printed
the value without using any extra variable.

4. Functions with no arguments but returns value.


We may need a function which does not take any argument but only returns values to the calling
function then this type of function is useful. Take a look.
1. #include<stdio.h>

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. }

10. void main()

11. {

12. int z;

13. clrscr();

14. z = send();

15. printf("\nYou entered : %d.", z);

16. getch();

17. }

Functions with no arguments and return values.

Source Code Explanation:


In this program we have a UDF which takes one integer as input from keyboard and sends back to
the calling function. This is a very easy code to understand if you have followed all above code
explanation.

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 ;

printf ( "\nEnter any number " ) ;


scanf ( "%d", &a ) ;

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 ) ;
}

And here is the output for four runs of the program


Enter any number 5
Factorial value = 120
The value of a is 5, main( ) would call rec( ) with 5 as its actual argument, and rec( ) will send
back the computed value. But before sending the computed value, rec( ) calls rec( ) and waits for a
value to be returned. It is possible for the rec( ) that has just been called to call yet another rec( ),
the argument x being decreased in value by 1 for each of these recursive calls. We speak of this
series of calls to rec( ) as being different invocations of rec( ). These successive invocations of
the same function are possible because the C compiler keeps track of which invocation calls
which. These recursive invocations end finally when the last invocation gets an argument value of
1, which the preceding invocation of rec( ) now uses to calculate its own f value and so on up the
ladder. So we might say what happens is,

rec ( 5 ) returns ( 5 times rec ( 4 ),


which returns ( 4 times rec ( 3 ),
which returns ( 3 times rec ( 2 ),
which returns ( 2 times rec ( 1 ),
which returns ( 1 ) ) ) ) )

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 –

1. Local variables are defined inside a function or a block

2. Global variables are outside all functions

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

You might also like