You are on page 1of 22

Programming in C [BCA I Sem 2014] Unit IV (1)

BCA I Year Semester I


PROGRAMMING IN C
[BCA111]

Unit IV
Functions - defining and accessing a function, function arguments, call by value, call
by reference, calling functions with arrays, external, state and register variables,
scope of variables, local and global variables, type conversion, block structure,
recursion.
=====================================================================

Introduction to Functions
A function is a block of code that performs a particular task. There are times
when we need to write a particular block of code for more than once in our
program. This may lead to bugs and irritation for the programmer.
C language provides an approach in which you need to declare and define a
group of statements once and that can be called and used whenever required.
This saves both time and space.
C functions can be classified into two categories,
Library functions
User-defined functions
Library functions are those functions which are defined by 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.
User-defined functions are those functions which are defined by the user at
the time of writing program. Functions are made for code reusability and for
saving time and space.
Advantage of function
o It provides modularity to the program.
o Easy code Reusability. You just have to call the function by its name to
use it.
o In case of large programs with thousands of code lines, debugging and
editing becomes easier if you use functions

Programming in C [BCA I Sem 2014] Unit IV (2)

Declaration of function
return-type function-name (parameter-list);
A function declaration consists of 4 parts.
1
2
3
4
5

return-type
function name
parameter list
function statement
a return statement

Definition of function
return-type function-name (parameter-list)
{
function-body ;
return statement;
}

//This is function header

Return type
Return type specifies the type of value (int, float, char, double) that
function is expected to return to the program calling the function.
Function name
Function name specifies the name of the function. The function name is
any valid C identifier and therefore must follow the same rule of formation as
other variables in C.
Parameter List
The parameter list declares the variables that will receive the data sent
by calling program. They often referred to as formal parameters. These
parameters are also used to send values to calling program.

Programming in C [BCA I Sem 2014] Unit IV (3)

Function Body
The function body contains the declarations and the
statement(algorithm) necessary for performing the required task. The body is
enclosed within curly braces { }and consists of three parts.
o Local variable declaration.
o function statement that performs the tasks of the function.
o a return statement that return the value evaluated by the
function.
Functions and Arguments
Arguments are the values specified during the function call, for which
the formal parameters are declared in the function.
The function can be categorized in three forms:o The function with no arguments and no return.
o The function with arguments but no return.
o The function with arguments and return.

Programming in C [BCA I Sem 2014] Unit IV (4)

1. Function with no arguments and no return


The function can be called (access, invoke, function calling) by writing its name
and parenthesis.
function_name();
Whenever a function is called the control is transfer to the specified function
the whole function is executed when the function is completed the control will
be returned to calling points.
The function is declared once but the function can be used (called) as many
times as required. The function can be called another function in program.
void print();
void main()
{
Statement1;
...
Statement2;
print();
Statement3;
...
Statement4;
}
void print()
{
Statement11;
...
Statement12;
printf("LMC);
Statement13;
...
Statement14;
}

4
2

The function declaration order may be different than order of function calling
means function can be called in any order.

Programming in C [BCA I Sem 2014] Unit IV (5)

2. Function with arguments and no return


In this type of functions the information is send from calling points which is
used within the function. The arguments at the calling point are called actual
arguments and the arguments at the declaration are called formal arguments.
void add(int ,int);
void main()
{
Statement1;
...
Statement2;
add(2,4);
Statement3;
...
Statement4;
}

//actual argument

void print(int a,int b)


S//formal argument
{
Statement11;
...
Statement12;
printf("Add %d and %d is %d,a,b,a+b);
Statement13;
...
Statement14;
}
When this type of function is called the function is transferred to functions
header and also the value of actual argument is copied into the formal
arguments then the execution of function is complied when function is
complete its execution the control transfer back to its calling points.
Note:
1. The no of actual arguments must be equal to no of formal arguments.
2. The type of actual arguments should be same of formal arguments
correspondingly.
3. The actual arguments of function call may be variable, constants or an
expression

Programming in C [BCA I Sem 2014] Unit IV (6)

Example
fun(5, 6)
fun (5, 2.9, a)
fun (j, k+2, +)

wrong
right
right

3. Function with arguments and with return


The type is the functions returns values type. If no type is mentioned then C
compiler by default take it as integer type. The function of this type must have
at lest one return statements. When function is accessed the control is transfer
to function header. The values of actual parameter is transferred to formal
parameters then whole function is executed when return statement is
encountered within function than control is transferred back to calling point
and the return value is placed at access point.
int add(int ,int);
void main()
{
Statement1;
...
Statement2;
tot = add(2,4);
Statement3;
...
Statement4;
}
int print(int a,int b)
{
Statement11;
...
Statement12;
c = a+b;
Statement13;
...
Statement14;
return c;
}

//actual argument

//formal argument

Programming in C [BCA I Sem 2014] Unit IV (7)

Note:
o Return value may be constant, variable or an expression
o The return statements value must be same type of the functions types
o The return statement without value can be used only in void type
functions.
o A single function may have one or more return statements. Whenever
the return statement is executed the control is transferred back to
calling point and the specified value is put there.

Programming in C [BCA I Sem 2014] Unit IV (8)

Call by Value and Call by Reference


In C language call by value and call by reference (also known as pass-byvalue and pass-by-reference). These methods are different ways of passing (or
calling) data to functions.
Call by Value
When we pass variable to function, it copies value of actual argument to
formal argument.
Example
int add(int ,int);
void main()
{
int a,b;
tot = add(a,b);
}
int print(int a,int b)
{
int c;
c = a+b;
return c;
}

a and b are
local to main

ACTUAL
VARIABLE

a and b are
local to print
FORMAL
VARIABLE

Call by Reference
When we pass address of variable to function, it copies value of actual
argument to formal argument.
Example
int add(int ,int);

7
510

void main()
{
int a,b;
tot = add(&a,&b);

4
804

510

804

*a

*b

a and b are
local to main
ACTUAL
VARIABLE

Programming in C [BCA I Sem 2014] Unit IV (9)

}
int print(int *a,int *b)
{
int c;
c = *a+*b;
return c;
}

*a and *b are
local to print
a & b is pointer

FORMAL
VARIABLE

Passing array to functions


In C programming, a single array element or an entire array can be passed to a
function. Also, both one-dimensional and multi-dimensional array can be
passed to function as argument.
If you want to pass a single-dimension array as an argument in a function, you
would have to declare function formal parameter in one of following two ways
and both the declaration methods produce similar results because each tells
the compiler that an integer pointer is going to be received. Similar way you
can pass multi-dimensional array as formal parameters.
While passing arrays to the argument, the name of the array is passed as an
argument (i.e. starting address of memory area is passed as argument).

Programming in C [BCA I Sem 2014] Unit IV


(10)

Syntax
First

int search(int valsrc, int *); //declaration


Second
int search(int, int []);
//declaration
.
.
.
void main()
{
.
.
pos = search(tot,arr);
//call
.
}
First

void search(int valsrc, int *ap)


{
.
.
.
}

//definition

Second
void search(int valsrc, int ap[])
{
.
.
.
}
Example
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main ()

arr

500

500

500

ap

static pointer

Programming in C [BCA I Sem 2014] Unit IV


(11)

/* an int array with 5 elements */


int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );

return 0;

int getAverage( int *bal, int tot )


{
int i,s=0;
for(i=0;i<tot;i++)
{
s+=bal[i];
}
return s/tot;
}
Function declaration
Void fun(int ,int );
Void fun(int ,float );
Void fun(int *,float );
Void fun(int *,float *);

Function call
fun(a,b)
fun(a,f)
fun(&a,f)
fun(&a,f)

Function Definition
Void fun(int x,int y){}
Void fun(int x,float y){}
Void fun(int *xp,float y){}
Void fun(int *xp,float *yp){}

Programming in C [BCA I Sem 2014] Unit IV


(12)

Recursion
Recursion is a programming technique that allows the programmer to express
operations in terms of themselves. In C, this takes the form of a function that
calls itself. A useful way to think of recursive functions is to imagine them as a
process being performed where one of the instructions is to "repeat the
process"(chaining of function/ Nesting of function).
This makes it sound very similar to a loop because it repeats the same code,
and in some ways it is similar to looping. On the other hand, recursion makes it
easier to express ideas in which the result of the recursive call is necessary to
complete the task. Of course, it must be possible for the "process" to
sometimes be completed without the recursive call.
Recursion is a special case of this process, where a function calls itself.
Example 1
main()
{
printf(We are in Main!);
main();
}
[main() called]
We are in Main!
[main() called]
We are in Main!

[main() called]
We are in Main!
Example 2 Factorial of number
int factorial (int n)
{
if ( n < 0)
return -1; /*Error*/
if (n == 0)
return 1; /*Terminating condition*/

Programming in C [BCA I Sem 2014] Unit IV


(13)

return (n * factorial (n -1));


factorial(5)
5*24 120
5 * factorial(5-1)
5 * factorial(4)
4*6 24
4 * factorial(4-1)
4 * factorial(3)
3*2 6
3 * factorial(3-1)
3 * factorial(2)
2*1 2
2 * factorial(2-1)
2 * factorial(1)
1*1 1
1 * factorial(1-1)
1 * factorial(0)
1 1
factorial(0)is 1

Example 3 Multiplication of two numbers


#include<stdio.h>
int multiply(int,int);
int main()
{
int a,b,product;
printf("Enter any two integers: ");
scanf("%d%d",&a,&b);
product = multiply(a,b);
printf("Multiplication of two integers is %d",product);
}

return 0;

Programming in C [BCA I Sem 2014] Unit IV


(14)

int multiply(int a,int b)


{
static int product=0,i=0;
if(i < a)
{
product = product + b;
i++;
multiply(a,b);
}
}

return product;

Advantages and Disadvantages of Recursion


Recursion is more elegant and requires few variables which make program
clean. Recursion can be used to replace complex nesting code by dividing the
problem into same problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also
difficult to debug the code containing recursion.

Programming in C [BCA I Sem 2014] Unit IV


(15)

Type Casting
Type casting is a way to convert a variable from one data type to another data
type. For example, if you want to store a long value into a simple integer then
you can type cast long to int. You can convert values from one type to another
explicitly using the cast operator as follows:
(type_name) expression
Consider the following example where the cast operator causes the division of
one integer variable by another to be performed as a floating-point operation:
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
When the above code is compiled and executed, it produces the following
result:
Value of mean: 3.400000
It should be noted here that the cast operator has precedence over division, so
the value of sum is first converted to type double and finally it gets divided by
count yielding a double value.
Type conversions can be implicit which is performed by the compiler
automatically, or it can be specified explicitly through the use of the cast
operator. It is considered good programming practice to use the cast operator
whenever type conversions are necessary.
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than
int or unsigned int are converted either to int or unsigned int. Consider an
example of adding a character in an int:

Programming in C [BCA I Sem 2014] Unit IV


(16)

#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
When the above code is compiled and executed, it produces the following
result:
Value of sum : 116
Here, value of sum is coming as 116 because compiler is doing integer
promotion and converting the value of 'c' to ascii before performing actual
addition operation.
Usual Arithmetic Conversion
The usual arithmetic conversions are implicitly performed to cast their values
in a common type. Compiler first performs integer promotion, if operands still
have different types then they are converted to the type that appears highest
in the following hierarchy:

Programming in C [BCA I Sem 2014] Unit IV


(17)

The usual arithmetic conversions are not performed for the assignment
operators, nor for the logical operators && and ||. Let us take following
example to understand the concept:
#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
When the above code is compiled and executed, it produces the following
result:
Value of sum : 116.000000
Here, it is simple to understand that first c gets converted to integer but
because final value is double, so usual arithmetic conversion applies and
compiler convert i and c into float and add them yielding a float result.

Programming in C [BCA I Sem 2014] Unit IV


(18)

Storage Class
Every variable and function in C programming has two properties: type and
storage class. Type refers to the data type of variable whether it is character or
integer or floating-point value etc.
There are 4 types of storage class:
1
2
3
4

Automatic
External
Static
Register

A storage class defines the scope (visibility) and life time of variables and/or
functions within a C Program.
Scope of Variable (ACTIVE): What region of the program a variable is actually
available for use? [Range of availability]
Longevity (ALIVE): refers to the period during which a variable retains a given
value during execution of program.
Variables are also categorized, depending on the place of their declaration,
Internal (local); declared within the particular function,
External (global); declared outside of any function,
1. Automatic Variables
(Private/ Local/ Internal)
auto is the default storage class for all local variables. They are created
when the function is called and destroyed automatically when function
is exited.
int Count;
auto int Month;
The example above defines two variables with the same storage class.
auto can only be used within functions, i.e. local variables. The keyword

Programming in C [BCA I Sem 2014] Unit IV


(19)

used for Automatic storage class is 'auto'. Keyword 'auto' are rarely
used.
#include<stdio.h>
#include<conio.h>
void main()
{
auto int a;
printf(%d,a)
}

auto int a;
or
int a;

Output:
1285
As seen above, the output is garbage value.
2. External Variables
(Public/ Global/ External)
Some applications it may be useful to have data which is accessible from
within any block and/or which remains in existence for the entire execution of
the program. Such variables are called global variables. The keyword used for
External storage class is 'extern'.
Default value of that variable is zero. Scope of that variable is global.
Variable is alive as long as the programs execution doesnt come to an end.
External variable can be declared outside all the functions or inside function
using 'extern' keyword.
Example 1
int a=10;
void main()
{
printf(%d,a);
}
int fun()
{
...
}
Output:
10

Local
variable
will
have
precedence over the global one.

Programming in C [BCA I Sem 2014] Unit IV


(20)

Example 2
void main()
{
printf(%d,a);
}
int a=10;
int fun()
{
...
}

a is a declared globally; but


cannot be accessed by main.
Because it
main()

is

declared

after

Now it is possible
void main()
{
extern int a;
printf(%d,a);
}
int a=10;
int fun()
{
...
}

a is a declared after main()


;globally; then we have to
declare
that
variable
with
extern
keyword
in
prior
function.

Output:
10
3. Static Variables
It persists until the end of program, and can be declared by keyword
static.
static int i;
It can be internal or external. If variable is static and internal than it is as
good as auto in case of its scope.
main()
{
int i;
auto int i;

Programming in C [BCA I Sem 2014] Unit IV


(21)

static int i;

Static variable is initialized only once, when program is compiled, and never
again.
void fun()
{
static int x = 3;
}
4. Register Variables
If we want to keep variable in register rather than to store in memory
(RAM). By this faster execution.
register int x = 3;
Note: It is request by programmer, that means C will automatically
convert register variable into non-register variable.

Storage

Default

Scope

Lifetime
Till the
Local to the
control
block in
remain in
auto
Memory Garbage(unpredictable)
which it is the block in
which it is
declared
declared
Till the
Local to the
control
block in
remain in
Register Garbage(unpredictable)
which it is the block in
register
declared
which it is
declared
Local to the
Value
block in
persist in
static
Memory
ZERO [0]
which it is
between
declared
function call
Alive and
Active till
extern Memory
ZERO [0]
Global
the program

Programming in C [BCA I Sem 2014] Unit IV


(22)

execution
does not
comes to
end