0% found this document useful (0 votes)
3 views14 pages

Notes 3

The document discusses the use of predefined library functions in C++, specifically focusing on the sqrt function from the cmath library. It explains how to include libraries, the importance of function prototypes, and provides examples of valid and invalid function calls. Additionally, it covers the standard library functions like abs, exit, rand, and srand, along with example programs demonstrating their usage.

Uploaded by

mblola2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Notes 3

The document discusses the use of predefined library functions in C++, specifically focusing on the sqrt function from the cmath library. It explains how to include libraries, the importance of function prototypes, and provides examples of valid and invalid function calls. Additionally, it covers the standard library functions like abs, exit, rand, and srand, along with example programs demonstrating their usage.

Uploaded by

mblola2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

ibrary Functions

----------------

In this section we turn our attention to using predefined library


functions. We have already seen a limited use of library functions
(recall the use of the fabs library function).

C++ contains many different libraries. In order to access a


function
within a particular library is is neccessary to #include
<library_name>
in your C++ program. Before discussing the different libraries
available
in C++, we will give an example of the sqrt function which is found
in the
cmath library (or the old C math.h library).

sqrt function
------------

The two real roots of the general quadratic equation:

2
ax + bx + c = 0 ,
2
are given by the formula : x = -b +- sqrt(b - 4ac)
____________________
2a

(we will omit complex roots for the time being...).

The following program reads in three doubles for the values of


a,b,c. It checks that the value of

b - 4*a*c is greater than 0. If this is true, then it computes the


two real roots by PASSING a value to the sqrt library function:

// Author: Ted Obuchowicz


// Jan. 28, 2002
// example program illustrating use of
// square root library function found in the cmath library
#include <iostream>
#include <string>
#include <cmath> // needed for the definition of the sqrt function

using namespace std;

int main()
{

cout << "Enter the three coefficients of the equation: a, b, c " ;


double a,b,c;
cin >> a >> b >> c;
double radical;
radical = (b*b) - (4*a*c) ;

if ( (a != 0) && (radical > 0) )


{
double first_root = (-b + sqrt(radical)) / (2*a);
double second_root = (-b - sqrt(radical)) / (2*a);
cout << "The roots are " << first_root << " and " <<
second_root << endl;
}
else
cout << "The equation does not have two real roots " << endl;

return 0;
}

When the program gets to the two lines:

double first_root = (-b + sqrt(radical)) / (2*a);


double second_root = (-b - sqrt(radical)) / (2*a);

a sequence of events occurs:

1) the appearance of the expression sqrt(radical) in the two


lines will cause a FUNCTION INVOCATION to occur. We say that the
variable radical is a FUNCTION ARGUMENT. The sqrt function
function
receives the value of this variable, it then calculates the value
of the
square root of whatever value was passed to it.

2) When the function has computed the calculation of the square


root,
it returns the value back to the program.

In programming terminology, we see that there is an "invocation" of


the square root function which "returns" a value back to the
"calling
program".

In order to make use of library functions we must first know several


things concerning the function:

1) the name of the function


2) the number and type of arguments that the function expects
3) the return type of the function.

All this information is contained in what is known as the


function prototype. For example, the prototype for the
sqrt function is:

double sqrt(double) ;

The above prototype (which is found in the math.h library file,


which is
located in /usr/include/math.h on our UNIX systems) reveals the
following:

the function is called sqrt, it expects a single (formal) parameter


of type double.
(the parameter list is the part enclosed in () after the function
name).
The function returns a single value of type double.

The type of the actual parameter which is passed to a function


should
MATCH the type of the formal parameter given in the function
prototype.
If there is mismatch between the types of the formal parameter and
the
actual arguments passed to the function, the compiler will attempt
to
convert the types if possible (for example, promoting an int to a
double).
If the usual conversions cannot convert the actual argument into the
type
specified by the formal parameter, the compiler gives up and report
and
error.

Here are some examples of legal invocations of sqrt:

// Author: Ted Obuchowicz


// Jan. 28, 2002
// example program illustrating use of
// legal square root invocation calls

#include <iostream>
#include <string>
#include <cmath> // needed for the definition of the sqrt function

using namespace std;

int main()
{

cout << sqrt(2) << endl; ; // the integer 2 will be promoted to a


double and a double will be ret
urned
int four = 4;
cout << sqrt(four) << endl ; // legal
cout << sqrt(-2.0) << endl ; // believe it or not this will display
Nan
return 0;
}

The program output is:

ted@flash Programs 9:03pm >legal_square_root


1.41421
2
NaN
ted@flash Programs 9:03pm >

One can even do something of the sort illustrated in the next


program:

// Author: Ted Obuchowicz


// Jan. 31, 2002
// example program illustrating use of
// square root library function found in the cmath library

#include <iostream>
#include <string>
#include <cmath> // needed for the definition of the sqrt function

using namespace std;

int main()
{

double num ;
cin >> num;
double quadric_root = sqrt(sqrt(num));
cout << quadric_root << endl;

return 0;
}

Some illegal invocations (where the usual conversions are not able
to
convert the actual argument into the type defined by the formal
parameter)
are:

// Author: Ted Obuchowicz


// Jan. 28, 2002
// example program illustrating use of
// illegal square root invocation calls

#include <iostream>
#include <string>
#include <cmath> // needed for the definition of the sqrt function

using namespace std;

int main()
{

cout << sqrt(3.4, 5.6) << endl ;

return 0;
}

The errors reported by the compiler are:

ted@flash Programs 9:09pm >g++ -o illegal_square_root


illegal_square_root.C
illegal_square_root.C: In function `int main()':
/usr/include/math.h:133: too many arguments to function `double
sqrt(double)'
illegal_square_root.C:20: at this point in file

Note that the compiler reports the line number in the include file
/usr/include/math.h which contains the prototype and it also
indicates
the line number in the source code where the illegal invocation
appears.

A function can return a single value, or it can return no value.


For functions which do not return a value, the return type in the
function prototype must be the built-in type called void:

void this_function_returns_no_value(int, int);

The above is a prototype of a function which takes two formal


arguments
of type int and does not return a value. You may think it strange
that
we would decleare and define functiosn with no return types, but
they are usefulin displaying messages:

(the following program uses what is known as a user-defined


function, these
will be explained in greater detail in a later section):

// Author: Ted Obuchowicz


// Jan. 7, 2002
// example program illustrating use of
// of a function with no return value

#include <iostream>
#include <string>

using namespace std;


// define the function first

void this_function_returns_no_value(int first, int second)


{
cout << "first is " << first << endl;
cout << "second is " << second << endl;
}

int main()
{

this_function_returns_no_value(1,2);
this_function_returns_no_value(3,4);
this_function_returns_no_value(34,7869);

return 0;
}

The output is:

ted@flash Programs 9:22pm >void_function


first is 1
second is 2
first is 3
second is 4
first is 34
second is 7869
ted@flash Programs 9:22pm >

Some Common C++ libraries


-------------------------

We will now examine some of the common C++ libraries and


the functions they contain. We first discuss various methods
of including libraries.

The standard C libraries are those with a .h suffix in their library


name. They would be included as :
#include <stdlib.h>

C++ libraries do not require the .h suffix and are included


by simply specifiying the name of the library within the <>
brackets as in:

#include <iostream>

Some C++ are derived from the standard C libbraries and have a
c as the prefix as in:

#include <cassert>
#include <cmath>

Again, for the derived libraries, there is no need for the .h suffix
in the library name.

The best source of information for access to standard libraries is


your
compiler documentation and a language reference manual.

The stdlib library


------------------

This is a C-based library called "standard lib". It contains a


collection
of miscellaneous functions and type definitions. Some of the
commonly
used functions found in stdlib are:

int abs(int) : returns the absolute value of the integer argument


passed

void exit(int) : causes the calling program to terminate with a


return value
equal to the parameter passed to the function:

exit(0); // terminate program with a return value of 0


exit(1); // terminate program with a return value of 1
#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

int main()
{

exit(1);
cout << "This will never be printed " << endl;

This program when compiled and run will do nothing and control
will be passed back to the operating system.

Here is an interesting experiment to perform on a UNIX system.


From a X-window, type the following from the UNIX prompt:

exit(0)

What happens to your window? It has disappeared. exit is actually


a system call. C was originallt developed to write the UNIX
operating
system. There is a strong coupling between UNIX and the C-language.

int rand() : returns a (somewhat) random number between 0 and


RAND_MAX , where RAND_MAX is an operating system
defined value. (On our UNIX system RAND_MAX is
defined in
/usr/include/stdlib.h as #define RAND_MAX
32767 )
The default seed value is set to 1.
void srand(unsigned int val) : Sets the seed value used by the rand
function
to the value given in the formal
paramter.

Example programs making use of rand() and srand():

// Author: Ted Obuchowicz


// Jan. 29, 2002
// example program illustrating use of

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

int main()
{

for(int i = 0 ; i <= 9 ; i++)


cout << rand() << endl; // print out 10 random numbers between 0
and 32767
return 0;
}

EVERY time that we run the above program it will produce the values:

16838
5758
10113
17515
31051
5627
23010
7419
16212
4086

If we wish to produce different sequences every time we call the


rand() function, we
must ensure that the starting seed value is different:

// Author: Ted Obuchowicz


// Jan. 29, 2002
// example program illustrating use of
// random seed function

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

int main()
{
int seed_value;
cout << "Please enter a seed value" ;
cin >> seed_value;
srand(seed_value);
for(int i = 0 ; i <= 9 ; i++)
cout << rand() << endl; // print out 10 random numbers between 0
and 32767
return 0;
}

The program's output when we run it two times with different initial
seed values
is:

ted@flash Programs 12:38pm >random_seed


Please enter a seed value 3
17747
7107
10365
8312
20622
15796
4173
15543
24392
28207
ted@flash Programs 12:38pm >random_seed
Please enter a seed value 890
11116
32040
23590
22778
15455
20008
22032
30327
15027
27003

We can modify the above program to display random numbers between 0


and 6
by simply changing the :

cout << rand() % 7 << endl; // print out 20 random numbers between
0 and 6

The output is now:

0
1
3
0
3
6
4
6
6
5
0
2
0
1
2
4
5
4
6
6
2

An "upside-down" histogram which plots the frequency


of occurrence of each number is:

0 1 2 3 4 5 6
--------------------------------------------------
* * * * * * *
* * * * * * *
* * * *
* *

You can see that even for a very small sample space of
20 values, the distribution is quite uniform. Each of
the 7 values between 0 and 6 is equally likely to occur.

You might also like