FUNCTIONS
FUNCTIONS
Unit-V 6 Hours
Functions
Designing structured programs, Functions in C, User-defined Functions, Inter-function
communication, Standard functions, Scope, Programming examples, Software Engineering,
Tips and common programming errors.
Top-down design technique is to understand the whole problem totally and break it down into sub-
modules until we end up with sub-modules that are not further divisible. This process of dividing
modules (problems) to sub-modules (sub-problems) is called factoring.
Structure charts is a tool used in top-down design. Structure charts are read / understood from top to
down and left to right. Following example illustrates a structure chart to design scientific calculator
operations.
Scientific calculator
(Main module)
Division
(Sub-module-1d)
We read the above structure chart from top to down and left to right. Here Main module can “call” Sub-
module-1, Sub-module-2, Sub-module-3 and Sub-module-4, and Sub-module-1 can “call” its sub-
ordinates Sub-module-1a, Sub-module-1b, Sub-module-1c and so on. If Sub-module-2 wants to
communicate with Sub-module-1 it cannot directly call it. It can only communicate through Main
module.
Here the superior/higher up module is called “Calling function” and the sub-ordinate is called as
“Called function”.
Note: In a structure chart one and only one superior module can call its subordinate modules.
Functions in C
Every C program should consist of one or more functions. Among these functions main( ) function
is compulsory. All programs start execution from main( ) function. Next let us define functions.
Functions are independent program modules that are designed to carry out a particular task. In
functions we have two types:
Page 1
UNIT-5 Lecture Notes
Built-in functions are C language functions already available with C compliers and can be used by any
programmers. Example: printf( ),scanf( )
User-defined functions are written by programmers to serve their own purpose and are not readily
available. Examples: In the above given structure chart for scientific calculator addition( ), subtraction(
) modules are called user-defined functions.
main( )
add( ) subtract( )
Function output
inputs Black-box
Note: As shown in the above diagram, function can accept any number of inputs but can return
only one value as output.
Page 2
UNIT-5 Lecture Notes
User defined
functions
#include<stdio.h>
int main( ) 1
{
/* statements */
printf(“Welcome to C World”);
return 0; 2
1. int main( ) meaning is → name of function is main and it returns integer value to compiler
2. {
} → whatever enclosed within two { } braces is body of function main()
3. body contains two statements printf( ) which is a built-in function and return statement
which returns 0 (zero) to compiler
We can re-write this program to display “Welcome to the C World” by using a user defined function
as follows: Parts of user defined function marked in the
example given are:
#include<stdio.h> 1. function prototype
void display(void); 2. calling function
int main( ) 2 3. called function/function call
{ 4. function definition
/* statements */ a. function header
i. return type
display( ); ii. function name
iii. parameters if any
}/* end of main */ b. function body
Page 3
UNIT-5 Lecture Notes
4a
void display(void )
/*statements*/
printf(“Welcome to the C World”); 4b
return;
Function prototype— ‘void display(void )’ tells to the calling function main( ) that there is a user defined
function with so and so name (in our case display( )) and its return type is so and so (i.e. void) and has
these parameters (i.e. void or no parameters).
Function call –‘display( );’ specifies that main() function is calling a function by name ‘display()’
and execution control jumps to the function definition of display().
Function defintion—starts the execution of display() function by using function header ‘void
display(void )’ and function body given within { } braces. Once the computation is over execution
control returns back to main(). The function display() discussed above is an example for void function
without parameters.
#include<stdio.h>
void show(int); 1
int main( ) 2 Description of user defined function marked in
{ the example given are:
/* statements */ 1. function prototype of show( ) has an
int num=5; integer parameter ‘int’
show(num); 2. calling function main ( )
3. actual parameter ‘num’ is passed to
}/* end of main */ function show( )
4. formal parameter ‘n’ contains value 5
void show(int n) copied from ‘num’ and displays it on
{ screen
/*statements*/
printf(“%d”, n);
return;
}
In this example a photocopy of value stored in ‘num’ (i.e. 5) is made in formal parameter ‘n’ and
finally displayed on screen. Next let us discuss functions with parameters and return values
Page 4
UNIT-5 Lecture Notes
#include<stdio.h>
int SquareMaker ( ); 1
int main( ) 2
{ Description of user defined function marked in
/* declaration*/ the example given are:
int square; 1. function prototype of SquareMaker( )
/* statements */ has an integer no parameter but return
square=SquareMaker( ); type is ‘int’
printf(“Square of number is %d”, square); 2. calling function
}/* end of main */ 3. No parameter is passed to function
SquareMaker( ) while calling it
void SquareMaker( ) 4. SquareMaker( ) calculates square of
{ ‘sq’ and returns that value back to
int sq; main( )
/*statements*/
printf(“Enter the number whose square is reqd”); 4
scanf(“%d”, &num);
return(sq * sq);
}
Note: Function call can be an expression like: “square=SquareMaker( )” only in functions with
return values. Void function call cannot be an expression.
Inter-Function Communication
Page 5
UNIT-5 Lecture Notes
Explanation for pass by value program calculating sum of two variables is as follows:
Now let us consider a function to swap( ) (i.e. exchange values in two variables). If we implement
this program with pass by value method as shown below it will not work properly:
void main()
{ void swap( int x, int y )
int a=5, b=10; {
swap(a, b); int temp;
printf(“%d %d”, a,b); temp=x;
x=y;
}
y=temp;
}
In Call by Value/Pass by Value any changes done to formal parameter will not reflect back in
actual parameter.
Pass by Reference/Address method:
Page 6
UNIT-5 Lecture Notes
To understand this method, first we have to learn basics of address storage in C language.
Every memory location referred to by a variable has an address associated with it. For example
consider following declaration:
int a=5, b=10;
1002 2000
a 5 b 10
We can store the memory addresses of ‘a’ and ‘b’ using a special variable called pointers. Simple
definition of pointers is it is a special variable that can store address of memory locations.
Declaring pointers is as follows:
void main( )
{
int x=25;
int *ptr;
/* meaning is ‘ptr’ is pointer variable that stores address of an integer value.*/
ptr =&x;
/* above statement stores memory address of ‘x’ in ‘ptr’ */
printf(“%d %d %d”, x, ptr , *ptr);
/* x displays 25, ptr displays memory address of ‘x’ and *ptr also displays 25 */
}
With this background let us re-write swapping function swap( )by pass by reference method.
void swap( int *x, int *y )
void main() {
{ int temp;
int a=5, b=10; /* temp is local variable*/
/*local variables*/ temp=*x;
swap(&a, &b); *x=*y;
printf(“%d %d”, a,b) *y=temp;
} }
Page 7
UNIT-5 Lecture Notes
Value stored in a variable is visible within a function based on place of declaration of that variable. That
is if a variable is declared outside all functions present in a program such variable’s value is accessible
(Visible) to all the functions in that program. Such variable is called Global Variable.
Example:
#include<stdio.h>
int a=5, b=10; /* a & b are global variables */ int add( )
void main() {
{ int sum;
int sum1; /* sum is local variable to add( )*/
/* sum1 is local variable to main( )*/ sum=a+b;
sum1=add(); return(sum);
printf(“%d”,sum1); }
}
In the above example ‘a’ and ‘b’ are global variables and their values are visible to both main ( )
and add ( ) functions. that is why even though parameters aren’t passed to add ( ) they get accessed
by add( ) function.
Now let us consider variables ‘sum1’ and ‘sum’ they are commented as Local variables as their
values are accessible only within main( )and add( )respectively.
Page 8
UNIT-5 Lecture Notes
square(num[i]);
return 0;
Output:
Square is=9 16 64 81 100
This diagram clearly illustrates how each individual element of array num[ ] is passed to
function square through parameter n.
3 4 8 9 10
num[3]=9→ n
0 1 2 3 4
num[2]=8→ n
num[1]=4 copied → n
num[0]=3 copied to n
Page 9
UNIT-5 Lecture Notes
Next program illustrates how to pass an entire array to a function average( ) and calculate
average marks. First sum of all the elements of array marks (i.e.35+65+75+95+85) is calculated
and average is stored in a variable avg. value in avg variable is returned to
main( ) and stored in avg1
avg=sum/5;
return (avg);
Output:
average=71.000000
In the above example each value of array marks[ ] is copied to array scores[ ] as shown
below:
marks[0]=35 copied to scores[0]
(Main module)
(Sub-module-1) (Sub-module-2)
(Sub-module-3)
(Sub-module-1a)
(Sub-module-2a) (Sub-module-3a)
(Sub-module-1b) (Sub-module-2b)
(Sub-module-3b)
Structure Charts are like blue-prints used while constructing buildings. Following rules are used
while writing Structure charts:
1. Structure chart rectangles denote user defined functions.
2. Standard library functions are not indicated using structure charts.
3. Structure Charts do not contain program code, they indicate only logic flow.
4. Program codes are indicated using low-level programming tools like algorithm or
flowcharts.
5. Function names written in structure charts should convey meaningful names.
6. Commonly used or repeatedly used functions are denoted by a cross-hatch or shading in
right-most corner of rectangle (see figure below).
Common
functions
Functional Cohesion:
It is a measure of how closely processes in a function are related to each other. Greater is the
relation more the cohesion measure.
Advantages of cohesion are:
1. Reusability of code
2. Ease of Maintenance
3. Error free coding
Reusability helps us to avoid re-invention of wheel process, so that built-in code which is tested
well can be used in future projects. Maintenance is a key feature of complex programming projects
and function based programs are handy here. Cohesive functions aptly avoid errors in programs.
Page 11
UNIT-5 Lecture Notes
int display(int x, y)
{
int z;
return z;
Page 12
UNIT-5 Lecture Notes
Page 13