2
C++ Functions Types
•In programming, function refers to a segment that
groups code to perform a specific task.
• Depending on whether a function is predefined or
created by programmer; there are two types of function:
• Library Function (Built-in functions)
• User-defined Function(Programmer-defined)
C++
Programming,
Ali
Alsbou
3.
3
Built-in functions
• pre-definedfunctions which are usually grouped into
specialized libraries .
• For using a predefined C++ Standard Library function we
have to include in our program the header file in which
the function is defined.
• For Example:
<math.h> library which include some functions like
(sqrt, abs,…)
Programmer can use library function by invoking function
directly; they don't need to write it themselves.
C++
Programming,
Ali
Alsbou
4.
4
C++ Standard Library
•Mathematical calculations (…< math.h >)
• String manipulations (…<string.h >)
• Input/Output (….< iostream.h >)
• Error checking (…< exception.h >)
• Format output ( <iomanip.h> )
C++
Programming,
Ali
Alsbou
5.
5
Math Library Functions
MathLibrary Functions header file : math.h (C) or cmath (C++)
Function name Description
sin(x) Compute sine of x ( x in radians )
cos(x) Compute cosine of x ( x in radians )
tan (x) Compute tangent of x ( x in radians )
sqrt(x) Compute square root of x
pow(x , y) x raised to power y xy
ceil(x) rounds x to the smallest integer not less than x
floor(x) Returns the largest interger value smaller than or equal to
Value. (Rounds down)
fmod(x,y) Compute remainder of division as floating point number
abs(x) Compute absolute value of x return integer number
fabs(x) Compute absolute value of x return floating point number
C++
Programming,
Ali
Alsbou
6.
Function Calling
6
• Programmercan use library function by
invoking(call)function directly
• Functions called by writing
functionName (argument);
// parameters , variables,
info
or
functionName(argument1, argument2, …);
• Function Arguments can be:
- constant sqrt(9);
- variable sqrt(x);//x is variable
- expression sqrt( x*9 + y) ;
sqrt( sqrt(x) ) ;
C++
Programming,
Ali
Alsbou
7.
7
Example(1)
How does itwork?
Sqrt(x) : Compute square root of x
cout << sqrt( 9 );
− sqrt return value (3)
− So: cout << 3;
• if (sqrt( 16 )== 4 ) cout<< sqrt(16);
• value= sqrt( 16 )
8.
8
Example (2):
Using afunctions within Code
#include <iostream>
#include <cmath> // <math.h>
int main(){
double number, squareRoot;
cout << "Enter a number: ";
cin >> number;
squareRoot = sqrt(number);
cout<<"Square root of "
<<number<<" = "<<squareRoot;
return 0;
}
9.
9
Example (3)
Write aC++ program to compute sin(90),tan(90) ,cos(60),cos(0),tan(0)
C++
Programming,
Ali
Alsbou
10.
pow(x , y)
•pow(x , y): Compute x raised to power y and
return integer number only
cout<<"raises 4 to the 2 power is:"<<pow(4, 2);
• Example (4) :
− cout<<"pow(2,3)= "<< pow(2,3)<<endl;
− cout<<"2*pow(2,3)= "<< 2*pow(2,3)<<endl;
− cout<<"pow(2,pow(2,3))= "
<<pow(2,pow(2,3))<<endl;
10
C++
Programming,
Ali
Alsbou
floor(x) & ceil(x)
• floor Removes the fractional part of an integer. When
dealing with negative numbers, int rounds down.
• Example(7):
− floor ( 5 ) // is 5
− floor (4.6) // is 4
− floor (-4.6)// is -5
− floor (-4.1) // is -5
• ceil rounds x to the smallest integer not less than x .
When dealing with negative numbers, Removes the fractional
part of an integer.
• Example(8) :
− ceil( 5 ) // is 5
− ceil(4.6) // is 5
− ceil(-4.6)// is -4
− ceil(-4.1) // is -4
− If x=-4.499 then ceil(x+2) // -2
13
C++
Programming,
Ali
Alsbou
Returns the largest interger
value smaller than or equal
to Value. (Rounds down)
14.
abs & fabs
•abs(x) : return integer number only
• fabs(x) : Compute absolute value of x
return floating point number
• Example(9) :
− cout<<" | 5.2 |= "<< fabs(5.2);
− cout<<" | -5 |= "<< fabs(-5);
− cout<<" |-5.3 |= "<< fabs(-5.3);
− cout<<" | 0 |= "<< fabs(0);
Example :
cout<<" | - 5.3 |= "<< abs(- 5.3 );
14
C++
Programming,
Ali
Alsbou
15.
fmod function
• fmod(double, double)
• Example(10) :
− cout<<fmod( 12.6 ,2.3); // 1.1
− cout<<fmod(42.12 ,3.4); // 1.32
− cout<<fmod(20.0 ,2.0); // 0
15
C++
Programming,
Ali
Alsbou
16.
Exercise(1)
• What thelast value of x on the following:
1. x=floor(ceil( 20.3 )-2); // x= 19
• ceil(20.3) rounds 20.3 to the smallest integer not less than
20.3 = 21
• floor(21) rounds 21 to the largest integer not greater than
21 >>>> 21
• 21- 2 = 19
• floor(19) = 19
2. x= pow(sqrt(4),floor(fabs(3.2))); //x=8
16
C++
Programming,
Ali
Alsbou
17.
Random number generation
stdlib.hlibrary
• rand function use to generate an integer
value between 0 and RAND-MAX (~32,767)
• rand function defined in<stdlib.h> library
17
C++
Programming,
Ali
Alsbou
18.
Generating a numberstatement:
open-range and specific range
• rand() // [0, RAND-MAX] open-
range
• Generating a number in a specific
range : Scaling:
− rand()%(max + 1) // [0, max]
− To generate numbers in the range [min,
max]:
rand()% (max - min + 1) + min
18
C++
Programming,
Ali
Alsbou
19.
19
Examples (11):
1. x=rand();//x has any number 0..RAND-MAX
2. generate 10 random numbers(open-range)
int x;
for( int i=0; i<=10; i++)
{
x=rand();
cout<<x<< " ";
}
20.
Examples (12):
Statement
range
•num=rand()%8; //[0..7]
•num=rand()%55; // [0..54]
•num=rand()%8+2; // [2,9]
•num=rand()%17-22; // [-22,-
6]
•num=rand()%19-3; // [-3,15]
20
C++
Programming,
Ali
Alsbou
21.
21
How to ?
•num=rand()%8+2; //
[2,9]
rand()% (max - min + 1) + min
(max - min + 1) + min=8
(max - 2 + 1) + 2=8
(max - 3) + 2=8
max =8 + 3 – 2
max =9
rand()% (9 - 2 + 1) + 2
22.
Example(13)
//generate 10 integersbetween 0..49
int x;
for( int i=0; i<10; i++)
{
x=rand()%50;
cout<<x<< " ";
}
22
C++
Programming,
Ali
Alsbou
Note: the rand( ) function will generate
the same set of random numbers each time you
run the program
23.
Example(14)
23
C++
Programming,
Ali
Alsbou
//generate 10 integersbetween 5…15
int x;
for (int i=1; i<=10; i++){
x= rand() % 11 + 5;
cout<<x<<" ";
}
//generate 100 number as simulation of
rolling a dice
int x;
for (int i=1; i<=100; i++){
x= rand % 6 + 1;
cout<<x<<" ";
}
Example (15) :rand()
#include <iostream.h>
#include <stdlib.h>
int main()
{
for(int i = 1; i <= 10; i++)
cout << rand() << endl;
return 0;
}
38457
733887
7384
94877
243
3994452
374008
23146
11833432
237844
First
Execution
Output
38457
733887
7384
94877
243
3994452
374008
23146
11833432
237844
Second
Execution
Output
Note: the rand( ) function will generate the same
set of random numbers each time you run the program
C++
Programming,
Ali
Alsbou
26.
srand
• The rand() function will generate the
same set of random numbers each time you
run the program
• To force NEW set of random numbers with
each new run use the randomizing process
by using function srand(integer);
• srand(seed);
26
C++
Programming,
Ali
Alsbou
27.
srand – con’t.
Apopular method for seeding is to use the
system clock.
srand(time(NULL)); //“Randomizes" the
seed
•time(NULL):Function in <time.h> library
returns the time at which the program was
executed
27
C++
Programming,
Ali
Alsbou
28.
Example (16): srand()
generatesa new random set each
time:
#include <iostream.h>
#include <time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
for(int i = 1; i <= 10; i++)
cout << rand() << endl;
return 0;
}
464
53735
342
23
6578
889
93723
7165
7422457
78614
First
Execution
Output
6877
245768
215
57618
78511
79738
3461
175117
35
257868
Second
Execution
Output
C++
Programming,
Ali
Alsbou
30
Header File: stdlib.h(C) or cstdlib (C++)
exit() function.
#include <stdlib.h>
#include <iostream.h>
main()
{
cout<<"Program will exit";
exit(1);//Returns 1 to the operating system
cout<<"Never executed";
}
C++
Programming,
Ali
Alsbou
31.
31
Character Functions
Character handlingfunctions
C++
Programming,
Ali
Alsbou
#include <cctype> (or older <ctype.h>)
• Because these are the original C
functions, bool isn't used. Instead,
zero is false and non-zero is true.
• types of the parameters are c=char/int.
function Description
isalnum(c) true if c is a letter or digit.
isalpha(c) true if c is a letter.
isdigit(c) true if c is a digit.
islower(c) true if c is a lowercase letter.
isupper(c) true if c is an uppercase letter.
32.
32
most common functionsto with
single characters.
isspace(c) true if c is whitespace character (space, tab,
vertical tab, carriage return, or newline).
tolower(c) returns lowercase version of c if there is one,
otherwise it returns the character unchanged.
toupper(c) returns uppercase version of c if there is one,
otherwise it returns the character unchanged.
33.
33
Example (17)
#include <iostream.h>
#include<ctype.h>
int main( ){
char c;
cin>> c;
if(isalnum(c))
cout<<c<<" is an alphanumeric character.n";
else
cout<<c<<" is not an alphanumeric
character.";
}
34.
34
Formatting Output (setw)
iomaniplibrary
• setw() is library function in C++ and is
declared inside #include<iomanip>
• Setw(n):Sets the number of characters
(field width n) to be used on output
operations for the next insertion
operation.
C++
Programming,
Ali
Alsbou
String Function :
TheC-style character string
<cstring.h> or <string.h> are a header file
that contains many functions for
manipulating:
• Copy functions :strcpy,strncpy
• Concatenate strings functions :strcat ,
strncat
• Comparison functions : strcmp,strncmp
• Other functions : strlen
38
C++
Programming,
Ali
Alsbou
39.
39
strlen : StringLength Check Function
Syntax : strlen(str)
– str :array of characters
– int strlen(char str);
• returns the length of String (integer
value) without null character (read
string until 0)
• If the null terminator is the first
character (empty string), it returns 0
C++
Programming,
Ali
Alsbou
String Copy Function
strcpy& strncpy
• Syntax : strcpy(string1, string2);
− string1:destination.
− string2:source
• Copy the content of the 2nd
string into the
1st
string, including the terminating null
character (and stopping at that point).
return string1
− replace content of string1 with string2
start from first element character by
character
− if number of string2 elements plus 1(‘n’)
less than string1 elements , it keep the
remaining elements in string1
41
C++
Programming,
Ali
Alsbou
42.
42
Example (21)
char str1[]=“information"; allocate 12 in memory
str1
strcpy(str1, "AB");
i n f o r m a t i o n 0
A B 0 o r m a t i o n 0
str1
C++
Programming,
Ali
Alsbou
cout<<str1; AB
strncpy
Syntax : strncpy(string1,string2,n);
Description : copies 'n' bytes from str2 to str1
− if n less than or equal length source string2;
copy n character of a string2 without null
character.
− Else copy part of a string2 with null
character
44
C++
Programming,
Ali
Alsbou
45.
Example (23)
45
char str1[]="information"; allocate 12 in memory
str1 i n f o r m a t i o n 0
N e w o r m a t i o n 0
str1
C++
Programming,
Ali
Alsbou
cout<<str1; Print Newormation since Characters printed
until null found
strncpy(str1, "New",3);
46.
Example (24)
46
char str1[]="information"; allocate 12 in memory
str1 i n f o r m a t i o n 0
N e w 0 0 m a t i o n 0
str1
C++
Programming,
Ali
Alsbou
cout<<str1; Print New since Characters printed until null found
strncpy(str1, "New",5); // 5 > strlen("New")
for (i=0; i<11;i++)
cout << str1[i];
Print New mation since it part of array
49
strcat :String Concatenation
Syntax: strcat(string1, string2);
• Concatenation is taking two strings and
then make them become one string
• This function takes the second string and
appends it to the first string,
overwriting the appends character at the
end of the first string with the first
character of the second string
• The last character copied onto the end of
the first string is the null character of
the second string.
C++
Programming,
Ali
Alsbou
50.
Example(27) :
String Concatenation
He l l o J i m 0
string1
char string1[10] = "Hello";
char string2[10] = "Jim";
strcat(string1,string2);
H e l l o 0
J i m 0
string1
string2
C++
Programming,
Ali
Alsbou
String Comparison :strcmp
Syntax : strcmp (string1, string2);
takes two strings and returns an integer value:
− A negative integer if string1 is less than
string2.
− Zero if string1 equals str2.
− A positive integer if string1 is greater than
string2.
52
C++
Programming,
Ali
Alsbou
If Result
string1< string2 < 0
string1> string2 > 0
string1== string2 == 0
53.
String Comparison
There aretwo rules for less than/greater than strings:
every character (symbol) is actually a number, as defined by the
ASCII code.
◦ Compare one character in str1 with one character in str2
which have the same index(n) if:
◦ two characters are match move to next pairs of character with
next index also.
◦ On first non-matching characters . str1 is less than str2 if
str1[n] < str2[n] else str1 is greater than str2.
◦ If str1 is shorter in length than str2 and all of the characters of
str1 match the corresponding characters of str2, str1 is less
than str2.
C++
Programming,
Ali
Alsbou
With Letter order (a..z, or A.. Z)
Value is increase
A value is 65
B value is 66
a value is 97
54.
54
Example(29)
str1 str2
return
value
reason
"AAAA" "ABCD"<0 ‘A’ <‘B’
"B123" "A089" >0 ‘B’ > ‘A’
"127" "409" <0 ‘1’ < ‘4’
"abc888" "abc888" =0 equal string
"abc" "abcde" <0 str1 is a sub string
of str2
"3" "12345" >0 ‘3’ > ‘1’
C++
Programming,
Ali
Alsbou
56
Exercises
• So whatwould be the result of the
following comparison function calls?
− strcmp("hello", "jackson");
− strcmp("red balloon", "red car");
− strcmp("blue", "blue");
− strcmp("aardvark", "aardvarks");
Note :
− ‘0’ value is 0
− ‘ ‘ (space) value is 32
C++
Programming,
Ali
Alsbou
Some ASCII code.
57.
57
Example (30)
#include <iostream.h>
#include<string.h>
main()
{
char x[6]="ABCZ";
char y[6]="ABCZ ";
if((strcmp(x,y)) < 0)
cout<<"The result is :x is less than y";
else if((strcmp(x,y)) > 0)
cout<<"The result is :x is greater than y";
else
cout<<"The result is :x equal to y";
}
58.
58
strncmp
Same as strcmpexcept that at most limit
characters are compared
Syntax : strncmp (string1, string2,n);
C++
Programming,
Ali
Alsbou
Some Common Errors
It is illegal to assign a value to a
string variable (except at declaration).
char A_string[10];
A_string="Hello";// illegal assignment
Should use instead
strcpy (A_string, "Hello");
C++
Programming,
Ali
Alsbou
61.
Some Common Errors
Theoperator == doesn't test two strings for
equality.
e.g.:
if (string1 == string2)//wrong illegal comparison
cout << "Yes!";
Should use instead
if (strcmp(string1,string2)==0)
cout << "Yes they are same!";
//note that strcmp returns 0 (false) if the two
strings are the same.
C++
Programming,
Ali
Alsbou
62.
Concatenation
• Plus “+”is used for string concatenation: s3=s1 + ”to” + s2;
− at least one operand has to be string variable!
• Compound concatenation allowed: s1 += ”duction”;
• Characters can be concatenated with strings:
s2= s1 + ’o’;
s2+=’o’;
• No other types can be assigned to strings or concatenated with strings:
s2= 42.54; // error
s2=”Catch” + 22; // error
63.
• Comparison operators(>, <, >=, <=, ==, !=) are
applicable to strings
string s1=”accept”, s2=”access”,
s3=”acceptance”;
s1 is less than s2 and s1 is less than s3
• Order of symbols is determined by the symbol table
(ASCII)
− letters in the alphabet are in the increasing order
− longer word (with the same characters) is greater than
shorter word
− relying on other ASCII properties (e.g. capital letters
are less than small letters) is bad style
Comparing Strings
64.
• Number ofstandard functions are defined for strings. Usual
syntax:
string_name.function_name(arguments)
• Useful functions return string parameters:
− size() - current string size (number of characters currently
stored in string
− length()- same as size()
− max_size() - maximum number of characters in string
allowed on this computer
− empty() - true if string is empty
• Example:
string s=”Hello”;
cout << s.size(); // outputs 5
String Functions
String Characteristics
65.
• Similar toarrays a character in a string can be accessed
and assigned to using its index (start from 0)
cout << str[3];
• Using Substrings function
Accessing Elements of Strings
66.
• substr -function that returns a substring of a string:
substr(start, numb), where
start - index of the first character,
numb - number of characters(bytes)
• Example:
string s=”Hello”;
cout << s.substr(3,2); // outputs ”lo”
----------------------
string s="123456789"; // size is 5
cout << s.substr(3,2); // outputs ”45”
Substrings - function
67.
• find familyof functions return position of substring found, if
not found return global constant string::npos defined in
string header
− find(substring) - returns the position of the first
character of substring in the string
− rfind(substring) - same as find, search in reverse
− find_first_of(substring) - finds first occurrence of
any character of substring in the string
− find_last_of(substring) - finds last occurrence of
any character of substr in the string
• All functions work with individual characters as well:
cout << s.find(“l”);
Searching - functions
68.
• insert(start, substring)-inserts
substring starting from position start
string s=”place”;
cout << s.insert(1, ”a”); // s=”palace”
• Variant insert(start, number, character)
– inserts number of character starting from
position start
string s=”place”;
cout << s.insert(4, 2, ’X’);//s= ”placXXe”
− note: ‘x’ is a character not a string
Inserting
69.
• replace (start,number, substring)-
replaces number of characters starting from start
with substring
− the number of characters replaced need not be the
same
• Example
string s=”Hello”;
s.replace(1,4, ”i, there”); //s is ”Hi, there”
Replacing
70.
• append(string2)- appendsstring2 to the end of the
string
string s=”Hello”;
cout << s.append(”, World!”);
cout << s; // outputs ”Hello, World!”
• erase(start, number)- removes number of
characters starting from start
string s=”Hello”;
s.erase(1,2);
cout << s; // outputs ”Hlo”
• clear()- removes all characters
s.clear(); // s becomes empty
Appending, Erasing
71.
• Strings (unlikearrays) can be returned:
− string myfunc(int, int);
• Note: passing strings by value and returning
strings is less efficient than passing them by
reference
• However, efficiency should in most cases be
sacrificed for clarity
Returning Strings
72.
C-string Problems
• C-stringsproblems stem from the underlying array
• With C-style strings the programmer must be careful not
to access the arrays out of bounds
• Consider string concatenation, combining two strings to
form a single string
− Is there room in the destination array for all the characters and
the null?
• The C++ string class manages the storage automatically
and does not have these problems
Editor's Notes
#2 External functions (e.g., abs, ceil, rand, sqrt, etc.)are usually grouped into specialized libraries (e.g., iostream, stdlib, math, etc.)
#3 The Standard C++ Library contains a large collection of predefined functions which may be
called and used by programmers.
For using a predefined C++ Standard Library function we have to include in our program
the header file in which the function is defined.
#13 floor :Explanation: Returns the largest interger value smaller than or equal to Value. (Rounds down)
#34 This manipulator is declared in header <iomanip>.
#36 This manipulator is declared in header <iomanip>.
#37 #include<iomanip.h>
int main()
{
int i;
for (i=0;i<3;i++)
cout <<"ABC"<<setw(5);
cout<<"\n";
for (i=0;i<3;i++)
cout <<"ABC"<<setw(2);
cout<<"\n";
for (i=0;i<3;i++)
cout <<setw(4)<<"ABC";
cout<<"\n";
for (i=0;i<3;i++)
cout <<setw(4)<<"ABC"<<setw(3)<<"EF";
return 0;
}
#57 #include <iostream.h>
#include <string.h>
main()
{
char x[6]="ABCZ ";
char y[6]="ABCZ ";
if((strcmp(x,y)) < 0)
cout<<"The result is :x is less than y";
else if((strcmp(x,y)) > 0)
cout<<"The result is :x is greater than y";
else
cout<<"The result is :x equal to y";
}
#59 #include <iostream.h>
#include <string.h>
main()
{
char x[6]="ABCZ ";
char y[6]="ABCD ";
char z[6]="ABB" ;
if((strncmp(x,y,4)) < 0)
cout<<"1.The result is :x is less than y\n";
else
cout<<"2.The result is :x is greater than y\n";
if((strncmp(x,y,3)) == 0)
cout<<"3. The result is :x equal to y\n";
if((strncmp(x,z,3)) > 0)
cout<<"4.The result is :x greater than z";
}