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
  #2 (permalink)  
Old 01-17-2011, 05:00 AM
Junior Member
 
Join Date: Jan 2011
Posts: 5
Default

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 is really amazing and outstanding.
__________________
taxi
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 02-05-2011, 11:19 PM
Junior Member
 
Join Date: Feb 2011
Location: USA
Posts: 1
Send a message via ICQ to 7k-ionline-Bargain
Default Love Love Loving it

online bargain

You might be one with the thousands of men and women, who are in acquiring freebies on the web. You
are on the right place because right here will be the opportunity for you. There are websites that gives you
tips on how to score yourself some freebies and it could sound too excellent to be true.

When you try to research on the net, you will find thousands of folks that also try to request the same
search, particularly on Break, YouTube, Daily Movement and many more. They will show you on how
to receive the free stuff online but will just make you deeply disappointed because most of them are just
scam.

How to score yourself some freebies on the? You should surf the net to attain tons of things for free.
It will be fun and super exciting. These said internet websites that give you freebies also give you the
opportunity to gain free of charge video games, consoles, computer systems, laptops and many more for
free of charge. Anything you believe you want could also be available for free.

Now, you may already ask on where all these internet sites can be found. Just merely go to Yahoo search
or even in Google and simply type the following keywords: free electronics ?and? free on-line stuff.? This
will surely help you on what you are looking for. Just always bear in mind to be wise and read the notes
carefully in order to avoid scam.

It is possible to obtain like freebie internet sites everywhere. Moreover, on this you could possibly
want. Indeed, it's in fact something. You'll be able to get all types o wallpapers, graphics, dollars, from
consumer electronics, and a lot more.

Well, in order to have some freebies online you must also train yourself on how to have some without
being scammed.


---------------------------------------------------
weekly deals
__________________
daily deals
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 02-23-2011, 03:18 AM
Junior Member
 
Join Date: Feb 2011
Location: Germany Nortrhine-Westfalia
Posts: 1
Default thanks...

thanks, that helped me a lot!
regards,
chantal
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 12:01 AM.


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