You are on page 1of 39

1 1

Copyright of Campus Corporate Centre


Functions
2 2


Copyright of Campus Corporate Centre
Session Plan
Function
Prototype
Definition
Call

Local variables and global variables

Pass by value
Pass by Reference



3 3


Copyright of Campus Corporate Centre
Understanding Functions Non Modular
A bug in the
program( in
the
specified
part )
Whole
object
undergone
diagnose
and testing
A non-
modular
Program
4 4


Copyright of Campus Corporate Centre
Understanding Functions - Modular
A bug in
the
program
The
specified
part
separated
Either
replaced /
repaired
Modular
Program
5 5


Copyright of Campus Corporate Centre
Modular Programming - Manageable
Huge Book of
3000 pages
Same book
published in
several volumes.
Easily
manageable
6 6


Copyright of Campus Corporate Centre
BOOK
Vol 1
Vol 2
Vol 3
Vol 2
Vol 4
Vol 3
Divide and Conquer
7 7


Copyright of Campus Corporate Centre
What is a Function?

A sub program that does a specific task.
A unit of program code, as per syntax, to perform specific and well
defined task.
Function 1
{ Tasks }
Function 2
{ Tasks }
Function-1 requests Function-2
Function-1 in need of service
from function 2
Function 2 services Function1
8 8


Copyright of Campus Corporate Centre
Classification of Functions

Library functions
- defined in the language
- provided along with the compiler

Ex: printf(), scanf()





User Defined functions
- written by the user

Ex: main()
9 9


Copyright of Campus Corporate Centre
Elements of a Function
Function Declaration or Function Prototype :
- The function should be declared prior to its usage.

Function Definition :
- Implementing the function or writing the task of the function.

Function Invocation or Function call:
- To utilize a functions service we have to invoke( call ) the function.


10 10


Copyright of Campus Corporate Centre
Example Function Terminologies
void fDisplay() ;

int main(int argc, char **argv) {
fDisplay();
return 0;
}

void fDisplay() {
printf(Hello World);
}

Function Prototype
Function Call Statement
Function Definition
Calling Function
Called Function
11 11


Copyright of Campus Corporate Centre
How Functions Work?
main()
Function
call
User defined
function
12 12


Copyright of Campus Corporate Centre
Functions (Continued)
Functions are used to perform a specific task on a set of values.
Values can be passed to functions so that the function performs the task on
these values.
Values passed to the function are called arguments.
After the function performs the task, it can send back the results to the calling
function.
The value sent back by the function is called return value.
A function can return back only one value to the calling function.
13 13


Copyright of Campus Corporate Centre
Function - Syntax
[ fn. return type ] < function name > ([parameter list]) < {

[ Local variable declarations ] ;

[ functional statements ] ;

[ return [ return-value ] ] ;

} >

< > Mandatory fields
[ ] Optional fields
14 14


Copyright of Campus Corporate Centre
Function Prototype
Function Prototyping is declaring ONLY the signature of the function before
actually defining the function.
Here signature includes function name, return type, list of parameter data types
and optional names of formal parameters.


Syntax
Return_data_type FunctionName ( data_type arg1,
data_type arg2,...,data_type argn );

Ex :
int iValidate_Date(int d,int m, int y);

Note: Name of the variables are not obligatory in prototype declaration
15 15


Copyright of Campus Corporate Centre
Function Definition
Function Definition is implementing the task of the function.

Function Definition :
Return_data_type FunctionName ( data_type arg1, data_type
arg2,...,data_type argn ) {

Statement block

return [ expression ] ;
}
16 16


Copyright of Campus Corporate Centre
Function Definition - Example

int fValidate_Date (int iArg1, int iArg2, int iArg3) {
/* local variables declarations */
:
:
:
return ( iValidationFlag );
}
Functional Statements

17 17


Copyright of Campus Corporate Centre
Function Call statement which returns a value :
Variable = function_name ( [argument1, ,
argumentN ] ) ;

Function Call statement which doesnt return any value :

function_name ( [ argument1, ,argumentN ]) ;

Ex :
iValidDate = iValidate_Date(iDay,iMonth,iYear);

replicate(*,10);

Function Invocation (Call)
18 18


Copyright of Campus Corporate Centre
Returning values
The result of the function can be given back to the calling functions.
Return statement is used to return value or Null value to the calling function
from the called function.

Various forms of return statement:
return ( expression ) ;

Ex:
return( iNumber * iNumber);
return 0;
return (3);
return;
return (10 * i);
19 19


Copyright of Campus Corporate Centre
Function Another Example
int fSquare(int iNum) ;

int main(int argc, char **argv) {
int iSquare;
int iResult;
printf(Enter a number to find its square);
scanf(%d,&iSquare);
iResult = fSquare(iSquare);
printf(Square of %d is %d\n,iSquare, iResult);
return 0;
}
int fSquare(int iNumber) {
int iResult;
iResult = iNumber * iNumber * iNumber;
return iResult;
}
Formal Argument
Actual Argument
Return value
20 20


Copyright of Campus Corporate Centre
Example finding the sum of two numbers using
functions ( No parameter passing and no return)

#include< stdio.h >
int fSum();
int main( int argc, char **argv ) {
fSum();
return 0;
}

int fSum() {
int iNum1,iNum2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNum1,&iNum2);
iSum=iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
return 0;
}
21 21


Copyright of Campus Corporate Centre
Example finding the sum of two numbers using
functions ( parameter passing )
#include< stdio.h >
int fSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ) {
int iNumber1,iNumber2;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
fSum(iNumber1,iNumber2);
return 0;
}
int fSum(int iNum1,int iNum2){
int iSum;
iSum=iNum1 + iNum2;
printf("\nThe sum is %d\n",iSum);
return 0;
}
22 22


Copyright of Campus Corporate Centre
Example finding the sum of two numbers using
functions ( parameter passing and returning value)
#include< stdio.h >
int fSum( int iNumber1, int iNumber2);
int main( int argc, char **argv ){
int iNumber1,iNumber2,iSum;
printf("\nEnter the two numbers:");
scanf("%d%d",&iNumber1,&iNumber2);
iSum = fSum(iNumber1,iNumber2);
printf("\nThe sum is %d\n",iSum);
return 0;
}
int fSum(int iNum1,int iNum2){
int iTempSum;
iTempSum=iNum1 + iNum2;
return iTempSum;
}
23 23


Copyright of Campus Corporate Centre
Parameter passing
Pass by value
Pass by reference
24 24


Copyright of Campus Corporate Centre
Pass by Value
When parameters are passed from the called function to a calling
function, the value of the actual argument is copied onto the formal
argument.
The above way of passing the parameters is called, Pass by Value
The value of the corresponding formal argument can be altered within
the calling function.
The value of the actual argument within the calling routine will not
change.

25 25


Copyright of Campus Corporate Centre
Example Pass by Value
#include<stdio.h>
int fIncrement(int a, int b); /* function prototype */

int main(int argc, char **argv) {
int x=10,y=25;
printf("Value of x and y\n");
printf("\nx=%d,y=%d \n",x,y);
fIncrement(x,y);
printf(After calling the function Increment\n);
printf("\nx=%d,y=%d \n",x,y);
return 0;
}

int fIncrement(int a, int b) { /* function definition */
a=a+5;
b=b+21;
return 0;
}
26 26


Copyright of Campus Corporate Centre
100 200
200 100
100
200
Actual Arguments

Data Being Passed

Formal Arguments
PASS BY VALUE
27 27


Copyright of Campus Corporate Centre
Pass by Value

Call of function increment(a,b)
main()
increment(x,y)
End of function increment(x,y)
28 28


Copyright of Campus Corporate Centre
Pass by Value - (Continued)
Advantages
Actual argument can be an expression /variable.
Protects value of the actual arguments from alterations within the function.

Disadvantages
Information cannot be transferred back to the calling portion of the program via
arguments.
29 29


Copyright of Campus Corporate Centre
Pass by Reference
Changes to formal args affect actual args
Alternative mechanism for returning info

30 30


Copyright of Campus Corporate Centre
1020 1023
200 100
1020
1023
Actual Arguments
Address of Actual Arguments
Formal Arguments
PASS BY REFERENCE
31 31


Copyright of Campus Corporate Centre
Variable Declaration


Variables can be declared in 3 places:

Inside the functions

In the definition of function parameters

Outside of all functions

32 32


Copyright of Campus Corporate Centre
Scope and Lifetime of Variables
Scope of a variable
Scope of a variable is the portion of the program block in which the variable
can be referenced.

Lifetime of a variable
The lifetime of a variable is the time during which the variable is bound to a
specific memory location.
The lifetime of a variable starts when it is bounded to a specific memory
and ends when it is unbounded from that memory.



33 33


Copyright of Campus Corporate Centre
Global & Local Variables
Local variables
variables defined inside a function
Global variables
variables defined outside of all functions

Ex:
int iGlobal;

int main(int argc, char ** argv) {
int iLocal ;
}


Global variable
Local variable
34 34


Copyright of Campus Corporate Centre
Scope and Lifetime of Local and Global Variables
Global Variables

Visible throughout the
program.

Alive till the program is
terminated.
Local Variables

Visible within its block
or scope.

Alive till the flow of
execution is within the
same block.
35 35


Copyright of Campus Corporate Centre
Consider the following example.
#include <stdio.h>
int iGlobalVar,iSameName; fiFunc();
void main() {
int iLocalVar; iSameName = 1; iGlobalVar = 2; iLocalVar = 3;
printf( "Starting in main : ");
printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", iGlobalVar,
iLocalVar, iSameName);
fiFunc();
printf( "Returned to main: ");
printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", iGlobalVar,
iLocalVar, iSameName); }
int fiFunc() {
int iLocalVar;int iSameName;iGlobalVar = 20;iLocalVar = 50;iSameName = 10;
printf( "In SubFunc..");
printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", iGlobalVar,
iLocalVar,iSameName);}
36 36


Copyright of Campus Corporate Centre
Global Variables - Disadvantages

Lifetime of global variables is throughout the program.
Hence usage of global variables leads to wastage of memory

Scope of the global variable is throughout the program.
Hence more than one function can modify the value of the global variable. This
makes debugging difficult.

37 37


Copyright of Campus Corporate Centre
What is the output of the following code snippet?
int iGlobal ;

int main() {
int iLocal;
printf(Value of iLocal = %d \n, Value of iGlobal =
%d,iLocal, iGlobal);
}



The output is:
Value of iLocal = <some garbage value>
Value of iGlobal = 0
38 38


Copyright of Campus Corporate Centre
Example
Write a function which will return the absolute value of a given number.

Write a function whose prototype is, double fSquareRoot(double ) .
The function should return the square root of a given number, N, with
reasonable approximation, say, |N (output)
2
| < 0.001.
(For hint look at the text page.)






39 39


Copyright of Campus Corporate Centre
Solution: Absolute Value function
float fAbsoluteVal(float N) {
if( N > 0)
return N;
else
return -N;
}