0% found this document useful (0 votes)
22 views13 pages

FUNCTIONS

The document discusses different types of functions in C programming including user-defined functions. It covers void functions, functions with return values, functions with and without parameters. Examples are provided to illustrate function prototypes, function calls, and function definitions.

Uploaded by

maneskin488
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views13 pages

FUNCTIONS

The document discusses different types of functions in C programming including user-defined functions. It covers void functions, functions with return values, functions with and without parameters. Examples are provided to illustrate function prototypes, function calls, and function definitions.

Uploaded by

maneskin488
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT-5 Lecture Notes

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.

Designing Structured Programs:


Structured programs consists of three basic components of problem solving viz. Sequential execution,
Selection based execution and Repetitive execution combined with top-down design.

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)

Arithmetic operations Calculus operations Statistics operations Trigonometric


(Sub-module-1) (Sub-module-2) (Sub-module-3) (Sub-module-4)

Addition Differentiation Mean Sine


(Sub-module-1a) (Sub-module-2a) (Sub-module-3a) (Sub-module-4a)

Subtraction Integration Variance Cosine


(Sub-module-1b) (Sub-module-2b) (Sub-module-3b) (Sub-module-4b)

Multiplication Standard deviation Tan


(Sub-module-1c) (Sub-module-3c) (Sub-module-4c)

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

1. Built-in (Library) functions


2. User defined functions

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.

Advantages of using Functions:


Function based modular programming is advantageous in many ways:
1. Managing huge programs and software packages is easier by dividing them into
functions/modules—Maintenance is easier
2. Error detection is easier—Debugging is easier
3. Functions once written can be re-used in any other applications – Reusability is enhanced
4. We can protect our data from illegal users—Data protection becomes easier

Following block diagram explains how functions are useful:


Instead of writing entire program (to add and subtract) within main( ) function we can write independent
modules add( ) and subtract( ) as shown:

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.

User Defined Functions


As we have defined earlier, user defined functions are written by end-user programmers and aren’t part
of C language complier. User defined functions can be classified broadly into following categories:

Page 2
UNIT-5 Lecture Notes

User defined
functions

Functions return Functions with


nothing return value
(void functions)

void functions Functions with


with parameters parameters and
return values

void functions Functions without


without
parameters

Functions without parameters and Return values


Consider an example program given below:

#include<stdio.h>
int main( ) 1
{
/* statements */
printf(“Welcome to C World”);
return 0; 2

}/* end of main */

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.

Functions with parameters and Without Return values


Example for void function with parameters, display value of a variable with help of user defined
function:

#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

Functions with parameters and Return values


In the following example square of a number is calculated by a function called SquareMaker( ) and
also returns the computed value to main( )

Page 4
UNIT-5 Lecture Notes

Description of user defined function marked in


#include<stdio.h> the example given are:
int SquareMaker (int); 1. function prototype of SquareMaker( )
1
int main( ) has an integer parameter ‘int’ and
2
{ return type ‘int’
/* declaration*/ 2. calling function
int num, square; 3. actual parameter ‘num’ is passed to
/* statements */ function SquareMaker( ) and the
evaluated value is stored in variable
printf(“Enter the number whose square is reqd”);
square
scanf(“%d”, &num); 4. formal parameter ‘sq’ contains value
square=SquareMaker(num); 3 passed by ‘num’ and square of that
printf(“Square of number is %d”, square); number is calculated and sent back to
}/* end of main */ main

void SquareMaker(int sq)


{
/*statements*/
return(sq * sq);
}

Functions with Return value and no parameters:


We will modify the SquareMaker( ) function slightly to carry out this task:

#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

Two functions can communicate with each other by two methods:


1. By Passing parameters as values (Pass by Value)/(Call by Value).
2. By passing parameters as address (Pass by Address)/(Call by Address).
Call by Value/Pass by Value
All the examples so far discussed in this unit on functions are examples for pass by value.
In pass-by-value we make photocopy of actual parameter values and pass it to formal parameters.
Following example makes the concept clear:

void main() void add( int x, int y)


{ {
int a=5, b=10,sum1; int sum;
add(a , b); sum=x+y;
} printf(“%d”, sum)
}
/* a & b are actual parameters */
/* x & y are formal variables*/

Explanation for pass by value program calculating sum of two variables is as follows:

Value in a=5 Copied to x

Value in b=10 Copied to y


Sum=x+y (i.e. 5+10) is calculated

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

temp=x /* copies 5 to temp*/


x=y /*copies 10 to x*/
Value in Copied to x y=temp /* copies 5 to y */
a=5
Thus x and y values got swapped, but problem is a
and b values remain unchanged!
Value in Copied to y So pass by value method fails here!
b=10 Alternative is pass by address/reference

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

1002 is memory address of a


2000 is memory address of b

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

Address of is Copied to x temp=*x /* copies 5 to temp */


a=say(1002) *x=*y /*copies 10 to *x (i.e. to a) */
*y=temp /* copies 5 to y (i.e. to b) */
Address of is Copied to y
b=say 2000 Thus ‘a’ and ‘b’ values got swapped
indirectly!

*x stands for “value at” x. x is 1002 value at 1002 is 5.


*y stands for “value at” y. y is 2000 value at 2000 is 10.
In Call by Address/Pass by address any changes done to formal parameter will reflect back in
actual parameter.
Scope of Variables:

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.

Standard Library Functions:


Ready-made functions already available with C compliers are called Standard-Library functions.
Code for these functions needn’t be written by end-users.
Examples for standard mathematical functions available in a header file “math.h” are given below:
Function prototype Purpose Data type used Example
int abs(int no) Used to return Applicable for int a= -25,b;
only positive integer data type b=abs(a);
value of a /*b will have 25*/
parameter ‘no’
double fabs(double no) Used to return Applicable for double x= -45.67;
only positive double data type double y;
value of a y=fabs(x);
parameter ‘no’ /* y will store 45.67*/
double sqrt(double no) Used to calculate Applicable on int a=25,root;
square root of integers/float/doub root=sqrt(a);
parameter ‘no’ le
/* root will have 5 as
answer*/
double pow(double x, Used to calculate Applicable on int a=2, b=4,x;
double y); power of number integers/float/doub x=pow(a,b);
x i.e. xy le /* x will store value 16
(24)

double ceil( double no) Ceiling function Applicable on float x=2.111, y;


rounds off a float/double y=ceil(x);
fractional
number to its /* y will have rounded

Page 8
UNIT-5 Lecture Notes

next integer of value 3*/


double floor (double no) Floor function Applicable on float x=2.111, y;
rounds of to float/double y=floor(x);
previous integer
/* y will have rounded
of value 2*/

Inter-Function Communication (Passing Array to the Function)


In large programs that use functions we can pass Arrays as parameters. Two ways of
passing arrays to functions are:
1. Pass individual elements of array as parameter
2. Pass complete array as parameter
Let us take an example program that uses a function square( ) to calculate square of
numbers stored in an array. In this program each array element is passed one by one.

Example-1: Example-1 cont’d:


int main( ) int square(int n )

int num[5], i; int sq;

num[5] ={3,4, 8, 9, 10}; sq=n*n; /*square is calculated*/


printf(“square is=%d”, sq);
for(i=0; i<5; i++) return 0;

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

Pass complete array as parameter

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

Example-2: Example-2 cont’d:


int main( ) int average(int score[ ] )
/* entire array is passed */
int marks[5], i
float avg1; int i , sum=0;
float avg;
marks[5] ={35,65, 75, 95, 85};
for(i=0; i<5;i++)
avg1=average(marks);
printf(“average=%f”, avg1) sum=sum+score[i];
return 0; /* calculate total marks */

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]

marks[1]=65 copied to scores[1]

marks[2]=75 copied to scores[2]

marks[3]=95 copied to scores[3]

marks[4]=85 copied to scores[4]

using these values average is calculated:


(35+65+75+95+85)/5= 71.000000

Software Engineering Tips for Functions:


While writing user defined functions in programs we have to make use of following three concepts:
Page 10
UNIT-5 Lecture Notes

1. Use of Structure Charts


2. Concept of Functional Cohesion
3. Top-Down Design technique

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

Programming Exercise Problems


1. Find any errors in the following function definitions:

Page 11
UNIT-5 Lecture Notes

int display(int x, y)
{
int z;
return z;

Answer: Error exists while specifying actual parameters int y is missing


2. Find errors if any:
int moon( int x, int y)
{
int sun(int z)
{
return(z+3);
}
}
Answer: Error exists, we cannot have one function definition written inside another, here sun( )
definition is given inside moon( )
3. Find errors in following function calls:
i. int moon(int x, y);
ii. void sun (void, void);
iii. int calc(x int, y float)
Answers:
i. we shouldn’t give data type of parameter in function call (int x should be
written as just x) also int moon should be written as just moon( x, y);

ii. answer is: sun( );

iii. answer is calc( x, y);

4. Evaluate value of following expressions:


i. fabs(-3.4);
ii. fabs(7);
iii. floor(9.5);
iv. ceil(9.5);
Answers:
i. 3.4
ii. 7.00
iii. 9
iv. 10

5. Identify local variables and global variables in following program:

Page 12
UNIT-5 Lecture Notes

int a=5, b=10, int add( )


{
void main() int sum;
{
int sum1; sum=x+y;
sum1=add(a,b);
printf(“%d”, sum1) return(sum);
}
Answer: sum1 is local variable to main( ) function
sum is local variable to add( ) function
a and b are global variables

6. The process of dividing program into functions is called


options: 1)Factoring , 2) charting 3)structuring 4)Programming

7. Which of the following is not a part of function header?


1) function name 2)return type 3)title 4)parameter list

8. Which of the following statements about function parameters is true


1) Empty parameters list are declared with key word void → True
2) If there is only one parameter function parentheses is not required→ False
3) Parameters are separated by semicolons →False (separated by comma)
4) Parameters given in function definition are called actual parameters →False ( they
are formal parameters)

Page 13

You might also like