0% found this document useful (0 votes)
2 views

Lecture 5 Functions-1

Uploaded by

vicentmachicho
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 5 Functions-1

Uploaded by

vicentmachicho
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

FUNCTIONS

A function is an assignment or a task that must be performed to complement the


other part(s) of a program. There are two kinds of functions:

Those supplied to you and those you will be writing.

The functions that are supplied to you are usually in three categories:

Those built-in the operating system, those written in C++ (they are part of the C++
language), and those supplied with your programming environment. The use of these
functions is the same regardless of the means you get them; you should know what a
function looks like, how to create one, what functions are already available, where
they are located, and what a particular function does, how and when to use it.

Function Declaration

In order to create and use a function, you must let the compiler know. Letting the
compiler know about your function means you “declare” it. The syntax of declaring a
function is:

ReturnType FunctionName();
The simplest return type you can use is called, and represented as, void. Using this
keyword, the simplest formula we can use is:

void FunctionName(); // void means the function is not written

Function Names

A function name follows the same rules we have applied to our variables except that
the name of a function will start in uppercase. In addition, use a name that specifies
what the function is expected to do. Usually, a verb is appropriate for a function that
performs an action. Examples of names of functions are Add, Start, Assign, Play, etc.

If the assignment of a function is a combination of words, such as converting a


temperature from Celsius to Fahrenheit, start the name of the function with a verb
and append the necessary words each starting in uppercase (remember that the
name of a function is in one word). Examples include ConvertToFahrenheit,
CalculateArea, LoadFromFile, etc. Some functions will not include a verb. They can
simply represent a word such as Width, Index, New. They can also be a combination
of words; examples include DefaultName, BeforeConstruction, or
MethodOfAssignment.

1
Function Definition

In order to use a function in your program, you have to let the compiler know what
the function does. To let the compiler know what the function is meant to do, you
have to “define” it; which also means describing its behavior. The formula to define a
function is:

void FunctionName() {Body}


You define a function using the rule we applied with the main() function. Define it
starting with its return value (if none, use void), followed by the function name, its
argument (if any) between parentheses, and the body of the function. Once you have
defined a function, other functions can use it.

Function Body

As an assignment, a function has a body. The body of the function describes what the
function is supposed to do. The body starts with an opening curly bracket “{“ and
ends with a closing curly bracket “}”. Everything between these two symbols belongs
to the function.

void Message() {};


In the body of the function, you describe the assignment the function is supposed to
perform. As simple as it looks, a function can be used to display a message. Here is
an example:

void Message(){ cout << "This is C++ in its truest form.";}


A function can also implement a complete behavior. For example, on a program used
to perform geometric shape calculations, you can use different functions to handle
specific tasks. Imagine you want to calculate the area of a square. You can define a
particular function that would request the side of the square:

cout << “Enter the side of the square: “;

cin >> Side;


and let the function calculate the area using the formula Area = Side * Side. Here is
an example of such a function:

void SquareArea()
{
double Side;

cout << "\nEnter the side of the square: ";


cin >> Side;

2
cout << "\n Square characteristics:";
cout << "\n Side = " << Side;
cout << "\n Area = " << Side * Side;
}

Calling Functions

One of the main reasons of using various functions in your program is to


isolate assignments; this allows you to divide the jobs among different
entities so that if something is going wrong, you might easily know where
the problem is. Functions trust each other, so much that one function does
not have to know HOW the other function performs its assignment. One
function simply needs to know what the other function does, and what that
other function needs.

Once a function has been defined, other functions can use the result of its
assignment. Imagine you define two functions A and B.

If Function A needs to use the result of Function B, function A has to use the name of
function B. This means that Function A has to “call” Function B:

When calling one function from another function, provide neither the return value nor
the body, simply type the name of the function and its list of arguments, if any. For
example, to call a function named Welcome() from the main() function, simply type
it, like this:

int main()
{
Message(); // Calling the Message() function

return 0;
}

3
The compiler treats the calling of a function depending on where the function is
declared with regards to the caller. You can declare a function before calling it. Here
is an example:

#include <iostream.h>

void Message()
{
cout << "This is C++ in its truest form.";
}

int main()
{
Message(); // Calling the Message() function

return 0;
}

Calling a Function Before Defining it

The example we saw above requires that you define a function before calling it. C++,
like many languages, allows you to call a function before defining it. Unlike many
languages, in C++, when calling a function, the compiler must be aware of the
function. This means that, you must at least declare a function before calling it. After
calling the function, you can then define it as you see fit. Here is an example:

#include <iostream.h>

int main()
{
void Message();

cout << "We will start with the student registration process.";
Message(); // Calling the Message() function

return 0;
}

Returning a Value

void Functions

A function that does not return a value is declared and defined as void. Here is an
example:
4
void Introduction()
{
cout << "This program is used to calculate the areas of some shapes.\n"
<< "The first shape will be a square and the second, a rectangle.\n"
<< "You will be requested to provide the dimensions and the program "
<< "will calculate the areas";
}

Any function could be a void type as long as you are not expecting it to return a
specific value. A void function with a more specific assignment could be used to
calculate and display the area of a square. Here is an example:

void SquareArea()
{
double Side;

cout << "\nEnter the side of the square: ";


cin >> Side;

cout << "\nSquare characteristics:";


cout << "\nSide = " << Side;
cout << "\nArea = " << Side * Side;
}
When a function is of type void, it cannot be displayed on the same line with the
cout extractor and it cannot be assigned to a variable (since it does not return a
value). Therefore, a void function can only be called.

The Type of Return Value

The purpose of a function identifies what the function is meant to do. When a
function has carried its assignment, it provides a result. For example, if a function is
supposed to calculate the area of a square, the result would be the area of a square.
The result of a function used to get a student’s first name would be a word
representing a student’s first name. The result of a function is called a return value. A
function is also said to return a value.

There are two forms of expectations you will have from a function: a specific value or
a simple assignment. If you want the function to perform an assignment
without giving you back a result, such a function is qualified as void and
would be declared as

5
void FunctionName();
A return value, if not void, can be any of the data types. This means that a function
can return a char, an int, a float, a double, a bool, or a string. Here are examples
of declaring functions by defining their return values:

double FunctionName();
char FunctionName();
bool FunctionName();
string FunctionName();
If you declare a function that is returning anything (a function that is not void), the
compiler will need to know what value the function returns. The return value must be
the same type declared. The value is set with the return keyword.

If a function is declared as a char, make sure it returns a character (only one


character). Here is an example:

char Answer()
{
char a;

cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? ";
cin >> a;

return a;
}
A good function can also handle a complete assignment and only hand a valid value
to other calling functions. Imagine you want to process member’s applications at a
sports club. You can define a function that would request the first and last names;
other functions that need a member’s full name would request it from such a function
without worrying whether the name is complete. The following function is in charge of
requesting both names. It returns a full name that any desired function can use:

string GetMemberName()
{
string FName, LName, FullName;

cout << "New Member Registration.\n";


cout << "First Name: ";
cin >> FName;
cout << "Last Name: ";
cin >> LName;

FullName = FName + " " + LName;


return FullName;

6
}

The return value can also be an expression. Here is an example:

double SquareArea(double Side)


{
return (Side * Side);
}
A return value could also be a variable that represents the result. Here is example:

double SquareArea(double Side)


{
double Area;

Area = Side * Side;


return Area;
}
If a function returns a value (other than void), a calling function can assign its result
to a local variable like this:

Major = GetMajor();
Here is an example:

#include <iostream.h>

int GetMajor()
{
int Choice;

cout << "\n1 - Business Administration";


cout << "\n2 - History";
cout << "\n3 - Geography";
cout << "\n4 - Education";
cout << "\n5 - Computer Sciences";
cout << "\nYour Choice: ";
cin >> Choice;

return Choice;
}

int main()
{
int Major;

7
cout << "Welcome to the student orientation program.";
cout << "Select your desired major:";

Major = GetMajor();

cout << "You select " << Major;


cout << "\n";
return 0;
}

Example

Imagine you want to write a function that would calculate an item’s purchase price based on the item’s
store price added the tax. The tax rate is a percentage value. This means that a tax rate set at 7.50% in
C++ terms is equal to 0.075 (because 7.50/100 = 0.075). The tax amount collected on a purchase is taken
from an item’s price; its formula is:

TaxRate
Tax Amount = Item Price * 100

The formula of calculating the final price of an item is:

Final Price = Item Price + Tax Amount

Here is an example:

#include <iostream.h>

int main()

double itemPrice, taxRate;

double PurchasePrice(double itemPrice, double taxRate);

cout << "Enter the price of the item in Tsh: ";

cin >> itemPrice;

cout << "Enter the tax rate in percentage: ";

8
cin >> taxRate;

cout << "\nThe final price is Tsh: " << PurchasePrice(itemPrice, taxRate);

cout << "\n\n";

return 0;

double PurchasePrice(double itemPrice, double taxRate)

double price;

price = itemPrice + (itemPrice * taxRate / 100);

return price;

Here is an example of running the program:

Enter the price of the item: 125.95

Enter the tax rate: 5.75

The final price is: 133.192

Exercises:

1. Use functions to write a program that computes the area of a right angled triangle.

2. Using a Function, write a C++ Program that finds the average of any four numbers.

3. Use a function to find the maximum of any two integers.

You might also like