<Previous Lesson

Introduction to Programming

Next Lesson>

Lesson#9

Lesson 9

Summary


o Introduction
o Functions
o Structure of a Function
o Declaration and Definition of a Function
o Sample Program 1
o Sample Program 2
o Sample Program 3
o Summary
o Tips

Introduction


Now our toolkit is almost complete. The basic constructs of programming are sequence,
decision making and loops. You have learnt all these techniques. Now we can write
almost all kinds of programs. There are more techniques to further refine the programs.
One of the major programming constructs is Functions. C is a function-oriented language.
Every program is written in different functions.
In our daily life, we divide our tasks into sub tasks. Consider the making of a laboratory
stool.
Page 80
It has a seat and three legs. Now we need to make a seat and three legs out of wood. The
major task is to make a stool. Sub tasks are, make a seat and then fabricate three legs. The
legs should be identical. We can fashion one leg and then re-using this prototype, we
have to build two more identical legs. The last task is to assemble all these to make a
stool. We have a slightly difficult task and have broken down it into simpler pieces. This
is the concept of functional design or top-down designing. In top design, we look at the
problem from top i.e. identification of the problem. What we have to solve? Then refine it
and divide it into smaller pieces. We refine it again and divide it into smaller pieces. We
keep on doing it as long as we get easily manageable task. Let's consider an example like
home construction. From the top level, we have to construct a home. Then we say that we
need design of the home according to which the building will be constructed. We need to
construct rooms. How can we construct a room? We need bricks, cement, doors,
windows etc. Procurement of all of these things is tasks. Once we come down to the level
where a task is easily manageable and doable, we stop doing further refinement. When
we break up a task into smaller sub tasks, we stop at a reasonable level. Top-down
designing mechanism is based on the principle of 'divide and conquer' i.e. we divide a big
task into smaller tasks and then accomplish them.
Let's have a look at a simple example to understand the process of dividing big task into
simple ones. Suppose we want to know how many students are currently logged in the
LMS (Learning Management System) of VU. This task will be handed over to the
network administrator to find out the number of students currently logged in LMS of the
university. The network administrator will check the network activity or get this
information from the database and get the list of students currently logged in. The
number of students is counted from that list and the result is given back to us. What has
happened in this whole process? There was a simple request to find the number of
students currently logged in LMS. This request is delegated to the network administrator.
The network administrator performs this task and we get the result. In the mean time, we
can do some other task as we are not interested in the names or list of students. We only
want the number of students. This technique is known as parallel processing. In terms of
programming, network administrator has performed a function i.e. calculation of the
number of students. During this process, the network administrator also gets the list of
students which is hidden from us. So the information hiding is also a part of the function.
Some information is given to the network administrator (i.e. the request to calculate the
number of students currently logged in the LMS) while some information is provided
back to us (i.e. the number of students).
Page 81

Functions


The functions are like subtasks. They receive some information, do some process and
provide a result. Functions are invoked through a calling program. Calling program does
not need to know what the function is doing and how it is performing its task. There is a
specific function-calling methodology. The calling program calls a function by giving it
some information and receives the result.
We have a main ( ) in every C program. ‘main ( )’ is also a function. When we write a
function, it must start with a name, parentheses, and surrounding braces just like with
main ( ). Functions are very important in code reusing.
There are two categories of functions:
1. Functions that return a value
2. Functions that do not return a value
Suppose, we have a function that calculates the square of an integer such that function
will return the square of the integer. Similarly we may have a function which displays
some information on the screen so this function is not supposed to return any value to the
calling program.

Structure of a Function


The declaration syntax of a function is as follows:
return-value-type function-name( argument-list )

{
declarations and statements

}
The first line is the function header and the declaration and statement part is the body of
the function.

return-value_type:


Function may or may not return a value. If a function returns a value, that must be of a
valid data type. This can only be one data type that means if a function returns an int data
type than it can only return int and not char or float. Return type may be int, float, char or
any other valid data type. How can we return some value from a function? The keyword
is return which is used to return some value from the function. It does two things, returns
some value to the calling program and also exits from the function. We can only return a
value (a variable or an expression which evaluates to some value) from a function. The
data type of the returning variable should match return_value_type data type.
Page 82
There may be some functions which do not return any value. For such functions, the
return_value_type
is void. ‘void’ is a keyword of ‘C’ language. The default
return_value_type
is of int data type i.e. if we do not mention any return_value_type with
a function, it will return an int value.

Function-name:


The same rules of variable naming conventions are applied to functions name. Function
name should be self-explanatory like square, squareRoot, circleArea etc.

argument-list:


Argument list contains the information which we pass to the function. Some function
does not need any information to perform the task. In this case, the argument list for such
functions will be empty. Arguments to a function are of valid data type like int number,
double radius etc.

Declarations and Statements:


This is the body of the function. It consists of declarations and statements. The task of the
function is performed in the body of the function.
Example:
//This function calculates the square of a number and returns it.
int square(int number)
{
int result = 0;
result = number * number;
return result;
}

Calling Mechanism:


How a program can use a function? It is very simple. The calling program just needs to
write the function name and provide its arguments (without data types). It is important to
note that while calling a function, we don’t write the return value data type or the data
types of arguments.
Example:
//This program calculates the square of a given number
#include <iostream.h>
main()
{
int number, result;
Page 83
result = 0;
number = 0;
// Getting the input from the user
cout << “ Please enter the number to calculate the square ”;
cin >> number;
// Calling the function square(int number)
result = square(number);
cout << “ The square of “ << number << “ is “ << result;
}

Declaration and Definition of a Function


Declaration and definition are two different things. Declaration is the prototype of the
function, that includes the return type, name and argument list to the function and
definition is the actual function code. Declaration of a function is also known as signature
of a function.
As we declare a variable like int x; before using it in our program, similarly we need to
declare function before using it. Declaration and definition of a function can be combined
together if we write the complete function before the calling functions. Then we don’t
need to declare it explicitly. If we have written all of our functions in a different file and
we call these functions from main( ) which is written in a different file. In this case, the
main( )
will not be compiled unless it knows about the functions declaration. Therefore
we write the declaration of functions before the main( ) function. Function declaration is
a one line statement in which we write the return type, name of the function and the data
type of arguments. Name of the arguments is not necessary. The definition of the function
contains the complete code of the function. It starts with the declaration statement with
the addition that in definition, we do write the names of the arguments. After this, we
write an opening brace and then all the statements, followed by a closing brace.
Example:
If the function square is defined in a separate file or after the calling function, then we
need to declare it:
Declaration:
int square ( int );
Definition:
Page 84
int square ( int number)
{
return (number * number ) ;
}
Here is the complete code of the program:
//This program calculates the square of a given number
#include <iostream.h>
// Function declarations.
int square(int);
main()
{
int number, result;
result = 0;
number = 0;
cout << “ Please enter the number to calculate the square ”;
cin >> number;
// Calling the function square(int number)
result = square(number);
cout << “ The square of “ << number << “ is “ << result;
}
// function to calculate the square of a number
int square ( int number)
{
return (number * number ) ;
}
A function in a calling program can take place as a stand-alone statement, on right- hand
side of a statement. This can be a part of an assignment expression.
Considering the above example, here are some more ways of function calling mechanism.
result = 10 + square (5);
or
result = square (number + 10);
or
result = square (number) + square (number + 1) + square (3 * number);
or
Page 85
cout << “ The square of “ << number << “ is “ << square (number);
In the above statements, we see that functions are used in assignment statements. In a
statement result = square(5); The square(5) function is called and the value which is
returned from that function (i.e. the value returned within the function using the return
keyword) is assigned to the variable result. In this case, the square(5) will return 25,
which will be assigned to variable result. There may be functions which do not return any
value. These functions can't be used in assignment statements. These functions are
written as stand-alone statements.

Sample Program 1


C is called function-oriented language. It is a very small language but there are lots of
functions in it. Function can be on a single line, a page or as complex as we want.

Problem statement:


Calculate the integer power of some number (xn).

Solution:


We want to get the power of some number. There is no operator for power function in C.
We need to write a function to calculate the power of x to n (i.e. xn). How can we
calculate the power of some number? To get the power of some number x to n, we need
to multiply x with x up to n times. Now what will be the input (arguments) to the
function? A number and power, as number can be a real number so we have to declare
number as a double date type and the power is an integer value so we will declare the
power as an integer. The power is an integer value so we will declare power as an integer.
The result will also be a real number so the return value type will be of double data type.
The function name should be descriptive, we can name this function as raiseToPow. The
declaration of the function is:
double raiseToPow ( double x, int power ) ;
To calculate the power of x up to power times, we need a loop which will be executed
power
times. The definition of function is:
// function to calculate the power of some number
double raiseToPow ( double x , int power )
{
double result ;
int i ;
result = 1.0 ;
for ( i = 1 ; i <= power ; i ++ )
{
result *= x ; // same as result = result * x
Page 86
}
return ( result ) ;
}
Here is the program which is calling the above function.
// This program is calling a function raiseToPow.
#include <iostream.h>
//Function declaration
double raiseToPow ( double , int )
main ( )
{
double x ;
int i ;
cout << “ Please enter the number “ ;
cin >> x ;
cout << “ Please enter the integer power that you want this number raised to “ ;
cin >> i ;
cout << x << “ raise to power “ << i << “ is equal to “ << raiseToPow ( x , i ) ;
}
Now we have to consider what will happen to the values of arguments that are passed to
the function? As in the above program, we are passing x and i to the raiseToPow
function. Actually nothing is happening to the values of x and i. These values are
unchanged. A copy of values x and i are passed to the function and the values in the
calling program are unchanged. Such function calls are known as 'call by value'. There is
another way to call a function in which the function can change the values of variables
that are passed as arguments, of calling program. Such function call is known as call by
reference.
Sample Program 2

Problem statement:

Calculate the area of a ring.

Solution:


Page 87
We know that a ring consists of a small circle and a big circle. To calculate the area of a
ring, we have to subtract the area of small circle from the area of big circle. Area of any
circle is calculated as Pi * r2. We write a function to calculate the area of a circle and use
this function to calculate the area of small circle and big circle.
Following is the code of the function circleArea:
// Definition of the circleArea function.
double circleArea ( double radius )
{
// the value of Pi = 3.1415926
return ( 3.1415926 * radius * radius ) ;
}
Here is the complete code of the calling program.
// This program calculates the area of a ring
#include <iostream.h>
// function declaration.
double circleArea ( double);
void main ( )
{
double rad1 ;
double rad2 ;
double ringArea ;
cout << “ Please enter the outer radius value: ” ;
cin >> rad1 ;
cout << “ Please enter the radius of the inner circle: “ ;
cin >> rad2 ;
ringArea = circleArea ( rad1 ) – circleArea (rad2 ) ;
cout<< “ Area of the ring having inner raduis “ << rad2 << “ and the outer radius “ <<
rad1 << “ is “ << ringArea ;
}
double circleArea ( double radius )
{
// the value of Pi = 3.1415926
return ( 3.1415926 * radius * radius ) ;
Page 88
}

Sample Program 3


There are some other kinds of functions which are used to test some condition. Such
functions return true or false. These functions are very important and used a lot in
programming. In C condition statements, the value zero (0) is considered as false and any
value other than zero is considered as true. So the return type of such functions is int. We
usually return 1 when we want the function to return true and return 0 when we want the
function to return 0. Here is a sample program to elaborate this.

Problem statement:


Write a function which tests that a given number is even or not? It should return true if
the number is even, otherwise return false.

Solution:


We already know the method of deciding whether a number is even or not. The name of
the function is isEven. Its return type will be int. It will take an int as an argument. So the
declaration of the function should be as below;
int isEven ( int ) ;
We can also use a function in the conditional statements like:
if ( isEven ( number ) )
If the number is even, the function will return none zero value (i.e. usually 1) and the if
statement
will be evaluated as true. However, if the number is odd, the function will
return a zero value and the if statement is evaluated as false.
Here is a complete program.
// This program is calling a function to test the given number is even or not
#include <iostream.h>
// function declaration.
int isEven(int);
void main ( )
{
int number;
cout << " Please enter the number: " ;
cin >> number ;
Page 89
if ( isEven ( number ) )
{
cout << " The number entered is even " << endl;
}
else
{
cout << " The number entered is odd " << endl;
}
}
int isEven ( int number )
{
if ( 2 * ( number / 2 ) == number )
{
return 1;
}
else
{
return 0;
}
}

Summary


Functions are very good tools for code reuse. We have seen in the above example that the
area of two circles has been calculated without rewriting the code. This means that the
code has been reused. We can reuse the circleArea function to find the area of any circle.
A function performs a specific task. Functions also provide encapsulation. The calling
program does not know how the function is performing its task. So we can build up
modular form from small building blocks and build up more and more complex
programs.
If we are going to use a function in our program and the definition of the function is after
the calling program. The calling program needs to know how to call the function, what
the arguments are and what it will return. So its declaration must occur before usage. If
we do not declare a function before using, the compiler will give an error. If we define a
function before the calling program, then we do not need a separate declaration. The
function declaration is also known as function prototype or function signature. Whenever,
we need to build something, first of all we build a prototype of that thing and then later
on we build it. Similarly the function declaration is used as a prototype. We are following
the top- down methodology. We break the program into smaller modules and just declare
the functions and later on we can define these.
Page 90

Exercise:


1. Modify the raise to power function so that it can handle negative power of x, zero
and positive power of x.
2. Modify the area of ring function put in error checking mechanism.

Tips


We used functions for breaking complex problems into smaller pieces,
which is a top-down structured approach.
Each function should be a small module, self-contained. It should solve a
well defined problem.
Variable names and function names should be self- explanatory.
Always comment the code.

<Previous Lesson

Introduction to Programming

Next Lesson>

Home

Lesson Plan

Topics

Go to Top

Copyright © 2008-2013 zainbooks All Rights Reserved
Next Lesson
Previous Lesson
Lesson Plan
Topics
Home
Go to Top