You are on page 1of 21

Republic of the Philippines

POLYTECHNIC UNIVERSITY OF THE PHILIPPINES


LOPEZ QUEZON, BRANCH

Module 6. Functions

Contents
6.1 Pre-defined functions
6.1.1 String functions
6.1.2 Numeric functions
6.2 User defined functions
6.3 Void functions

Objectives
At the end of the course, the students should be able to:
✓ Understand the components of a function
✓ Differentiate pre-defined and user defined function
✓ Identify the different string and character functions used in C++;
✓ Discuss the different mathematical function;
✓ Discuss the different string functions;

OMP 20023 PROGRAMMING 1 1


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

Introduction
A function is a block of code that performs a task. Every C++ program contains at least
one function which is named main; however, most C++ programs contains many functions. Some
of the functions used in a program are built into C++ language. The code for these built-in
functions or pre-defined functions resides in C++ libraries, which are special files that come
with the C++ language. Other program functions, like main, are created by the programmer.
These functions often are referred to as a program-defined functions also called as user-
defined function, because the function definitions are contained in the program itself rather than
in a different file. But why would a programmer need more than the main function? One reason
is to avoid the duplication of code. For instance, assume that the same task needs to be
performed in more than one section of a program. Rather than enter the appropriate code in
each of those sections, it is more efficient for the programmer to enter the code once, in a
function. Any section in the program can then call (or invoke) the function to perform the required
task. Program-defined functions allow large and complex programs, which typically are written
by a team of programmers, to be broken into small and manageable tasks. Each member of the
team is assigned one or more tasks to code as a function. When each programmer completes
his or her functions, all of the functions are gathered together into one program.

In other words, program-defined functions allow more than one programmer to work on a
program at the same time, decreasing the time it takes to write the program. Typically, a
program’s main function is responsible for calling (or invoking) each of the other program-defined
functions. However, any program-defined function can call any other program-defined or build-
in function. All program-defined and build-in functions are categorized as either value-returning
or void functions. Value-returning functions return a value, whereas void functions do not return
a value. All value-returning functions, whether build-in or program-defined, perform a task and
then return precisely one value after the task is completed.

OMP 20023 PROGRAMMING 1 2


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

6.1 Pre-defined Functions

As mentioned earlier, pre-defined functions are program built into C++ language that
reside in C++ libraries, these programs are special files that come with the C++ language. They
are a set of subroutines that perform standard mathematical functions included in a programming
language; either included in a program at compilation time, or called when a program is executed.

C++ Library Functions

➢ Library functions are the built-in functions in C++ programming.

➢ Programmers can use library functions by invoking the functions directly; they don't need
to write the functions themselves.

➢ Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
➢ In order to use library functions, we usually need to include the header file in which these
library functions are defined.

➢ For instance, in order to use mathematical functions such as sqrt() and abs(), we need
to include the header file cmath.

Example: C++ Program to Find the Square Root of a Number

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double number, squareRoot;

number = 25.0;

// sqrt() is a library function to calculate the square root


squareRoot = sqrt(number);

OMP 20023 PROGRAMMING 1 3


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

cout << "Square root of " << number << " = " << squareRoot;

return 0;
}

Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root of a number.
The function declaration of sqrt() is defined in the cmath header file. That's why we need to use
the code #include <cmath> to use the sqrt() function.

6.1.1 String functions

The instructions for creating a string object, which can be either a string variable or a string
named constant, are contained in a string file. Therefore, for a program to use the string class, it
must contain the #include<string> directive.

Here are some of the string functions that you can use:

String Function
getline() getline function will continue to read the characters entered at the keyboard until
it encounters the delimiter character.
ignore() ignore function can be used to instruct the computer to first read then ignore
characters stored in the cin object.
length() ;ength function is used to determine the number of characters contained in a
string variable.
substr() substr function allows you to access any number of characters contained in a
string variable; it then return the characters.
find() find function is used to search the contents of a string variable to determine
whether it contains a specific sequence of characters.
erase() erase function is used to remove one or more characters located anywhere in a
string variable

OMP 20023 PROGRAMMING 1 4


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

replace() replace function replaces a sequence of characters in a string variable with


another sequence of character.
insert() insert function is used for inserting characters within a string variable.
assign() assign function is used to duplicate a specified number of times and then assign
the resulting string to a string variable.
string concatenation string concatenation refers to the process of concatenation (or linking) strings
together. You concatenate a string using the concatenation operator, which is
the + sign in C++.

Sample program using string functions.

Problem Specification
Create a program that allows the user to enter a company’s annual income. The program should
remove any commas and spaces from the annual income before displaying it on the screen.

Input
Annual income
Processing
Processing items:
Character subscript(0)

Output
Annual Income with no commas or spaces

OMP 20023 PROGRAMMING 1 5


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

C++ Code

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main()
{
string income = "";
int subscript = 0;

cout << "Anual income (-1 to end): ";


getline(cin, income);

while(income != "-1")
{
while(subscript < income.length())
{
if(income.substr(subscript, 1) == "," || income.substr(subscript, 1) == " ")
income.erase(subscript, 1);
else
subscript +=1;
}

cout << "Annual income with no commas " << "or space: $ " << income << endl <<
endl;
cout << "Annual income (-1 to end): ";
getline(cin, income);
subscript = 0;
}

system("pause");

return 0;
}

OMP 20023 PROGRAMMING 1 6


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

OUTPUT

Figure 6.1 Sample output for string function program

6.1.2 Numeric functions

Sr.No Function & Purpose

1
double cos(double);
This function takes an angle (as a double) and returns the cosine.

2
double sin(double);
This function takes an angle (as a double) and returns the sine.

3
double tan(double);
This function takes an angle (as a double) and returns the tangent.

4
double log(double);
This function takes a number and returns the natural log of that number.

OMP 20023 PROGRAMMING 1 7


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

5
double pow(double, double);
The first is a number you wish to raise and the second is the power you wish to raise it t

6
double hypot(double, double);
If you pass this function the length of two sides of a right triangle, it will return you the
length of the hypotenuse.

7
double sqrt(double);
You pass this function a number and it gives you the square root.

8
int abs(int);
This function returns the absolute value of an integer that is passed to it.

9
double fabs(double);
This function returns the absolute value of any decimal number passed to it.

10
double floor(double);
Finds the integer which is less than or equal to the argument passed to it.

OMP 20023 PROGRAMMING 1 8


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

Sample program using math functions.

C++ Code

#include <iostream>
#include <cmath>
using namespace std;

int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;

// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;

return 0;
}

OUTPUT

Figure 6.2 Sample output for math function program

OMP 20023 PROGRAMMING 1 9


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

6.2 User-defined Functions

A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.

The C++ standard library provides numerous built-in functions that your program can call.
For example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions.

A function is known with various names like a method or a sub-routine or a procedure etc.

Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}

A C++ function definition consists of a function header and a function body. Here are all the parts
of a function −

• Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.

• Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.

• Parameters − A parameter is like a placeholder. When a function is invoked, you pass a


value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.

OMP 20023 PROGRAMMING 1 10


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

• Function Body − The function body contains a collection of statements that define what
the function does.

Example
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and return the biggest of both −
// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Function Declarations
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.

A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), following is the function declaration −

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is
required, so following is also valid declaration −

int max(int, int);

Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function at the
top of the file calling the function.

OMP 20023 PROGRAMMING 1 11


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use
a function, you will have to call or invoke that function.

When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when it’s return statement is executed or when its
function-ending closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value. For example −

#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2) {
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

OMP 20023 PROGRAMMING 1 12


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

While running final executable, it would produce the following result −

Max value is : 200

Sample program using user defined function.

Problem Specification
Create a program that allows the user to enter a rectangle’s length and width (in feet). The program
should calculate and display the rectangle’s area in square feet.

Input
length(feet)
lidth(feet)
Processing
Algorithm:
1. Enter the length and width
2. Call the getRectangleArea function to calculate the area; pass the length and width
Output
area (square feet)

OUTPUT

Figure 6.1 Sample output for program above using user defined function

OMP 20023 PROGRAMMING 1 13


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

C++ Code

#include <iostream>

using namespace std;

double getRectangleArea(double len, double wid);

int main()
{
double length = 0.0;
double width = 0.0;
double area = 0.0;

cout << "Rectangle length (in Feet): ";


cin >> length;
cout << "Recatanle width (in Feet): ";
cin >> width;

area = getRectangleArea(length, width);


cout << "Area : " << area << " square feet" << endl;

return 0;
}
double getRectangleArea(double len, double wid)
{
return len * wid;
}

6.3 Void Functions

Like value-returning functions, void functions also perform a task. However, unlike value-
returning functions, void functions do not return a value after completing their task. A program
might use a program-defined void function to display information (such as title and column
headings) at the top of each page in a report. Rather than duplicating the required code several
times in the program, the code can be entered once in a void function. The program then calls
the void function whenever and wherever it is needed.

A void function is appropriate in this situation because the function does not need to return
a value after completing a task.

OMP 20023 PROGRAMMING 1 14


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

Syntax:

void functionName([parameterList])
{
one or more statements
}

Example 1:
void displayLine()
{
cout << “ ---------------------------------------- “ << endl;
}

The function displays a straight line composed of hyphens.

Example 2:
void displayCompanyInfo()
{
cout << “ABC Company” << endl;
cout << “Chicago, Illinois” << endl;
}

The function displays a company’s name, city, and state.

Example 3:
void displayTotalSales(int total)
{
cout << “Total Sales: $” << total << endl;
}

The function displays the total sales it receives from the statement that invoked it.

OMP 20023 PROGRAMMING 1 15


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

Sample program using void function.

#include <iostream> OUTPUT


using namespace std;

void displayLine();
void displayCompanyInfo();
void displayTotalSales(int total);

int main()
{
int store1Sales = 0;
int store2Sales = 0;
int totalSales = 0;

cout << "Store 1's sale: ";


cin >> store1Sales;
cout << "Store 2's sale: ";
cin >> store2Sales;

totalSales = store1Sales + store2Sales;

displayLine();
displayCompanyInfo();
displayTotalSales(totalSales);
displayLine();

return 0;
}
void displayLine()
{
cout << " ------------------------------- " << endl;
}
void displayCompanyInfo()
{
cout << "ABC Company" << endl;
cout << "Chicago, Illinois" << endl << endl;
}
void displayTotalSales(int total)
{
cout << "Total Sales: $ " << total << endl;
}

OMP 20023 PROGRAMMING 1 16


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

For additional discussion and sample program, watch the videos below. You can also
click on the text hyperlink to be redirected to the video

Watch: Videos on youtube- https://tinyurl.com/y6oop8j6


➢ Buckys C++ Programming Tutorials - 9 - Functions
➢ Buckys C++ Programming Tutorials - 10 – Creating Functions that use
Parameters
➢ Buckys C++ Programming Tutorials - 11 – Functions that use Multiple
Parameters

Read resources:
➢ https://www.w3schools.com/cpp/cpp_syntax.asp
➢ https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm

OMP 20023 PROGRAMMING 1 17


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

Coding Exercises:
Using CodeBlocks, code and run the following sample program and try to analyze and understand
each program’s output.

Sample Program 1:

Create a program that will generate two random numbers from 1 to 10. The user will then input
the sum of the two numbers. The program should be able to validate if the user’s answer is correct
or not. If the user’s answer is correct it will then display the “Correct” word, if not, it then display
the correct answer. The user will have to answer 5 different sets addition of two random numbers.
Once the user is done answering, the program will then display the total score the user gets based
on the correct answer they got.

Algorithm (pseudocode) Sample Output:

Input:

user’s answer

Processing:

First random number (1 to 10)


Second random number (1 to 10)
Counter (1 to 5)
Correct answer

Output:
Additional problem message

Total Score of correct answer

OMP 20023 PROGRAMMING 1 18


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

C++ Code

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int getRandomNumber();
void printLang();

int main()
{ int num1 = 0;
int num2 = 0;
int correctAnswer = 0;
int userAnswer = 0;
int score =0;

srand(static_cast<int>(time(0)));

for (int x=1; x <=5; x +=1)


{ num1 = getRandomNumber();
num2 = getRandomNumber();
correctAnswer = num1 + num2;
cout << "What is the sum of" << num1 << "+" << num2 << " ?" << endl;
cin >> userAnswer;

if (userAnswer == correctAnswer)
{
cout << "Correct! " << endl;
score += 1;
}
else
{
cout << "Sorry, the correct answer is " << correctAnswer << "." << endl;
}
}

printLang();
cout<< "Total Score: " << score << " out of 5." << endl;
return 0;
}
int getRandomNumber()
{
int randInteger = 0;
randInteger = rand()%(10-1+1);
return randInteger;
}
void printLang()
{ OMP 20023 PROGRAMMING 1 19
cout<< "---------------------------------"<< endl;
}
Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

Coding Exercises:
Using CodeBlocks, code and run the following sample program and try to analyze and understand
each program’s output.

Sample Program 2:

Create a program that can add, subtract, multiply and divide two numbers. The program will ask
the user to enter an operation, it will then print the answer. The program should also contain a
loop, which asks the user if he/she wants to compute again. If the user answers, y or yes, the
program will clear the previous operation and will then ask the user to another a new operation.
Once the user answer’s n or no, only then will the program ends.

Algorithm (pseudocode) Sample Output:

Input:

Mathematical operation

Processing:

Identify the operation (+,-,*,/)


do the operation
Print answer
Ask the user to compute again

Output:
answer

OMP 20023 PROGRAMMING 1 20


Republic of the Philippines
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
LOPEZ QUEZON, BRANCH

C++ Code

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

using namespace std;

float add(float a, float b);


float sub(float a, float b);
float mul(float a, float b);
float div(float a, float b);

int main()
{
float num1 = 0.0;
float num2 = 0.0;
float ans = 0.0;
char op;
char loop = 'Y';

while (loop == 'Y' || loop == 'y'){

cout << "Please enter your input using the following format: 1 + 1 " << endl << endl;
cin >> num1 >> op >> num2;

if( op == '+')
{ ans=add(num1, num2); }
else if(op == '-')
{ ans=sub(num1, num2); }
else if(op == '/')
{ ans=div(num1, num2) }
else if(op == '*')
{ ans=mul(num1, num2); }
cout << "Answer is : " << ans << endl;
cout << endl;
cout << "Do you want to compute again? ";
cin >> loop;
system("CLS");
ans = 0; num1=0; num2=0;
}
return 0;
}
float add(float a, float b)
{ return a + b; }
float sub(float a, float b)
{ return a - b; }
float mul(float a, float b)
{ return a * b; } OMP 20023 PROGRAMMING 1 21
float div(float a, float b)
{ return a / b; }

You might also like