By Mr. Sokunbi, M.A.
Computer Tech Dept, YabaTech
COM313
INTRODUCTION TO C++
By
Mr. Sokunbi, M.A.
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
C++ Functions
A large program can sometimes become too long
and very difficult to manage.
To make programs manageable, programmers
modularize them into subprograms
In C++, these subprograms are called functions
Functions can be part of the main programs or
they can be compiled and tested separately, and
re-sused in other programs
There are two main types of functions in C++
(i) Standard C++ library functions or built-in functions
(ii) User-defined Functions
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Standard C++ Library Functions
• The Standard C++ Library is a collection of pre-defined
functions and other program elements which are
accessed through header files.
• For example, the “cin” and “cout” that we have been
using for input and output operations are defined in
the header file called <iostream>
• Other functions such as getchar() is defined in <stdio>,
the sqrt() function is defined in <cmath>, the rand()
function defined in <cstdlib>, and the time() function
defined in <ctime>
• In general, header files define functions and other
program elements
• Note that some of the functions used in C++ are defined
in C language library
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Examples of C++ Library Functions Defined in
<cmath> Header File
• Function Description Example
• 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
• log10(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 sqrt(2) returns 1.41421
• tan(x) tangent of x (in radians) tan(2) returns -2.18504
• Some C library functions
• abs(n) returns absolute value of n <cstdlib> header file e.g int abs(n)
• getchar() returns the next character <cstdio> header file e.g int getchar()
• Notice that every mathematical function returns a double type. If an integer is
passed to the function, it is promoted to a double before the function
processes it.
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Some Header Files In Standard C++ Library
• Header File Description
• <iostream> Defines C++ standard input/output functions
• <iomanip> Defines functions stream manipulation that formats stream data
• <cassert> Defines the assert() function
• <ctype> Defines functions to test characters
• <cfloat> Defines constants relevant to floats
• <climits> Defines the integer limits on your local system
• <cmath> Defines mathematical functions
• <cstdio> Defines functions for standard input and output
• <cstdlib> Defines utility functions
• <cstring> Defines functions for processing strings
• <ctime> Defines time and date functions
• These , (except iosream and iomanip) are derived from the Standard C Library.
They are used the same way that Standard C++ header files such as <iostream>
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Programming Example
Write a C++ program to compute the square root of 81
#include <cmath> // defines the sqrt() function
#include <iostream> // defines the cout object
#include <cstdio> //defines getchar()
using namespace std;
int main()
{ // tests the sqrt() function:
int n = 81; int k =0;
k = sqrt(n);
cout << « \n\t The square root = " << k <<endl;
getchar();
return 0;
}
OR
#include <cmath> // defines the sqrt() function
#include <iostream> // defines the cout object
#include <cstdio> //defines getchar() or #include<stdio>
using namespace std;
int main()
{ // tests the sqrt() function:
cout << « \n\t The square root of 81 = " << sqrt(81) <<endl;
getchar();
return 0; }
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Brief Explanation on Functions
In the above example, the actual code performing the
square root is hidden away within the standard C++
library file - cmath
The appropriate header file must be included in your
program before the compiler can execute the function
call e.g sqrt(n)
The expression n in the function call (sqrt(n)) is called
the argument or actual parameter of the function
In this example, argument is passed by value
Class Work
Write a C++ program to compute the square and the cube of all integers
from 1 – 10 using built-in functions. Display your result as a table of
Num, Square & cube
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
User Defined Functions
C++ also allows users to define their own functions to satisfy
their exact need
A user defined function has two parts
i) function’s head (ii) function’s body
The syntax for the head is:
return_type name(parameter_list)
This specifies for the compiler the function’s return type (the type
of data to return), the function’s name, and the function’s
parameter list or arguments
e.g int cube(n) - function’s head
The body of the function is a block of code that follows its head.
It contains the code that performs the function’s actions,
including the return statement that specifies the value that the
function sends back to the place where it was called from.
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
User Define Functions
Example of a complete function:
int cube(x)
{
return(x*x*x);
}
In the above, int cube(x) is the function head
while { return(x*x*); } is the body of the
function.
A function’s return statement serves 2 purposes –
(i) it terminates the execution of the function
(ii) It returns a value to the calling program
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Function Test Drivers
• Whenever you create your own function, you should immediately test it with
a simple program.
• Such a program is called a test driver for the function.
• Its only purpose is to test the workability of the function.
#include <iostream>
#include <stdio>
int cube(int x)
{ // returns cube of x:
return x*x*x;
}
int main()
{
int n=1;
while (n != 0)
Cout<<“\n Enter an integer value: “;
{ cin >> n;
cout << "\tcube(" << n << ") = " << cube(n) << endl;
} } //This program continues until you enter 0 as input
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Function Declaration and Definition
There are generally two methods of defining
functions in a program
i) Complete definition of functions above the main program as seen
in the above example
Listing only the function header above the main program, and then
listing the function’s complete definition – head and body below the
main() function
In this method, the function’s declaration is separated from its
definition. A function’s declaration is simply the function’s head,
followed by a semi-colon e.g int cube(x); This is called function
prototype
A function’s definition is the complete function – header and body
Function’s declaration is also called prototype
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Function Declaration and Definition
• A function declaration is like a variable declaration; its purpose is simply to
provide the compiler with all the information it needs to compile the rest of the
file.
• The compiler does not need to know how the function works (its body). It only
needs to know the function’s name, the number and types of its parameters, and
its return type. This is precisely the information contained in the function’s head.
• Also like a variable declaration, a function declaration must appear above any
use of the function’s name.
• But the function definition, when listed separately from the declaration, may
appear anywhere outside the main() function and is usually listed after it or in a
separate file.
• The variables that are listed in the function’s parameter list are called
parameters. They are local variables that exist only during the execution of the
function. They are not recognized outside the function. Their listing in the
parameter list constitutes their declaration.
• The variables that are listed in the function’s calls are called the arguments. Like
any other variable in the main program, they must be declared before they are
used in the call.
•
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Function Declaration and Definition
Method 1: Function definition before the main() program
#include <iostream>
#include <stdio>
int cube(int x)
{ // returns cube of x:
return x*x*x;
}
int main()
{
int n=1;
while (n != 0)
Cout<<“\n Enter an integer value: “;
{ cin >> n;
cout << "\tcube(" << n << ") = " << cube(n) << endl;
} } //This program continues until you enter 0 as input
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Function Declaration and Definition
Method 2: Function declaration before main() prg and definition after main() prog.
#include <iostream>
#include <stdio>
int cube(int ); // function declaration (prototype)
int main()
{
int n=1;
while (n != 0)
Cout<<“\n Enter an integer value: “;
{ cin >> n;
cout << "\tcube(" << n << ") = " << cube(n) << endl;
}
int cube(int x) // function definition
{
return x*x*x;
}
} //This program continues until you enter 0 as input
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Types of Functions
• void FUNCTIONS
• A function need not return a value. In other programming languages,
such a function is called a procedure or a subroutine. In C++, such a
function is identified simply by placing the keyword void where the
function’s return type would be.
• BOOLEAN FUNCTIONS
• In some situations it is helpful to use a function to evaluate a
condition, typically within an if statement or a while statement. Such
functions are called boolean functions after the British logician
George Boole who developed boolean algebra. Boolean function
returns true or false
• I/O FUNCTIONS
• I/O function are functions written to handle input/output operations of
a program. They are particularly useful for encapsulating tasks that
require messy details that are not very relevant to the primary task of
the program.
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
Sample program
• The following program classifies the 128 ASCII characters (see Appendix A):
#include <cctype> // defines the functions isdigit(), islower(), etc.
#include <iostream> // defines the cout object
using namespace std;
void printCharCategory(char c);
// prints the category to which the given character belongs;
int main()
{ // tests the printCharCategory() function:
for (int c=0; c < 128; c++)
printCharCategory(c);
}
void printCharCategory(char c)
{ // prints the category to which the given character belongs:
cout << "The character [" << c << "] is a ";
if (isdigit(c)) cout << "digit.\n";
else if (islower(c)) cout << "lower-case letter.\n";
else if (isupper(c)) cout << "capital letter.\n";
else if (isspace(c)) cout << "white space character.\n";
else if (iscntrl(c)) cout << "control character.\n";
else if (ispunct(c)) cout << "punctuation mark.\n";
else cout << "Error.\n";
return 0;
}
By Mr. Sokunbi, M.A. Computer Tech Dept, YabaTech
PRACTICAL
• Debug and test run the sample programs. Add using
namespace to any of the program where the compiler
complains about cout
• You can know how to program only by writing programs
and running them – Practice makes perfect.
• Be sincere to yourself!
For your practical, you can download cxxdroid app
from play store into your mobile phone
or Borland C++ compiler into your laptop
Check the Assignment on Google classroom