C++ Programming:
Problem Solving and
Programming
Chapter 8
Standard Functions
Objectives
In this chapter you will:
• Learn about standard (predefined) functions
and discover how to use them in a program
• They are:
− Mathematical functions
− Character functions
− String functions
− Input functions
2
Standard (Predefined) Functions
• They are functions (or modules) whose
definitions have been written and are ready to
be used in the programs
• They are organized as a collection of libraries
or header files
• The corresponding header file has to be
included in the program before the standard
function can be used in the program,
e.g. pow(x,y) in <cmath> header file and
isalpha(ch) in <cctype> header file
3
Mathematical Functions
Mostly defined in <cmath> header file,
some in <cstdlib> header file
• abs(x) – returns the absolute value of integer
argument.
• fabs(x) – returns the absolute value of floating-
point argument.
• pow(x,y) – returns the value of x raised to the
power of y, xy.
• sqrt(x) – returns the square root of the argument.
• ceil(x) – returns the next higher integer in double.
• floor(x) – returns the next lower integer in double.
4
Mathematical Functions
• sin(x) – returns the sine of the argument. The
argument should be an angle expressed in
radians.
• asin(x) – returns the arcsine of the argument in
radians.
• fmod(x,y) – returns the remainder of x divided by y
in double. Both x and y are also double.
• exp(x) – returns the exponential function of the
argument.
• log(x) – returns the natural logarithm of the
argument (base-e logarithm).
• log10(x) – returns the base-10 logarithm of the
argument.
5
Mathematical Functions - Examples
Function Data type Function and Library Header
example
Square root double sqrt(16.0) cmath
Power double pow(2.0, 3.0) cmath
Ceiling double ceil(3.2) cmath
Floor double floor(3.2) cmath
Absolute int abs(-7) cstdlib
integer
Absolute double fabs(-7.5) cmath
double
6
Mathematical Functions - Exercise
What is the output for each of the follows?
1.abs(-6) 2. fabs(-9.2) 3. fabs(-8)
4.ceil(2.1) 5. ceil(-2.1) 6.
floor(2.5)
7.floor(-2.5) 8. ceil(4.0)
Convert the following mathematical
expression to C++ |x arithmetic
– y| expression
a) b) c)
7
Random Functions
• Defined in <cstdlib> header file
• Use two functions:
• srand()
• rand()
8
Random Functions – srand( )
srand()
• seed random number function
• creates the starting seed for pseudorandom
number series (a repeatable series of
numbers with random properties)
• Used by random number generator rand( )
to calculate the next number in the series.
• Each seed will produce a different series.
• As each number is generated, it becomes
the seed for the next number in the series.
9
Random Functions – srand( )
• To generate a different series in each run, use
the time as the seed.
srand(time(NULL));
OR
srand(time(0));
• Returns the current time in seconds.
• time function requires <ctime> header file
• srand( ) must be called/executed only once for
each random number series.
• Place srand( ) after variable declarations but
before rand function.
10
Random Functions – rand( )
rand()
• Returns a pseudorandom integer between 0 and
RAND_MAX (defined in the standard library as
the largest number that rand( ) can generate).
• If srand is not called before the first call to rand,
the series will based on the seed 1 and the same
series of number will always be generated.
•To generate a random integral in a range x to y,
first scale the number, then if x is greater than 0,
shift the number within the range. We scale the
number using modulus operator %. 11
Scaling Random Numbers
Use formula:
rand() % ((max + 1) – min) + min
Example:
•To produce random numbers in the range
0 to 50 by using rand()%51
12
Scaling Random Numbers - Example
• To generate random number in the range 3 to 7.
• Use the formula where max = 7 and min =3
rand() % ((max+1 – min) + min
rand() % ((7+1-3) + 3
rand() % 5 + 3 13
Scaling Random Numbers - Example
/* Generate a random series in the range 3 to 7 */
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main ( ) {
int range;
srand (time (NULL)); //Seed function to be called once only
cout << rand() % 5 + 3 << endl;
cout << rand() % 5 + 3 << endl;
cout << rand() % 5 + 3 << endl;
return 0;
}
14
Scaling Random Numbers - Exercise
• Define the range of the random numbers
generated by the following expressions:
a) rand() % 11
b) rand() % 11 + 1
c) rand() % 50 – 5
15
Scaling Random Numbers - Exercise
d) Write a program to generate three lucky
numbers in the range 100 to 999.
e) Write a program to generate a random
number in the range of 1 to 10. Let the
user to guess the random number. User
is given two chances to guess the
number.
16
Character Functions
Defined in <cctype> header file:
1.isalpha(ch) – returns true (non-zero value) if ch
is a letter, otherwise false (zero value)
2.isdigit(ch) – returns true if ch is a digit,
otherwise false
3.isalnum(ch) – returns true if ch is an
lowercase, uppercase or a digit , otherwise
false
4.isspace(ch) – return true if ch is a white space
character (‘\n’, ‘ ’, ‘\t’), otherwise false
17
Character Functions
5. islower(ch) – returns true if ch is a
lowercase letter, otherwise false
6. isupper(ch) – returns true if ch is a
uppercase letter, otherwise false
7. toupper(ch) – converts ch to uppercase.
8. tolower(ch) – converts ch to lowercase.
18
Character Functions - Examples
cout << "Enter 4 letters : ";
cin >> a >> b >> c >> d;
cout<<"1st letter: ";
if (isalpha(a) == 0)
cout<<"It is not a alphabet!\n";
else
cout<<"It is a alphabet!\n";
cout<<"2nd letter: ";
if (isdigit(b) != 0)
cout<<"It is a digit!\n";
else
cout<<"It is not a digit!\n";
cout<<"3rd letter: ";
if (islower(c) = = 0)
cout<<"It is not a lowercase!\n";
else
cout<<"It is a lowercase!\n";
cout<<"4th letter: ";
if (isupper(d) != 0)
cout<<"It is a uppercase!\n";
else AACS2524 Programming Concepts 19
cout<<"It is not a uppercase!\n";
Character Functions - Examples
cout << "Enter 2 letters : ";
cin >> a >> b;
cout<<“\n1st letter: ";
if (islower(a) != 0)
{
cout<<"It is a lowercase!\n";
ch = static_cast<char>(toupper(a));
cout<<“Its uppercase is “<<ch<<endl;
}
cout<<“\n2nd letter: ";
if (isupper(b) != 0)
{
cout<<"It is a uppercase!\n";
ch = static_cast<char>(tolower(b));
cout<<"Its lowercase is “<<ch<<endl;
}
20
String Class Functions
• Defined in <string> header file
• Declare a string:
#include <string>
void main() {
string name1 = “Muthu Samy”;
string name2 = “”;
string name3 (“Muthu Samy”);
}
21
String Class Functions
• Find string length
− E.g. length = str.length();
− Return the length of str including the spaces in
between
− str.length() is same as str.size()
• Find empty string
− E.g. if(str.empty())
cout << “String is empty”;
− Return true if string is empty, otherwise false
22
String Class Functions
• Compare strings
a = (name1 == name2 );
a = (name1 != name2 );
a = (name1 < name2 );
a = (name1 > name2 );
− Return non-zero if true, zero if false
− E.g. if (username == validName)
cout << “Valid user”;
23
String Class Functions
• Copy string
− E.g. string a, b, name1=“Ahmad”, name2=“May”;
a = name1; // copy name1 to a
b = name2; // copy name2 to b
• Concatenate strings
− E.g string a, s1=“abc”, s2=“def”, s3=“ghi”;
a = s1 + s2; // a = “abcdef”
a = s2 + s1; // a = “defabc”
s1 += s3; // s1 = “abcghi” (append)
24
String Class Functions
• Print character by character from string
− E.g. string s1 = “abcdef”;
for ( i = 0 ; i < s1.length() ; i++ )
cout << s1.at(i);
• Find position of a word or character of a string
− E.g string s1=“Michael Wong Ming Heng”;
a = s1.find(“Wong”); // return 8
b = s1.find (‘g’); // return 11, the 1st out of
the other ‘g’ found in s1
25
String Class Functions
• Insert string
− E.g. string s1=“Michael Wong Ming Heng”;
s1.insert(8, “Mr. ” );
// s1 = “Michael Mr. Wong Ming Heng”
• Replace string
− E.g string s1=“Michael Wong Ming Heng”;
( start , no of char, “replace string”)
s1.replace( 8 , 4 , “Tan”);
// s1 = “Michael Tan Ming Heng”
26
String Class Functions
• Append characters to string
− E.g. string s1=“Michael Wong Ming Heng”;
( no. of character, ‘character’)
s1.append( 2 , ‘!’ );
// s1 = “Michael Wong Ming Heng!!”
s1.append( “, Dr.”);
// s1 = “Michael Wong Ming Heng, Dr.”
27
String Class Functions
• Remove characters from string
− E.g. string s1=“Michael Wong Ming Heng”;
( start position, no. of characters)
s1.erase( s1.size( ) - 1, 1 );
// s1 = “Michael Wong Ming Hen”
28
C-String Functions
Conversion functions
•Defined in <cstdlib> header file
•Does not apply to string class function
− atof(string) // convert numeric string “1.2345” to
double
− atoi(string) // convert numeric string “123” to integer
− atol(string) // convert numeric string “123456789” to
long integer
29
C-String Functions - Example
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char *n=“123.45”; // char n[10]=“123.45;
int m;
m = atof(n) * 100; // convert to double
cout << m; // Answer: 12345
m = atoi(n) * 100;
cout << m; // Answer: 12300
return 0;
}
30
C-String Functions
Manipulation functions
•Defined in <cstring> header file
strcpy(s1,s2) // copy s2 to s1
strncpy(s1,s2,n) // copy n char from s2 to s1
strcat(s1,s2) //Append s2 into s1
strncat(s1,s2,n) //Append n char from s2 to s1
31
C-String Functions - Examples
Before After
str1 str2 str1 str2
strcpy(str1, str2); “” “Nasi Ayam” “Nasi Ayam” “Nasi Ayam”
strcpy(str1, str2); “Mee” “Goreng” “Goreng” “Goreng”
strncpy(str1, str2, 3); “” “Tom Yam” “Tom” “Tom Yam”
strncpy(str1, str2, 2); “Nasi” “Lemak” “Lesi” “Lemak”
32
C-String Functions - Examples
char str1[5]="", str2[ ]="yes"; str1
strncpy(str1, str2, 2); y
\0 \0
e \0 \0 \0
cout << str1; 0 1 2 3 4
ye str1
?
y ?
e ? ? ?
char str1[5], str2[ ]="yes"; 0 1 2 3 4
strncpy(str1, str2, 2);
cout<< str1;
ye
33
C-String Functions - Examples
char str1[5]="", str2[ ]="yes";
strcpy(str1, str2); str1
cout<< str1; y
\0 \0
e \0
s \0 \0
yes
0 1 2 3 4
char str1[5], str2[ ]="yes"; str1
strcpy(str1, str2); ?
y ?
e ?
s ?
\0 ?
cout<< str1; 0 1 2 3 4
yes
34
C-String Functions - Examples
Before After
str1 str2 str1 str2
strcat(str1, str2); “Nasi” “Ayam” “NasiAyam” “Ayam”
strcat(str1, str2); “” “Goreng” “Goreng” “Goreng”
strncat(str1, str2, 3); “” “Tom Yam” “Tom” “Tom Yam”
strncat(str1, str2, 2); “Nasi” “Lemak” “NasiLe” “Lemak”
35
C-String Functions
Comparison functions
•Defined in <cstring> header file
strcmp(s1,s2) // compare s1 to s2
strncmp(s1,s2,n) // compare up to n char of
s1 to s2
Compare Result Remark
s1 = s2 0 S1 & S2 match
s1 > s2 >0 S1 is greater than S2
s1 < s2 <0 S1 is less than S2
36
C-String Functions - Examples
str1 str2 Result
strcmp(str1, str2); “Nasi” “Nasi” 0
strcmp(str1, str2); “Lemak” “LeMak” 1
strcmp(str1, str2); “LeMak” “Lemak” -1
strcmp(str1, str2); “Cendol” “Cen” 1
strncmp(str1, str2, 3); “Nasi” “Nanas Lemak” 1
strncmp(str1, str2, 2); “ABC12” “ABC34” 0
strncmp(str1, str2, 4); “ABC12” “ABC34” -1
37
C-String Functions
Example- Example
char pw[ ]=“abc”, str[4];
cout << “Enter your password: ”;
cin >> str;
if (strcmp(pw, str) == 0)
cout << “Matched\n”;
else
cout << “Invalid password\n”;
38
C-String Functions
Example
Length function
•Defined in <cstring> header file
strlen(s1) // determine the length of string s1
•Example
char name[ ] = “Yusof Bin Abdullah”
cout << strlen(name); // Output is 18
39
C-String Functions
Example
Locate characters in string function
•Defined in <cstring> header file
strpbrk(string1, string 2)
•Example
From the test characters of “computer”, ‘o’ is the first character
to appear in “Learning programming is fun”
char *string1 = "Learning programming is fun";
char *string2 = "computer";
cout << "From the test characters of \"" << string2 << "\", ";
cout << "\'" << *strpbrk(string1, string2) << "\'" << "is the first character to appear in\n";
cout << "\"" << string1 << "\"" << endl;
40
Input Functions
Example
• cin and get functions (Revision)
• get – used to read character data,
including whitespaces.
• Example: char ch1, ch2;
int num;
Input: A 25
If using cin in this statement:
cin >> ch1 >> ch2 >> num;
• Result: ch1 = ‘A’ , blank is skipped by the >>
ch2 = ‘2’
num = 5 41
Input Functions
Example
• If using these statements:
cin.get(ch1);
cin.get(ch2);
cin >> num;
Input: A 25
Result: ch1 = ‘A’
ch2 = ‘ ’ the blank is not skipped
num = 25
42
Input Functions
Example
• cin and the ignore function
• ignore – discard a portion of the input.
• Example:
cin.ignore (100, ‘\n’);
• The statement ignores the next 100
characters or until it encounters the
character specified (in this case is the
newline)
43
Input Functions
Example
Example:
•Assume we have variable declaration:
char ch1, ch2;
•Input: Hello there. My name is Mickey.
•With these statements:
cin >> ch1;
cin.ignore (100, ‘.’);
cin >> ch2;
•Result: ch1 = ‘H’
ch2 = ‘M’ , the blank is skipped by
the >> 44