Programming Language 2 (Eee) : Lab Manual
Programming Language 2 (Eee) : Lab Manual
LANGUAGE 2 [EEE]
LAB MANUAL
Lab Manual # 3
Faculty:
M. Arifur Rahman
Table of Contents
I. 1.0 The Need for sub-programs ...................................................................................... 2
PAGE 1 OF 12
1.0 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 subprograms, and in C++ all subprograms are called functions
(corresponding to both "functions" and "procedures" in Pascal and some other programming languages).
We have already been using subprograms. 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 subprogram accessed via the library file cmath (old header style
math.h). The subprogram 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.
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;
/* MAIN PROGRAM: */
int main()
{ int this_length, this_width;
cout << "Enter the length: "; /* < line 9
*/ cin >> this_length;
PAGE 2 OF 12
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;
}
return number;
} /* end of function definition */
/* END OF FUNCTION */
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:
PAGE 4 OF 12
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.
#include<iostream>
#include<cmath>
using namespace std;
/* 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 */
return product;
}
/* END OF FUNCTION */
PAGE 5 OF 12
Program 3.1.1: Functions with Arguments
By the use of a value parameter, we have avoided the (correct but unwanted) output
which would have resulted if the function "factorial(...)" had permanently changed the value of the variable
"whole_number".
We can achieve this as follows using reference parameters, whose types are post-fixed with an "&":
#include<iostream>
using namespace std;
/* 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 */
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".
C++ allows polymorphism, i.e. it allows more than one function to have the same name, provided all functions
are either distinguishable by the typing or the number of their parameters. Using a function name more than
once is sometimes referred to as overloading the function name. Here's an example:
#include<iostream>
using namespace std;
/* MAIN PROGRAM: */
int main()
{ int number_A = 5, number_B = 3, number_C = 10;
cout << "The integer average of " << number_A << " and "; cout
<< number_B << " is ";
cout << average(number_A, number_B) << ".\n\n";
cout << "The integer average of " << number_A << ", ";
cout << number_B << " and " << number_C << " is ";
cout << average(number_A, number_B, number_C) <<
".\n";
return 0;
}
/* END OF MAIN PROGRAM */
One of the main purposes of using functions is to aid in the top down design of programs. During the design
stage, as a problem is subdivided into tasks (and then into subtasks, sub-subtasks, etc.), the problem solver
(programmer) should have to consider only what a function is to do and not be concerned about the details of
the function. The function name and comments at the beginning of the function should be sufficient to inform
the user as to what the function does. (Indeed, during the early stages of program development, experienced
programmers often use simple "dummy" functions or stubs, which simply return an arbitrary value of the correct
type, to test out the control flow of the main or higher level program component.)
Developing functions in this manner is referred to as functional or procedural abstraction. This process is aided
by the use of value parameters and local variables declared within the body of a function. Functions written in
this manner can be regarded as "black boxes". As users of the function, we neither know nor care why they work.
As we have seen, C++ makes heavy use of predefined standard libraries of functions, such as "sqrt(...)". In
fact, the C++ code for "sqrt(...)", as for most functions, is typically split into two files:
• The header file "cmath" contains the function declarations for "sqrt(...)" (and for many other
mathematical functions). This is why in the example programs which call "sqrt(...)" we are able to
write "#include<cmath>", instead of having to declare the function explicitly.
PAGE 8 OF 12
• The implementation file "math.cpp" contains the actual function definitions for "sqrt(...)" and
other mathematical functions. (In practice, many C++ systems have one or a few big file(s) containing all
the standard function definitions, perhaps called "ANSI.cpp" or similar.)
It is easy to extend this library structure to include files for user-defined functions, such as "area(...)",
"factorial(...)" and "average(...)". As an example, Program 6.0.1 below is the same as Program
4.0.1, but split into a main program file, a header file for the two average functions, and a corresponding
implementation file.
#include<iostream>
#include"averages.h"
using namespace std;
int main()
{ int number_A = 5, number_B = 3, number_C = 10;
cout << "The integer average of " << number_A << " and "; cout
<< number_B << " is ";
cout << average(number_A, number_B) << ".\n\n";
cout << "The integer average of " << number_A << ", ";
cout << number_B << " and " << number_C << " is ";
cout << average(number_A, number_B, number_C) <<
".\n";
return 0;
}
Notice that whereas "include" statements for standard libraries such as "iostream" delimit the file name
with angle ("<>") brackets, the usual convention is to delimit user-defined library file names with double quotation
marks hence the line "#include"averages.h" " in the listing above.
The code in the header file "averages.h" is listed below. Notice the use of the file identifier "AVERAGES_H",
and the reserved words "ifndef" ("if not defined"), "define", and "endif". "AVERAGES_H" is a (global)
symbolic name for the file. The first two lines and last line of code ensure that the compiler (in fact, the
preprocessor) only works through the code in between once, even if the line "#include"averages.h"" is
included in more than one other file.
Constant and type definitions are also often included in header files.
PAGE 9 OF 12
#ifndef AVERAGES_H
#define AVERAGES_H
#endif
#include<iostream>
#include"averages.h"
using namespace std;
Note the modularity of this approach. We could change the details of the code in "averages.cpp" without
making any changes to the code in "averages.h" or in the main program file.
PAGE 10 OF 12
7.0 Exercises
Question 1
Add 6 appropriate function declarations for
celsius_of absolute_value_of
print_preliminary_message input_table_specifications
print_message_echoing_input print_table
to the following program, and add the 4 missing function definitions, so that it produces output such as that given
below. Test your program with various inputs.
PAGE 11 OF 12
/* FUNCTION TO CONVERT FAHRENHEIT TO ABSOLUTE VALUE */ double
absolute_value_of(int fahr)
{ return ((static_cast<double>(5)/9) * (fahr ‐ 32)) + 273.15;
}
/* END OF FUNCTION */
Example output:
This program prints out a conversion table of temperatures.
Question 2
Split your answer program to Question 1 into three files: (i) a main program file, (ii) a header file called
"conversions.h" for the functions "celsius_of(...)" and "absolute_value_of(...)", and
(iii) an implementation file for these two functions. Again, test your program with various inputs.
Question 3
(a) Create a header file "statistics.h" and a corresponding implementation file
"statistics.cpp" containing the functions "average(...)" and
"standard_deviation(...)". The functions should
return the average and standard deviation respectively of 1, 2, 3 or 4 real number values. The standard deviation
of the numbers r1, ..., rN is defined as the square root of the average of the expressions
PAGE 12 OF 12
where a is the average value of r1, ..., rN.
Hints:
i. You should take advantage of C++'s facility for polymorphic functions, and overload the
function names.
ii. It is possible to call one function from inside another. iii. You should be doing plenty
of cutting and pasting (not usually desirable!)
(b) Write a program which tests the functions in "statistics.h" again and again with various inputs
until you tell the program that you are finished. Your program should be able to reproduce the following sample
input/output session:
Hints:
i. Design your program "top down". Begin by writing a short main program which calls functions such
as "test_three_values()", which you can define in detail later, after "main".
ii. As a top level control structure, you might want to use a "for loop" with empty initialization and
update statements (this is equivalent to a "while statement").
PAGE 13 OF 12