0% found this document useful (0 votes)
4 views11 pages

Module 3 (Functions) Note

Uploaded by

camyoder49
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)
4 views11 pages

Module 3 (Functions) Note

Uploaded by

camyoder49
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/ 11

FUNCTIONS

Functions are sub program that form part of a large programming project.
Readability is one of the qualities of a good program. When the size of
codes in a program increases tremendously, reading those codes
becomes very difficult and also unmanageable. Functions are used to
segment the program codes so that they are readable and manageable.
This process of segmenting program into component parts is also known
as modularization, and is very useful in object-oriented programming.
Basically, two types of functions exist in programming. These are pre-
defined or built-in-function and user-defined function.

Function are designed so that they can solve a segment of a large


computational problem and return the result after or that segment to the
main body of the program.

4.1 Built-in-Function

The built-in-functions are special functions that come handy in the


standard C++ library. Examples of these are the mathematical functions.
Using any built-in-function will require a header file at the top. The table
4.1 below shows some standard built-in-functions.

Table 4.1 Some functions defined in <cmath> Header file

Function Description Example


acos(x) inverse cosine of x (in radians) acos(0.2) returns 1.36944
asin(x) inverse sine of x (in radians) asin(0.2) returns 0.201358
atan(x) inverse tangent of x (in radians) atan(0.2) returns 0.197396
ceil(x) ceiling of x (rounds up) ceil(3.141593) returns 4.0
cos(x) cosine of x (in radians) cos(2) returns -0.416147
exp(x) exponential of x (base e) exp(2) returns 7.38906
fabs(x) absolute value of x fabs(-2) returns 2.0
floor(x) floor of x (rounds down) floor(3.141593) returns 3.0
log(x) natural logarithm of x (base e) log(2) returns 0.693147
0log10(x) common logarithm of x (base 10) log10(2) returns 0.30103
pow(x,p) x to the power p pow(2,3) returns 8.0
sin(x) sine of x (in radians) sin(2) returns 0.909297
sqrt(x) square root of x tangent of x sqrt(2) returns 1.41421
tan(x) (in radians) tan(2) returns -2.18504

Other functions are contained in other C++ library header files, such as
rand() function contained in the <cstdlib> or <ctime>

Program 4.1: Generating Random Numbers

#include <cstdlib> // defines the rand() function and RAND_MAX


const
#include <iostream>
using namespace std;
int main()
{ // prints pseudo-random numbers:
for (int i = 0; i < 8; i++)
cout << rand() << endl;
cout << "RAND_MAX = " << RAND_MAX << endl;
}
On each run, the computer generates 8 unsigned integers that are
uniformly distributed in the interval 0 to RAND_MAX, which is
2,147,483,647 on this computer. Unfortunately each run produces the
same sequence of numbers. This is because they are generated from the
same “seed.”

Each pseudo-random number is generated from the previously generated


pseudo-random number by applying a special “number crunching”
function that is defined internally. The first pseudo-random number is
generated from an internally defined variable, called the seed for the
sequence. By default, this seed is initialized by the computer to be the
same value every time the program is run. To overcome this violation of
pseudo-randomness, we can use the srand() function to select our own
seed.

Program 4.2: Setting the seed interactively


#include <cstdlib> // defines the rand() and srand() functions
#include <iostream>
using namespace std;
int main()
{ // prints pseudo-random numbers:
unsigned seed;
cout << "Enter seed: ";
cin >> seed;
srand(seed);
for (int i = 0; i < 8; i++)// initializes the seed
cout << rand() << endl;

The line srand(seed) assigns the value of the variable seed to the internal
“seed” used by the rand() function to initialize the sequence of pseudo-
random numbers that it generates. Different seeds produce different
results.

Note that the seed value 12345 used in the third run of the program is the
first number generated by rand() in the first run. Consequently the first
through seventh numbers generated in the third run are the same as the
second through eighth numbers generated in the first run. Also note that
the sequence generated in the second run is the same as the one
produced in. This suggests that, on this computer, the default seed value
is 1.

4.2 User-Defined Functions

Section 4.1 considered the pre-defined functions. In this section, we shall


study the customized functions, designed to meet users’ need. This is the
user-defined function.
4.2.1 Function Definition

For a function to exist, it must first be declared and secondly the body
defined before it can be called anywhere.

Function Declaration

This done when we announce the function by stating its name and
parameters (function header).

Syntax:

return-value-type function-name (parameter-list);


Example:
int fact(num);
Notice that the definition line ends with a semi colon.

Function Definition

Function definition includes stating the function’s header and the body.
The body of the function is expressly the action that the function is
expected to perform when called. In other words, the body is a series of
instruction to be executed during function call.

return-value-type function-name (parameter-list )


{
declaration of local variables;
statements;
return return-value;
}
The syntax is very similar to that of the main program, which is also a
function. main() has no parameters and returns the integer 0 if the
program executes correctly. Hence the return value type of the main()
function is int.
int main()
{
declarations ;
statements ;
return 0;
}

Program 4.3: Computing the factorials of numbers without function

#include<iostream>
using namespace std;
int main()
{
double fact = 1;
int num;
cout<<"Enter the number:"<<endl;
cin>>num;
for(int i=1;i<=num;i++)
{
fact *=i;
}
cout<<"The factorial is:"<<endl;
cout<<fact<<endl;
return 0;
}

Program 4.3 computes the factorial of a number inputted by user. It is a


small program. Consider a case where our program is meant to compute
several components as shown in program 4.4 below.

Program 4.4: Single program to perform multiple computations

#include<iostream>
using namespace std;
int main()
{
double fact = 1;
int num;
cout<<"Enter the number:"<<endl;
cin>>num;
for(int i=1;i<=num;i++)
{
fact *=i;
//cout<<i<<endl;
}
cout<<"The factorial is:"<<endl;
cout<<fact<<endl;
int i;
cout<<"Enter the value to convert"<<endl;
cin>>i;
do
{
cout<<i%2;
i = i/2;
}
while(i>0);
return 0;
}

This program can compute the factorial of a given number and also
computer the conversion from base ten to base two. This kind of problem
can best be solved using functions to separate the different computations.
Now program 4.5 will do just that:

Program 4.5: Program to computer the binary conversion and factorial


using functions

1 #include<iostream>
2 using namespace std;
3 int binary(); //function declaration
double factorial(); //function declaration
4 int main()
5 {
6 int choice;
7 xx: cout<<"Enter a choice:"<<endl<<endl;
8 cout<<"1: Compute Factorial"<<endl;
9 cout<<"2: Computer Binary Conversion"<<endl;
10 cout<<"0: End or Exit"<<endl;
11 cin>>choice;
12 switch(choice)
13 {
14 case 1:
15 factorial();
16 //break;
17 goto xx;
18 case 2:
19 binary();
20 //break;
21 goto xx;
22 default:
23 break;
24 }
25 return 0;
26 }
27 double factorial()
28 {
29 double fact = 1;
30 int num;
31 cout<<"############# Computing Factorial
32 #############"<<endl;
33 cout<<"Enter the number:"<<endl;
34 cin>>num;
35 for(int i=1;i<=num;i++)
36 {
37 fact *=i;
38 //cout<<i<<endl;
39 }
40 cout<<"The factorial is:"<<endl;
41 cout<<fact<<endl;
42 return 0;
43 }
44 int binary()
45 {
46 int i;
47 cout<<"$$$$$$$$$$$$$ Computing Banary
Conversion $$$$$$$$$$$"<<endl;
48 cout<<"Enter the value to convert"<<endl;
49 cin>>i;
50 do
51 {
52 cout<<i%2;
53 i = i/2;
54 }
55 while(i>0);
56 return 0;
57 }

As you can already see, the functions used here do not return any value
to the calling program. Therefore, we are going to demonstrate once more
how to return a value during function call.

Program 5.6: Program to illustrate how to return value to a calling program

1 #include<iostream>
2 using namespace std;
3 double factorial(int num)
4 int main()
5 {
6 int num;
7 cout<<"Enter the number:"<<endl;
8 cin>>num;
9 returned_val = factorial(num)
10
11 cout<<"The factorial is:"<<endl;
12 cout<<returned_val<<endl;
13 }

14 double factorial(int num)


15 {
16 double fact = 1;
17 for(int i=1;i<=num;i++)
18 {
19 fact *=i;
20 //cout<<i<<endl;
21 }
22 return fact;
23 }
The function was declared on line 3, the function was defined on line 14
and called on line 9. In the definition, the value to be returned is indicated
at line 22.
4.4 Passing by value or reference

There are two ways to pass values to functions. Up to now we have looked
only at examples of passing by value. In the passing by value way of
passing parameters, a copy of the variable is made and passed to the
function. Changes to that copy do not affect the original variable’s value
in the calling function. This prevents the accidental corrupting of variables
by functions and so is often the preferred method for developing correct
and reliable software systems. One disadvantage of passing by value
however, is that only a single value can be returned to the caller.

If the function has to modify the value of an argument or has to return


more than one value, then another method is required.

An alternative uses passing by reference in which the function is told


where in memory the data is stored (i.e., the function is passed the
memory address of the variables). In passing the address of the variable
we allow the function to not only read the value stored but also to change
it.

Here’s an analogy. When you tell a friend about a webpage on the course
wiki, you can either print out a copy of the webpage for them; or you can
send them the URL of the webpage. Giving them the copy is ‘pass by
value’; giving them the URL is “pass by reference”. When you ‘pass by
value’, they can manipulate their copy of the page, and their manipulations
have no effect on the original page. When you ‘pass by reference’, they
will be able to edit the contents of the webpage.

To indicate that a function parameter is passed by reference the symbol


& is placed next to the variable name in the parameter list of the function
definition and prototype (but not the function call). Inside the function the
variable is treated like any other variable. Any changes made to it,
however, will automatically result in changes in the value of the variable
in the calling function.

A simple example of passing by reference is given below for a function


that swaps the values of two variables in the calling function’s data by
reading and writing to the memory locations of these variables. Note that
the parameters are mentioned only by name in the function call. This
appears to be the same as calling by value. The function header and
prototype, however, must use the & symbol by the variable name to
indicate that the call is by reference and that the function can change the
variable values.

Program 4.7: Illustrating Call by References

// Program to sort two numbers using call by reference.


// Smallest number is output first.
#include <iostream>
using namespace std;
// Function prototype for call by reference
void swap(float &x, float &y);
int main()
{
float a, b;
cout << "Enter 2 numbers: " << endl;
cin >> a >> b;
if(a>b)
swap(a,b);
// Variable a contains value of smallest number
cout << "Sorted numbers: ";
cout << a << " " << b << endl;
return 0;
}
// A function definition for call by reference
// The variables x and y will have their values changed.
void swap(float &x, float &y)
// Swaps x and y data of calling function
{
float temp;
temp = x;
x = y;
y = temp;
}

You might also like