SlideShare a Scribd company logo
1
Functions in C++
C++.
Chapter
(7)
Ali Alsbou
Al Hussein Bin Talal University
Built-in functions
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
Built-in functions
• pre-defined functions 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
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
Math Library Functions
Math Library 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
Function Calling
6
• Programmer can 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
Example(1)
How does it work?
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
Example (2):
Using a functions 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
Example (3)
Write a C++ program to compute sin(90),tan(90) ,cos(60),cos(0),tan(0)
C++
Programming,
Ali
Alsbou
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
11
Example (5):
pow(x,y)
#include <iostream.h>
#include <math.h>
main()
{
int y;
cin>>y;
if (pow(y,3) == 8 )
cout<<"Y is == 2"<<endl;
for (int i=2; i<6;i+=2)
cout<<"pow("<<i<<",3)= "<< pow(i,3)<<"n";
}
12
Example (6):
// Note : sqrt ( X ) is equivalent to pow( X , 0.5 )
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)
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
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
Exercise(1)
• What the last 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
Random number generation
stdlib.h library
• 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
Generating a number statement:
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
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<< " ";
}
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
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
Example(13)
//generate 10 integers between 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
Example(14)
23
C++
Programming,
Ali
Alsbou
//generate 10 integers between 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<<" ";
}
rand function:
Generate from specific range with specific elements
24
C++
Programming,
Ali
Alsbou
• [ 1, 2, 3, 4, 5]
rand() % 5 + 1
• [ 2, 4, 6, 8, 10]
(rand() % 5 + 1) * 2
• [3, 5, 7, 9, 11 ]
(rand() % 5 + 1) * 2 + 1
• [6, 10, 14, 18, 22]
((rand() % 5 + 1) * 2 + 1) * 2
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
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
srand – con’t.
A popular 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
Example (16): srand()
generates a 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
Exercise (2)
29
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
Character Functions
Character handling functions
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
most common functions to 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
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
Formatting Output (setw)
iomanip library
• 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
35
C++ Programming:iteration, Ali Al sbou
C++
Programming,
Ali
Alsbou
36
Output and Formatting Output (setw)
Example (18)
C++ Programming:iteration, Ali Al sbou
Output
C++
Programming,
Ali
Alsbou
37
Example (19)
C++ Programming:iteration, Ali Al sbou
Output
C++
Programming,
Ali
Alsbou
String Function :
The C-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
strlen : String Length 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
40
Examples(20)
1
3
2
char a[ ]="abcd";
cout<<strlen(a); // 4
char s[ ]="ABCD";
for (int i =0;i<strlen(s);i++)
cout <<s[i]<<endl;
int string_length =strlen("abcde");
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
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
43
Example(22)
char str1[9]="0";
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
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);
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
47
Example(25)
#include <iostream.h>
#include<string.h>
main()
{
char str[] = "Computer";
char str1[9]=""; //char str1[9]="0";
strncpy(str1, str, 6);
cout<<str1;
}
Example(26)
48
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
Example(27) :
String Concatenation
H e 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
51
Example (28 ):
strncat
Append at most n bytes of a source string
to destination
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
String Comparison
There are two 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
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
C++
Programming,
Ali
Alsbou
56
Exercises
• So what would 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
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
strncmp
Same as strcmp except that at most limit
characters are compared
Syntax : strncmp (string1, string2,n);
C++
Programming,
Ali
Alsbou
59
Example(31)
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
Some Common Errors
The operator == 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
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
• 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
• Number of standard 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
• Similar to arrays 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
• 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
• find family of 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
• 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
• 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
• append(string2)- appends string2 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
• Strings (unlike arrays) 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
C-string Problems
• C-strings problems 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
Ad

Recommended

Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
Chap 5 c++
Chap 5 c++
Venkateswarlu Vuggam
 
Chap 5 c++
Chap 5 c++
Venkateswarlu Vuggam
 
2.overview of c++ ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 
Library functions in c++
Library functions in c++
Neeru Mittal
 
lecture56.ppt
lecture56.ppt
AqeelAbbas94
 
lecture56functionsggggggggggggggggggg.ppt
lecture56functionsggggggggggggggggggg.ppt
abuharb789
 
Functions in C++
Functions in C++
home
 
CPP Homework Help
CPP Homework Help
C++ Homework Help
 
Chp8_C++_Functions_Part2_User-defined functions.pptx
Chp8_C++_Functions_Part2_User-defined functions.pptx
ssuser10ed71
 
C++ Functions.pptx
C++ Functions.pptx
DikshaDani5
 
C++ Homework Help
C++ Homework Help
C++ Homework Help
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
NoorAntakia
 
Chapter 9 Value-Returning Functions
Chapter 9 Value-Returning Functions
mshellman
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Chapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
Programming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptx
singyali199
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03
sanya6900
 
C++ Functions.ppt
C++ Functions.ppt
kanaka vardhini
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
bhargavi804095
 
Functions in C++
Functions in C++
home
 
C++ functions
C++ functions
Mayank Jain
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.ppt
Suleman Khan
 
2-Functions.pdf
2-Functions.pdf
YekoyeTigabuYeko
 
functions
functions
Makwana Bhavesh
 
Functions123
Functions123
sandhubuta
 
Functions12
Functions12
sandhubuta
 
how to reuse code
how to reuse code
jleed1
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
 

More Related Content

Similar to Chp7_C++_Functions_Part1_Built-in functions.pptx (20)

CPP Homework Help
CPP Homework Help
C++ Homework Help
 
Chp8_C++_Functions_Part2_User-defined functions.pptx
Chp8_C++_Functions_Part2_User-defined functions.pptx
ssuser10ed71
 
C++ Functions.pptx
C++ Functions.pptx
DikshaDani5
 
C++ Homework Help
C++ Homework Help
C++ Homework Help
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
NoorAntakia
 
Chapter 9 Value-Returning Functions
Chapter 9 Value-Returning Functions
mshellman
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Chapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
Programming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptx
singyali199
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03
sanya6900
 
C++ Functions.ppt
C++ Functions.ppt
kanaka vardhini
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
bhargavi804095
 
Functions in C++
Functions in C++
home
 
C++ functions
C++ functions
Mayank Jain
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.ppt
Suleman Khan
 
2-Functions.pdf
2-Functions.pdf
YekoyeTigabuYeko
 
functions
functions
Makwana Bhavesh
 
Functions123
Functions123
sandhubuta
 
Functions12
Functions12
sandhubuta
 
how to reuse code
how to reuse code
jleed1
 
Chp8_C++_Functions_Part2_User-defined functions.pptx
Chp8_C++_Functions_Part2_User-defined functions.pptx
ssuser10ed71
 
C++ Functions.pptx
C++ Functions.pptx
DikshaDani5
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
NoorAntakia
 
Chapter 9 Value-Returning Functions
Chapter 9 Value-Returning Functions
mshellman
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Chapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
Programming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptx
singyali199
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03
sanya6900
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
bhargavi804095
 
Functions in C++
Functions in C++
home
 
cpphtp4_PPT_03.ppt
cpphtp4_PPT_03.ppt
Suleman Khan
 
how to reuse code
how to reuse code
jleed1
 

Recently uploaded (20)

University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
“THE BEST CLASS IN SCHOOL”. _
“THE BEST CLASS IN SCHOOL”. _
Colégio Santa Teresinha
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Health Care Planning and Organization of Health Care at Various Levels – Unit...
Health Care Planning and Organization of Health Care at Various Levels – Unit...
RAKESH SAJJAN
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
LDMMIA Practitioner Level Orientation Updates
LDMMIA Practitioner Level Orientation Updates
LDM & Mia eStudios
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
LDM Recording Presents Yogi Goddess by LDMMIA
LDM Recording Presents Yogi Goddess by LDMMIA
LDM & Mia eStudios
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Health Care Planning and Organization of Health Care at Various Levels – Unit...
Health Care Planning and Organization of Health Care at Various Levels – Unit...
RAKESH SAJJAN
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
LDMMIA Practitioner Level Orientation Updates
LDMMIA Practitioner Level Orientation Updates
LDM & Mia eStudios
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
LDM Recording Presents Yogi Goddess by LDMMIA
LDM Recording Presents Yogi Goddess by LDMMIA
LDM & Mia eStudios
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
Ad

Chp7_C++_Functions_Part1_Built-in functions.pptx

  • 1. 1 Functions in C++ C++. Chapter (7) Ali Alsbou Al Hussein Bin Talal University Built-in functions
  • 2. 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-defined functions 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 Math Library 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 • Programmer can 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 it work? 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 a functions 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 a C++ 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
  • 11. 11 Example (5): pow(x,y) #include <iostream.h> #include <math.h> main() { int y; cin>>y; if (pow(y,3) == 8 ) cout<<"Y is == 2"<<endl; for (int i=2; i<6;i+=2) cout<<"pow("<<i<<",3)= "<< pow(i,3)<<"n"; }
  • 12. 12 Example (6): // Note : sqrt ( X ) is equivalent to pow( X , 0.5 )
  • 13. 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 the last 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.h library • 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 number statement: 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 integers between 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 integers between 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<<" "; }
  • 24. rand function: Generate from specific range with specific elements 24 C++ Programming, Ali Alsbou • [ 1, 2, 3, 4, 5] rand() % 5 + 1 • [ 2, 4, 6, 8, 10] (rand() % 5 + 1) * 2 • [3, 5, 7, 9, 11 ] (rand() % 5 + 1) * 2 + 1 • [6, 10, 14, 18, 22] ((rand() % 5 + 1) * 2 + 1) * 2
  • 25. 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. A popular 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() generates a 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. 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 handling functions 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 functions to 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) iomanip library • 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
  • 35. 35 C++ Programming:iteration, Ali Al sbou C++ Programming, Ali Alsbou
  • 36. 36 Output and Formatting Output (setw) Example (18) C++ Programming:iteration, Ali Al sbou Output C++ Programming, Ali Alsbou
  • 37. 37 Example (19) C++ Programming:iteration, Ali Al sbou Output C++ Programming, Ali Alsbou
  • 38. String Function : The C-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 : String Length 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
  • 40. 40 Examples(20) 1 3 2 char a[ ]="abcd"; cout<<strlen(a); // 4 char s[ ]="ABCD"; for (int i =0;i<strlen(s);i++) cout <<s[i]<<endl; int string_length =strlen("abcde");
  • 41. 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
  • 44. 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
  • 47. 47 Example(25) #include <iostream.h> #include<string.h> main() { char str[] = "Computer"; char str1[9]=""; //char str1[9]="0"; strncpy(str1, str, 6); cout<<str1; }
  • 49. 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 H e 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
  • 51. 51 Example (28 ): strncat Append at most n bytes of a source string to destination C++ Programming, Ali Alsbou
  • 52. 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 are two 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. 56 Exercises • So what would 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 strcmp except that at most limit characters are compared Syntax : strncmp (string1, string2,n); C++ Programming, Ali Alsbou
  • 60. 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 The operator == 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 of standard 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 to arrays 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 family of 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)- appends string2 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 (unlike arrays) 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-strings problems 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.
  • #9: Sin(x) ,x:in radians #include<iostream.h> #include<math.h> main() { const double pi=3.14159265; // converts degrees to radians cout<<" sin(90)= "<<sin(90 * pi/180)<<endl; cout<<" tan(90)= "<<tan(90 * pi/180)<<endl; cout<<" cos(60)= "<<cos(60 * pi/180)<<endl; cout<<" cos(0) = "<<cos( 0 )<<endl; cout<<" tan(0) = "<<tan( 0 )<<endl; }
  • #11: #include <iostream.h> #include <math.h> main() { int x=5; x=x+ pow(4,2) ; cout<<"x= "<< x<<endl; int y; cin>>y; if (pow(y,3) == 8 ) cout<<"Y is == 2"<<endl; for (int i=2; i<6;i+=2) cout<<"pow("<<i<<",3)= "<< pow(i,3)<<"\n"; }
  • #12: #include <iostream.h> #include <math.h> main() { cout <<"sqrt(81) = "<<sqrt(81)<<endl; cout <<"sqrt(81)+sqrt(9) = "<<sqrt(81)+sqrt(9)<<endl; cout <<"pow( 81 , 0.50 ) = "<<pow( 81 , 0.50 )<<endl; cout <<"pow( 81 , 0.25 ) = "<<pow( 81 , 0.25 )<<endl; cout <<"pow( 81 , 1/3 ) = "<<pow( 81 , 1/3 )<<endl; cout <<"pow( 81 , 3.0/4 ) = "<<pow( 81 , 3.0/4 )<<endl; }
  • #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; }
  • #40: #include <iostream.h> #include<string.h> main() { char read[12] = "My Name"; char write[15] = "Is Ali"; cout << strlen(read) + strlen(write) << endl; }
  • #43: #include <iostream.h> #include<string.h> main() { char str[] = "Computer"; char str1[9]=""; strcpy(str1, str); cout<<str; }
  • #47: #include <iostream.h> #include<string.h> main() { char str[] = "Computer"; char str1[9]=""; strncpy(str1, str, 6); cout<<str1; }
  • #48: #include <iostream.h> #include<string.h> main() { char str[] = "Computer"; char str1[4]="Inf"; /*strncpy(str1, str,2); cout<<str1; strncpy(str, str1,2); cout<<str; */ strncpy(str, str1,6); cout<<str<<strlen(str)<<endl; }
  • #50: #include <iostream.h> #include<string.h> main() { char string1[10] = "Hello"; char string2[10] = "Jim"; strcat(string1,string2); cout<<string1; }
  • #53: if str1[n] == str2[n] then move to next n if str1[n] < str2[n]
  • #56: With Letter order (a..z) Value is increase
  • #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"; }