Thursday, August 5, 2010

User defined function in BlueJ programs - Part I

What is function



Function means a block where number of statement(s) are kept. These statement(s) are to be executed when required. In structured programming, a program is divided into different modules. Another reason of using functions in a program is to reduce the size of the program. In programs there may be situations when same set of statements will be required to be executed in different parts of the same program. In such case create, a function with the statements. In BlueJ and other Object oriented programming languages, user defined function is a must.

In Icse and Isc computer applications question papers, you will find BlueJ programs to write with using specific user defined functions as written in question paper. You have to do the program with the guide line provided. So a clear concept on user defined function is very much needed for students.

Components of a function



1.Function name (user defined)—Function should have a name.

2.Return type of the function (should be placed before the function name)– function which returns value must have a return type equivalent to the type of value returned (e.g. int, float etc). If a function does not return any value then it’s return type should be void.

3.parentheses [()] follow the function name. Functions can take values or arguments when invoked .If a function takes any argument then it must be declared inside the parentheses.

Two steps required for function



1. Function definition – next comes the function definition. The function definition of the above declared functions would look like: -
void add ()
{
From this point the function body starts
The statement(s), which form the unit
Should be placed within this body
} Function body ends here.

Note that there is no semicolon after void add (). In case of function definition there should be no semicolon. A function definition must have a function body and inside the body the function statements should be placed. In BlueJ programs, sometimes we have to define a function with empty body, means no statement inside the function body. In such case also we have to define the block of function body. On calling the function the statements will be executed. void main () is an example of function definition.

2.Calling the function – To execute the statements of a function body, the function is to be called. At the time of calling a function no return type should be used. Suppose we want to call the previously defined function then the syntax should be: - add ();

In BlueJ programs, we normally define function and call function. Declaring a function in BlueJ means something different. In such case, the class would be abstract class. In inheritance we will discuss it abstract class in details. Where as in C Language and C++ programs we can declare functions in normal situation.

3 comments:

Subscribe via email

Enter your email address:

Delivered by FeedBurner