Engineering Forum

India Education

Engineering Colleges Forum

Functions and Procedural Abstraction

This is a discussion on Functions and Procedural Abstraction within the Computer engineering forums, part of the ENGINEERING WORLD category; The Need for Sub-programs A natural way to solve large problems is to break them down into a series of ...


Go Back   Engineering Forum > ENGINEERING WORLD > Computer engineering

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

   

Reply

 

Thread Tools Display Modes
  #1 (permalink)  
Old 08-28-2008, 07:28 PM
aayush_005's Avatar
Administrator
 
Join Date: Aug 2008
Posts: 225
Default Functions and Procedural Abstraction

The Need for Sub-programs

A natural way to solve large problems is to break them down into a series of sub-problems, which can be solved more-or-less independently and then combined to arrive at a complete solution. In programming, this methodology reflects itself in the use of sub-programs, and in C++ all sub-programs are called functions (corresponding to both "functions" and "procedures" in Pascal and some other programming languages).

We have already been using sub-programs. For example, in the program which generated a table of square roots, we used the following "for loop":
...
#include<cmath>
...
...
for (number = 1 ; number <= 10 ; number = number + 1) {
cout.width(20);
cout << number << sqrt(number) << "\n";
}
...
...

The function "sqrt(...)" is defined in a sub-program accessed via the library file cmath (old header style math.h). The sub-program takes "number", uses a particular algorithm to compute its square root, and then returns the computed value back to the program. We don't care what the algorithm is as long as it gives the correct result. It would be ridiculous to have to explicitly (and perhaps repeatedly) include this algorithm in the "main" program.

In this chapter we will discuss how the programmer can define his or her own functions. At first, we will put these functions in the same file as "main". Later we will see how to place different functions in different files.
(BACK TO COURSE CONTENTS)



3.2 User-defined Functions

Here's a trivial example of a program which includes a user defined function, in this case called "area(...)". The program computes the area of a rectangle of given length and width.
#include<iostream>
using namespace std;

int area(int length, int width); /* function declaration */

/* MAIN PROGRAM: */
int main()
{
int this_length, this_width;

cout << "Enter the length: "; /* <--- line 9 */
cin >> this_length;
cout << "Enter the width: ";
cin >> this_width;
cout << "\n"; /* <--- line 13 */

cout << "The area of a " << this_length << "x" << this_width;
cout << " rectangle is " << area(this_length, this_width);

return 0;
}
/* END OF MAIN PROGRAM */

/* FUNCTION TO CALCULATE AREA: */
int area(int length, int width) /* start of function definition */
{
int number;

number = length * width;

return number;
} /* end of function definition */
/* END OF FUNCTION */
Program 3.2.1

Although this program is not written in the most succinct form possible, it serves to illustrate a number of features concerning functions:
The structure of a function definition is like the structure of "main()", with its own list of variable declarations and program statements.

A function can have a list of zero or more parameters inside its brackets, each of which has a separate type.

A function has to be declared in a function declaration at the top of the program, just after any global constant declarations, and before it can be called by "main()" or in other function definitions.

Function declarations are a bit like variable declarations - they specify which type the function will return.


A function may have more than one "return" statement, in which case the function definition will end execution as soon as the first "return" is reached. For example:
double absolute_value(double number)
{
if (number >= 0)
return number;
else
return 0 - number;
}


(BACK TO COURSE CONTENTS)



3.3 Value and Reference Parameters

The parameters in the functions above are all value parameters. When the function is called within the main program, it is passed the values currently contained in certain variables. For example, "area(...)" is passed the current values of the variables "this_length" and "this_width". The function "area(...)" then stores these values in its own private variables, and uses its own private copies in its subsequent computation.
Functions which use Value Parameters are Safe

The idea of value parameters makes the use of functions "safe", and leads to good programming style. It helps guarantee that a function will not have hidden side effects. Here is a simple example to show why this is important. Suppose we want a program which produces the following dialogue:
Enter a positive integer:
4
The factorial of 4 is 24, and the square root of 4 is 2.

It would make sense to use the predefined function "sqrt(...)" in our program, and write another function "factorial(...)" to compute the factorial n! = (1 x 2 x ... x n) of any given positive integer n. Here's the complete program:
#include<iostream>
#include<cmath>
using namespace std;

int factorial(int number);

/* MAIN PROGRAM: */
int main()
{
int whole_number;

cout << "Enter a positive integer:\n";
cin >> whole_number;
cout << "The factorial of " << whole_number << " is ";
cout << factorial(whole_number);
cout << ", and the square root of " << whole_number << " is ";
cout << sqrt(whole_number) << ".\n";

return 0;
}
/* END OF MAIN PROGRAM */

/* FUNCTION TO CALCULATE FACTORIAL: */
int factorial(int number)
{
int product = 1;

for ( ; number > 0 ; number--)
product *= number;

return product;
}
/* END OF FUNCTION */
Program 3.3.1

By the use of a value parameter, we have avoided the (correct but unwanted) output
Enter a positive integer:
4
The factorial of 4 is 24, and the square root of 0 is 0.

which would have resulted if the function "factorial(...)" had permanently changed the value of the variable "whole_number".
(BACK TO COURSE CONTENTS)



Reference Parameters

Under some circumstances, it is legitimate to require a function to modify the value of an actual parameter that it is passed. For example, going back to the program which inputs the dimensions of a rectangle and calculates the area, it would make good design sense to package up lines 9 to 13 of the main program into a "get-dimensions" sub-program (i.e. a C++ function). In this case, we require the function to alter the values of "this_length" and "this_width" (passed as parameters), according to the values input from the keyboard. We can achieve this as follows using reference parameters, whose types are post-fixed with an "&":
#include<iostream>
using namespace std;

int area(int length, int width);

void get_dimensions(int& length, int& width);

/* MAIN PROGRAM: */
int main()
{
int this_length, this_width;

get_dimensions(this_length, this_width);
cout << "The area of a " << this_length << "x" << this_width;
cout << " rectangle is " << area(this_length, this_width);

return 0;
}
/* END OF MAIN PROGRAM */

/* FUNCTION TO INPUT RECTANGLE DIMENSIONS: */
void get_dimensions(int& length, int& width)
{
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "\n";
}
/* END OF FUNCTION */

/* FUNCTION TO CALCULATE AREA: */
int area(int length, int width)
{
return length * width;
}
/* END OF FUNCTION */
Program 3.3.2

Notice that, although the function "get_dimensions" permanently alters the values of the parameters "this_length" and "this_width", it does not return any other value (i.e. is not a "function" in the mathematical sense). This is signified in both the function declaration and the function heading by the reserved word "void".
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are Off
Refbacks are Off
Forum Jump


All times are GMT. The time now is 10:32 AM.


Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.