FUNCTIONS

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 79

FUNCTIONS

• Defining a Function
• Accessing a function
• Function Prototypes
• Passing arguments to a function
• Recursion
• Storage classes in C
• Preprocessor
Benefits of functions
Divide and conquer
 Manageable program development
Software reusability-Use existing functions as building blocks for new programs
 Abstraction - hide internal details (library functions)
Avoid code repetition-The length of a source program can be reduced by using functions at appropriate places. This factor is
particularly critical with microcomputers where memory space is limited.
Debugging-It is easy to locate and isolate a faulty function for further investigations.
Functions are building blocks of C.
A function is a self-contained block of
statements that perform a coherent task of
some kind.
Every C program can be thought of as a
collection of these functions.
Function performs the same set of instructions
on different sets of data or at different portions
of a program.
 Function call analogy:
Boss asks worker to complete task
Worker gets information, does task, returns
result
Functions
Every C program starts with main()function
Additional functions are called or invoked when the program
encounters function names
Functions could be
Pre-defined library functions (e.g., printf, sin, tan) or
Programmer-defined functions (e.g., my_printf, area)
Functions
Perform a specific task
May take arguments
May return a single value to the calling function
May change the value of the function arguments (call by
reference)
Functions
Any C program contains at least one function.
If a program contains only one function, it must be main( ).
If a C program contains more than one function, then one
(and only one) of these functions must be main( ), because
program execution always begins with main( ).
There is no limit on the number of functions that might be
present in a C program.
Each function in a program is called in the sequence specified
by the function calls in main( ).
C functions can be classified into two categories, namely
1. Library functions and
2. User-defined functions.
library functions are commonly required functions grouped
together and stored in a library.
This library of functions is present on the disk and is
written for us by people who write compilers for us. Almost
always a compiler comes with a library of standard
functions.
Eg: printf() and scanf() belong to the category of library
functions.
A user-defined function has to be developed by the user at the
time of writing a program to perform a specific task.
main(),area(),volume() is an example of user-defined functions.
Common Library Functions
#include <math.h> #include <stdio.h>
 sin(x) // radians  printf()
 cos(x) // radians  fprintf()
 tan(x) // radians  scanf()
 atan(x)  sscanf()
 atan2(y,x)  ...
 exp(x) // ex
#include <string.h>
 log(x) // loge x  strcpy()
 log10(x) // log10 x  strcat()
 sqrt(x) // x  0  strcmp()
 pow(x, y) // xy  strlen()
 ...  ...
DEFINING AND
ACCESSING
FUNCTION
3 Elements of user-defined
functions
1.Function/Prototype Declaration
2.Function Call
3.Function Definition
Function prototype(Declaration)
 Every function in C programming should be declared before they are used.
These type of declaration are also called function prototype.
 Function prototype gives compiler information about function name, type of
arguments to be passed and return type.
Syntax of function prototype
return_type function_name(datatype(1) argument(1),
datatype(2) argument(2)
……….
datatype(n) argument(n));
 Example:int add(int a, int b);
is a function prototype which provides following information to the
compiler:
 name of the function is add()
 return type of the function is int.
 two arguments of type int are passed to function.
 Function prototype are not needed if user-definition function is
written before main() function.
Function call
Control of the program cannot be transferred to user-defined
function unless it is called invoked.
Syntax of function call

function_name(argument(1),argument(2),....argument(n));

Example, add(num1,num2); function call is made using


statement from main().
This make the control of program jump from that statement to
function definition and executes the codes inside that function.
Function definition
Function definition contains programming codes to perform
specific task.
Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}
Example:
int add(int a, int b)
{
int sum;
sum = a + b;
return sum;
}
Return Statement
The return statement serves two purposes:
(1)On executing the return statement it immediately transfers the
control back to the calling program.
(2) It returns the value present in the parentheses after return, to
the calling program.

Syntax of return statement


return (expression);
For example:
return a; return (a+b);
Note:A function can return only one value at a time.
Thus, the following statements are invalid.
return ( a, b ) ;
return ( x, 12 ) ;
Return Statement

return sum;
In above example, value of variable sum in add() function
is returned.
The data type of expression in return statement should
also match the return type of function.
If return type not mentioned in function declaration and
definition ,compiler assumes the function to return an
integer.
The value returned by a function can be assigned to a
variable, printed, or used in an expression
A complete Example-Functions
Void Functions
 A void function may be called to
 perform a particular task (clear the screen)

 modify data

 perform input and output

 A void function() does not return a value to the calling


program
 int function() return an integer to the calling program
 main()/any function() by default returns an integer
 A return; statement can be used to exit from function
without returning any value
Example:
void main( ) //calling function
{
message( ) ; //function call
printf ( "Have a nice day!\n" ) ;
}
void message( ) //function definition
{
printf ( "Smile, and the world smiles with you...\n" ) ;
}
Output...
Smile, and the world smiles with you...
Have a nice day!
Example:calling more than 1 function
void brazil( )
void main( )
{
{ printf ( "\nI am in brazil" ) ;
printf ( "\nI am in main" ) ; }
italy( ) ; void argentina( )
brazil( ) ; {
printf ( "\nI am in argentina" ) ;
argentina( ) ;
}
} Output:
void italy( ) I am in main
{ I am in italy
printf ( "\nI am in italy" ) ; I am in brazil
I am in argentina
}
Example:One function can call another function
void main( ) void brazil( )
{ {
printf ( "\nI am in main" ) ; printf ( "\nI am in brazil" ) ;
italy( ) ; argentina( ) ;
printf ( "\nI am finally back in }
main" ) ; void argentina( )
} {
void italy( ) printf ( "\nI am in argentina" ) ;
{ }
printf ( "\nI am in italy" ) ; Output:
I am in main
brazil( ) ; I am in italy
printf ( "\nI am back in italy”) ; I am in brazil
I am in argentina
} I am back in italy
I am finally back in main
Any function can be called from any other function. Even main( ) can be
called from other functions.
For example,
main( )
{
message( ) ; OUTPUT:
} INFINITE TIMES
message( ) Can't imagine life without C
Can't imagine life without C
{
Can't imagine life without C
printf ( "\nCan't imagine life without C" ) ; -
main( ) ; -
} Can't imagine life without
A function can be called any number of times.
For example,
void main( )
{
message( ) ;
message( ) ;
}
void message( )
{
OUTPUT:
printf ( "\nJewel Thief!!" ) ; Jewel Thief!!
} Jewel Thief!!
A function can be called from other function, but a function cannot be
defined in another function.
Thus, the following program code would be wrong and shows error, since
argentina( ) is being defined inside another function, main( ).
main( )
{
printf ( "\nI am in main" ) ;
argentina( )
{
printf ( "\nI am in argentina" ) ;
}
}
User-defined functions can be categorized as:

1. Function with no arguments and no return

value

2. Function with no arguments and return value

3. Function with arguments but no return value

4.Function with arguments and return value.


#include<stdio.h>
void sum(); /*declaring prototype of function*/
void main()
{
sum(); /* calling function*/
}
void sum ( ) /* function definition*/
{
int a,b, result;
printf("\n Enter the two numbers : ");
scanf("%d %d",&a,&b); /* taking two numbers as input*/
result = a + b ;
printf(“the result is %d”, result);
}
#include<stdio.h>
int sum(); /*declaring prototype of function*/
void main()
{
int c;
c=sum( ); /* calling function- the value returned by the function is
stored in c */
printf(“the result is %d”, c);
}
int sum ( ) /* function definition*/
{
int a,b,result;
printf("\n Enter the two numbers : ");
scanf("%d %d",&a,&b); /* taking two numbers as input*/
result = a + b ; /*adding two numbers*/
return (result); /*result is returned to main*/
}
Passing arguments to
a function
Any number of arguments can be passed to a function
being called.
However, the type, order and number of the actual and
formal arguments must always be same.
The variables (a, b and c)used in calling function are
called ‘actual arguments’,
The variables( x, y and z) used in called function are
called ‘formal arguments’.
If the value of a formal argument is changed in the called
function, the corresponding change does not take place in
the calling function.
#include<stdio.h>
void sum(int,int); /*declaring prototype of function*/
void main()
{
int a,b;
printf("\n Enter the two numbers : ");
scanf("%d %d",&a,&b); /* taking two numbers as input*/
sum(a,b); /* calling function,
}
void sum ( int num1,int num2) /* function definition*/
{
int result; /*variable scope lies within function */
result = num1 + num2 ; /*adding two numbers*/
printf(“the result is %d”, result);
}
#include<stdio.h>
int sum(int,int); /*declaring prototype of
function*/
void main()
{
int a,b,c;
printf("\n Enter the two numbers : ");
scanf("%d %d",&a,&b); /* taking two numbers as input*/
c = sum(a,b); /* calling function,the value returned by the function is stored in c */
printf("\n The sum of two numbers is : %d ",c);
}

int sum ( int num1,int num2)


{
int result; /* defining variable, its scope lies within function */
result = num1 + num2 ; /*adding two numbers*/
return (result) ; /* returning result */
}
#include<stdio.h>
float square(float); And here are three sample runs
main( ) of this program...
{
float a, b ;
printf ( "\nEnter any number " ) ; Enter any number 3
scanf ( "%f", &a ) ; Square of 3 is 9.000000
b = square ( a ) ;
printf ( "\nSquare of %f is %f", a, b ) ;
} Enter any number 1.5
float square ( float x )
Square of 1.5 is 2.250000
{
float y ;
y=x*x; Enter any number 2.5
return ( y ) ;
} Square of 2.5 is 6.250000
#include<stdio.h>
void max(); /*declaring prototype of function*/
void main()
{
max(); /* calling function*/
}
void max ( ) /* function definition*/
{
int a,b,c, result;
printf("\n Enter the numbers : ");
scanf("%d %d %d",&a,&b,&c);
result = a>b?(a>c?a:c): (b>c?b:c) ;
printf(“the largest is %d”, result);
}
#include<stdio.h>
int max(); /*declaring prototype of function*/
void main()
{
int largest;
largest=max( ); /* calling function*/
printf(“the largest is %d”, largest);
}
int max ( ) /* function definition*/
{
int a,b,c, result;
printf("\n Enter the numbers : ");
scanf("%d %d %d",&a,&b,&c);
result = a>b?(a>c?a:c): (b>c?b:c) ;
return (result); /*result is returned to main*/
}
#include<stdio.h>
void max(int,int,int); /*declaring prototype of function*/
void main()
{
int a,b,c;
printf("\n Enter the two numbers : ");
scanf("%d %d %d",&a,&b,&c);
max(a,b,c); /* calling function,
}
void max ( int a,int b,int c) /* function definition*/
{
result = a>b?(a>c?a:c): (b>c?b:c) ;
printf(“the largest is %d”, result);
}
#include<stdio.h>
int max(int,int,int); /*declaring prototype of function*/
void main()
{
int a,b,c,largest;
printf("\n Enter the numbers : ");
scanf("%d%d%d",&a,&b,&c);
largest = max(a,b,c); /* calling function*/
printf("\n The sum of two numbers is : %d ",largest);
}
int max ( int a,int b,int c) /* function definition*/
{
int result;
result = a>b?(a>c?a:c): (b>c?b:c) ;
return result;
}
Recursion
A function can call itself. Such a process is called ‘recursion’.
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.
Example:
void main()
{
printf(“Hello\n”);
main();
}
Infinite call
Recursion
Example: factorials
5! = 5 * 4 * 3 * 2 * 1
Notice that
 5! = 5 * 4!
 4! = 4 * 3! ...

Can compute factorials recursively


Solve base case (1! = 0! = 1) then plug in
 2! = 2 * 1! = 2 * 1 = 2;
 3! = 3 * 2! = 3 * 2 = 6;
Factorial using function
int factorial ( int x ) ;
void main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = factorial ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
int factorial ( int x ) And here is the output...
{ Enter any number
int f = 1, i ; 5
for ( i = x ; i >= 1 ; i-- ) Factorial value = 120
f=f*i;
return ( f ) ;
}
Factorial using recursion
int rec(int);
void main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
} And here is the output...
Enter any number
int rec ( int x ) 5
{ Factorial value = 120
int f ;
if ( x == 1 )
return ( 1 ) ;
else
f = x * rec ( x - 1 ) ;
return ( f ) ;
Example Using Recursion:
The Fibonacci Series
Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
Each number is the sum of the previous two
Can be solved recursively:
 fib( n ) = fib( n - 1 ) + fib( n – 2 )
f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0
#include<stdio.h>
int Fibonacci(int);
void main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Storage Classes
in C
To fully define a variable one needs to mention not only its
‘type’ but also its ‘storage class’. In other words, not only do
all variables have a data type, they also have a ‘storage class’.
a variable name identifies some physical location within the
computer where the string of bits
representing the variable’s value is stored.
There are basically two kinds of locations in a computer
where such a value may be kept—
 Memory and CPU registers.
It is the variable’s storage class that determines in which of
these two locations the value is stored.
a variable’s storage class tells us:
(a) Where the variable would be stored.
(b) What will be the initial value of the variable, if
initial value is not specifically assigned.(i.e. the
default initial value).
(c) What is the scope of the variable; i.e. in which
functions the value of the variable would be available.
(d) What is the life of the variable; i.e. how long would
the variable exist.
There are four storage classes in C:
(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class
Automatic Storage Class
Storage − Memory.
Default initial value − An unpredictable value, which is
often called a garbage value.
Scope − Local to the block in which the
variable is defined.
Life − Till the control remains within
the
block in which the variable is
defined.
Following program shows how an automatic storage class variable
is declared, and the fact that if the variable is not initialized it
contains a garbage value.
main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}
The output of the above program could be...
1211 221
where, 1211 and 221 are garbage values of i and j. When
you run this program you may get different values
main( )
{
auto int i = 1 ;
{
{
{
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
}
The output of the above program is:
111
main( )
{
auto int i = 1 ;
{
auto int i = 2 ;
{
auto int i = 3 ;
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
The output of the above program would be:
321
Register Storage Class
The features of a variable defined to be of register
storage class are as under:
Storage - CPU registers.
Default initial value - Garbage value.
Scope - Local to the block in which
the variable is defined.
Life - Till the control remains
within the block in
which the
variable is defined.
A value stored in a CPU register can always be
accessed faster than the one that is stored in memory.
Therefore, if a variable is used at many places in a
program it is better to declare its storage class as
register. A good example of frequently used
variables is loop counters. We can name their
storage class as register.
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}
Here, even though we have declared the storage class of
i as register, we cannot say for sure that the value of i
would be stored in a CPU register.
Why? Because the number of CPU registers are limited,
and they may be busy doing some other task.
What happens in such an event... the variable works as
if its storage class is auto.
Static Storage Class
The features of a variable defined to have a static storage
class are as under:
Storage − Memory.
Default initial value − Zero.
Scope − Local to the block in which
the variable is defined.
Life − Value of the variable persists
between different function
calls.
main( ) main( )
{
increment( ) ; {
increment( ) ; increment( ) ;
increment( ) ;
} increment( ) ;
increment( ) increment( ) ;
{
auto int i = 1 ; }
printf ( "%d\n", i ) ; increment( )
i=i+1;
} {
Output: 1 static int i = 1 ;
1
1 printf ( "%d\n", i ) ;
i=i+1;
}
Output : 1
2
3
External Storage Class
The features of a variable whose storage class has been
defined as external are as follows:
Storage − Memory.
Default initial value − Zero.
Scope − Global.
Life − As long as the program’s
execution doesn’t come to an end.
int i ;
main( )
{
printf ( "\ni = %d", i ) ;
increment( ) ;
increment( ) ;
decrement( ) ;
decrement( ) ;
} The output would be:
increment( ) i=0
on incrementing i = 1
{ on incrementing i = 2
i=i+1; on decrementing i = 1
printf ( "\non incrementing i = %d", i ) ; on decrementing i = 0
}
decrement( )
{
i=i-1;
printf ( "\non decrementing i = %d", i ) ;
}
int x = 21 ;
main( )
{
extern int y ;
printf ( "\n%d %d", x, y ) ; Output:
} 21 31

int y = 31 ;
Here, x and y both are global variables.
int x = 10 ;
main( )
{
int x = 20 ;
printf ( "\n%d“,x);
display( ) ;
} The output would be:
display( ) 20
{ 10
printf ( "\n%d", x ) ;
}
Here x is defined at two places, once outside main( ) and once inside it.
When the control reaches the printf( ) in main( ) which x gets printed?
Whenever such a conflict arises, it’s the local variable that gets
preference over the global variable. Hence the printf( ) outputs 20.
When display( ) is called and control reaches the printf( ) there is no such
conflict. Hence this time the value of the global x, i.e. 10 gets printed.,
int x = 10 ;
void main( )
{
int x = 20 ;
{
int x = 30 ;
printf ( "\n%d", x ) ;
}
printf ("\n%d", x ) ;
}
Output:
30
20
#include <stdio.h>
void main( )
{
{ int x = 30 ;
printf ( "\n%d", x ) ;
}
printf ("\n%d", x ) ;
}

error: ‘x’ undeclared


Which to Use When
We can make a few ground rules for usage of different
storage classes in different programming situations
with a view to:
(a) economise the memory space consumed by the
variables
(b) improve the speed of execution of the program
Use static storage class only if you want the value of a
variable to persist between different function calls.
Use register storage class for only those variables that
are being used very often in a program. Reason is,
there are very few CPU registers at our disposal and
many of them might be busy doing something else.
Make careful utilization of the scarce resources. A
typical application of register storage class is loop
counters, which get used a number of times in a
program.
Use extern storage class for only those variables that are
being used by almost all the functions in the program.
This would avoid unnecessary passing of these variables as
arguments when making a function call. Declaring all the
variables as extern would amount to a lot of wastage of
memory space because these variables would remain
active throughout the life of the program.
If you don’t have any of the express needs mentioned
above, then use the auto storage class. In fact most of the
times we end up using the auto variables, because often it
so happens that once we have used the variables in a
function we don’t mind loosing them.
Introduction-Preprocessing
Preprocessor--a system program that modifies (making
changes to the text )C program prior to its compilation
Compilation=Preprocessing +Translation
C program → Modified C program → Object Code
Preprocessing involves
Inclusion of external files
Definition of symbolic constants
Macros
Conditional compilation

63
Preprocessor
All preprocessor directives or commands begin with a
# symbol.
E.g. #include <stdio.h>
E.g. #define MAX 100
preprocessor compiler
 Directives not C statements-Do not end with ;

Dept of CSE,SKCET 64
Preprocessor Directives
File inclusion
#include
Macro definition
#define, #undef
Conditional Compilation
#if, #else, #elseif,#ifdef, #ifndef, #endif
Others

Dept of CSE,SKCET 65
File inclusion-#include Preprocessor directive
The first task of a preprocessor is file inclusion
#include directive-Puts copy of file in place of directives in
a program.
Two forms
 #include <filename>

 For standard header files from system library

File contain function prototypes for library functions


<stdlib.h> , <math.h> , etc
 Searches predesignated directories

 #include "filename"

 for user-defined header files in the user defined

directory
66 of CSE,SKCET
Dept
The #include Preprocessor Directive
Usage
Loading header files
 #include <stdio.h>
Programs with multiple source files
Header file
 Has common declarations and definitions
 Classes, structures, enumerations, function prototypes

 Extract commonality of multiple program files

67 of CSE,SKCET
Dept
Standard C libraries
Build-in with your compiler
stdio.h
core input and output capabilities of C
printf() function
scanf () function

Dept of CSE,SKCET 68
Math Library Functions
Math library functions
perform common mathematical calculations
 E.g. exp(), pow(), sqrt(), fabs(), sin(), cos().

#include <math.h>
Format for calling functions
FunctionName( argument, …, argument );
 All math functions return data type double

E.g.: printf( "%f", sqrt( 9 ) );


Arguments may be constants, variables, or expressions

Dept of CSE,SKCET 69
stdlib.h
A variety of utility functions
rand function
A function to generate a pseudo-random integer number
 Return value is in the range 0 to RAND_MAX
 Example:

#include <stdlib.h>
int i = rand();
• Exit()

• memory allocation
• process control

Dept of CSE,SKCET 70
string.h
All the string handling functions
strcpy
strcat
strcmp

Dept of CSE,SKCET 71
Macro definition
The second preprocessor task is expanding macro
definition.
 A macro definition command associates a
name(macro name) with a sequence of
tokens(macro body).
A macro definition is of the form
#define <macro name> <macro body>
• Simplest macro is to define a constant.
E.g.
#define FALSE 0 , #define SIZE 5
Dept of CSE,SKCET 72
#define
Need to be careful in coding the macro body.
Whenever a macro call is encountered the
preprocessor replaces macro call with the macro
body.
If the macro body not created carefully it may
create an error .
 E.g. #define SIZE = 10
void main()
{
int a =SIZE;// interpreted as a==10
}
Dept of CSE,SKCET 73
#define
To undefined a macro-A macro must be
undefined before being redefined to a different
value.
 E.g. #undef SIZE
#define SIZE 10
void main()
{
int a [SIZE];
}

Dept of CSE,SKCET 74
Define Functions
E.g. To get the product of two variables:
#define PRODUCT(A,B) A*B
void main()
{
int x;
x = PRODUCT(3,5);
}
Preprocessing done in two steps:
1.x=A*B;
2.x = 3*5;

Dept of CSE,SKCET 75
Carefully Define Functions
#define PRODUCT(A,B) A*B
void main()
{
int x;
int a=3,b=5;
x = PRODUCT(a+1,b+1);
}
Preprocessing done in two steps:
1.x=A*B;
2.x = a+1*b+1;//but we need (a+1)*(b+1)
Solution :place parameters inside parenthesis.
#define PRODUCT(A,B) (A)*(B)
Dept of CSE,SKCET 76
Define Functions
E.g. To get the maximum of two variables:

#define max(A,B) ( (A) > (B) ? (A):(B))

If in the C code:


x = max(3,5);
After preprocessing:
x = ( (3) > (5) ? (3) : (5));

Dept of CSE,SKCET 77
#if #else #endif expression
“If” clause statement is included in source file if given

condition is true.
Otherwise, else clause statement is included in source

file for compilation and execution.


#endif-Terminates the conditional code

You might also like