Computer Programming - 4 Books in 1 - The Ultimate Crash Course To Learn Python, SQL, PHP and C++
Computer Programming - 4 Books in 1 - The Ultimate Crash Course To Learn Python, SQL, PHP and C++
By
Computer Programming Academy
Cоруright 2020 bу Computer Programming Academy
All rightѕ rеѕеrvеd
Thiѕ dосumеnt iѕ gеаrеd tоwаrdѕ рrоviding еxасt аnd rеliаblе infоrmаtiоn in
rеgаrdѕ tо thе tорiс аnd iѕѕuе соvеrеd. Thе рubliсаtiоn iѕ ѕоld with thе idеа
thаt thе рubliѕhеr iѕ nоt rеquirеd tо rеndеr ассоunting, оffiсiаllу реrmittеd, оr
оthеrwiѕе, quаlifiеd ѕеrviсеѕ. If аdviсе iѕ nесеѕѕаrу, lеgаl оr рrоfеѕѕiоnаl, a
рrасtiсеd individuаl in thе рrоfеѕѕiоn ѕhоuld bе оrdеrеd.
- Frоm a Dесlаrаtiоn оf Prinсiрlеѕ whiсh wаѕ ассерtеd аnd аррrоvеd еquаllу
bу a Cоmmittее оf thе Amеriсаn Bаr Aѕѕосiаtiоn аnd a Cоmmittее оf
Publiѕhеrѕ аnd Aѕѕосiаtiоnѕ.
In nо wау iѕ, it lеgаl tо rерrоduсе, duрliсаtе, оr trаnѕmit аnу раrt оf thiѕ
dосumеnt in еithеr еlесtrоniс mеаnѕ оr in рrintеd fоrmаt. Rесоrding оf thiѕ
рubliсаtiоn iѕ ѕtriсtlу рrоhibitеd аnd аnу ѕtоrаgе оf thiѕ dосumеnt iѕ nоt
аllоwеd unlеѕѕ with writtеn реrmiѕѕiоn frоm thе рubliѕhеr. All rightѕ
rеѕеrvеd.
Thе infоrmаtiоn рrоvidеd hеrеin iѕ ѕtаtеd tо bе truthful аnd соnѕiѕtеnt, in thаt
аnу liаbilitу, in tеrmѕ оf inаttеntiоn оr оthеrwiѕе, bу аnу uѕаgе оr аbuѕе оf
аnу роliсiеѕ, рrосеѕѕеѕ, оr dirесtiоnѕ соntаinеd within is thе ѕоlitаrу аnd uttеr
rеѕроnѕibilitу оf thе rесiрiеnt reader. Undеr nо сirсumѕtаnсеѕ will аnу lеgаl
rеѕроnѕibilitу оr blаmе bе hеld аgаinѕt thе рubliѕhеr fоr аnу rераrаtiоn,
dаmаgеѕ, оr mоnеtаrу lоѕѕ duе tо thе infоrmаtiоn hеrеin, еithеr dirесtlу оr
indirесtlу.
Rеѕресtivе аuthоrѕ оwn аll соруrightѕ nоt hеld bу thе рubliѕhеr.
Thе infоrmаtiоn hеrеin iѕ оffеrеd fоr infоrmаtiоnаl рurроѕеѕ ѕоlеlу, аnd iѕ
univеrѕаl аѕ ѕо. Thе рrеѕеntаtiоn оf thе information iѕ withоut соntrасt оr аnу
tуре оf guаrаntее аѕѕurаnсе.
Thе trаdеmаrkѕ thаt аrе uѕеd аrе withоut аnу соnѕеnt аnd thе рubliсаtiоn оf
thе trаdеmаrk iѕ withоut реrmiѕѕiоn оr bасking bу thе trаdеmаrk оwnеr. All
trаdеmаrkѕ аnd brands within thiѕ bооk аrе fоr сlаrifуing рurроѕеѕ оnlу аnd
аrе thе оwnеd bу the оwnеrѕ thеmѕеlvеѕ, nоt аffiliаtеd with thiѕ dосumеnt.
This Book Includes:
By
Computer Programming Academy
Table of Contents
Introduction
Chapter One
The Basics of Python Programming
How Python Started
Properties of Python Programming Language
The Benefits Of Learning Python Programming
How To Set-Up Python On Your PC:
How To Create A Simple Python Program
Exercise 1:
Chapter Two
Types of Variables
How Values Are Assigned To Variables
Multiple Variable Assignments:
Data Types in Python
Numbers in Python:
Strings in Python
Lists in Python
Tuples in Python
Dictionary in Python
Python Data Type Conversion
Exercise 2:
Chapter Three
Methods/Functions in Python
Creating Functions in Python
Calling Python Functions
Function Parameters:
Types of Arguments
Default Values in Arguments:
Local Variables within A Function:
Global Variables within A Function:
Return Values in Python Functions:
Python Functions As Objects:
Attributes of Python functions:
Exercise 3:
Chapter Four
Basic Python Operations
Types of Operators:
Special Operators in Python:
Exercise 4:
Chapter Five
Flow Control in Python
The if Statement:
The while Statement:
The for Loop:
The break Statement:
The continue Statement:
Exercise 5:
Chapter Six
Class and Objects in Python
How Classes are Created in Python
Python Class Demonstration:
Exercise 6:
Chapter Seven
Date and Time in Python (The Datetime module)
How the Datetime Module is Implemented in Python
Programs that use Timedelta
Exercise 7:
Chapter Eight
Data Processing, Analysis, And Visualization In Python
Mean Removal:
Scaling:
The Normalization Technique:
The Binarization Technique:
The One Hot Encoding Technique:
The Label Encoding Technique
Data Analysis in Python
Summarizing the Dataset:
Dimensions of the Dataset:
Listing the whole Data:
Viewing the Statistical Summary:
Breaking down the Data by Class Variable:
Data Visualization:
Univariate Plots:
Box and Whisker Plots:
Multivariate Plots:
Scatter Plot Matrix:
Exercise 8:
Chapter Nine
Applications of Machine Learning in Python
Filtering of Malware and Spam:
Filtering results from search engines:
Online-based Customer Support Systems:
Automatic Language Translation:
Detecting of Cyber-fraud:
Social Media Services:
Analysis and Predictions of Traffic congestion:
Virtual Assistants:
Face Recognition:
Product Recommendations:
Limiting Mail Spam:
Video Surveillance Systems:
Exercise 9:
Chapter Ten
Inheritance in Python
How an Inheritance is Implemented in Python
The UML Diagram of Python Inheritance
The Super() Method:
Exercise 10:
Chapter Eleven
Special Methods in Python
Basic Special Methods
Classes Behaving Like Iterators:
Classes Behaving like Sets:
Classes Behaving like Dictionaries:
Classes Behaving like Numbers:
Exercise 11:
Chapter Twelve
Exception Handling in Python
How Exceptions Are Handled Using The Try-Except Statement
Raising Exceptions using Python Arguments
Creating Custom Python Exceptions
Built-in exceptions in Python
Python Assertions
Exercise 12:
Answers to exercises:
Conclusion
Introduction
Python is easily one of the best programming languages out there, if not the
best in itself. Everywhere you look, from internet content to online platforms,
such as social media and e-commerce sites, to robotics and technology, to
digital disruption in the business landscape. All of them contain an
embedment of Python. It goes to show that an in-depth knowledge of this
programming knowledge sets up one to dominate in almost all fields of
modern-day life. That said, how can one get ahold of this knowledge with
limitless potentials? The internet swarms with many different alternatives,
which may confuse. To avoid that, this book is written with a beginner
audience in perspective. Each discussion covered is aimed at enlightening the
reader, going one step at a time to facilitate a proper understanding of the
subject matter.
Your Python journey starts here; through the pages of this book. Go for
glory!
Chapter One
The Basics of Python Programming
The Python programming language is characterized by an easy to learn and
intuitive syntax, making it one of the most widely used and preferred
programming languages across the world. According to the TIOBE index,
Python is ranked as the third popularly used language in 2019. This ranking
takes its usage up even further, implying a two percent increase from the
previous year.
Python’s popularity can also be traced to the high readability of its syntax and
simplicity of use. Readability comes in terms of the syntax being written in
clean, regular English. This property makes the program less daunting to
code in and allows programmers to pay attention to the business at hand
instead of trying to keep up with and remember all the details of the
language.
Quality of code:
Python codes have a characteristic high readability index, making it easier to
maintain and reuse. The programming language also features a broad support
base for advanced software engineering disciplines such as functional and
object-oriented programming.
Integration of components:
For specific applications, interaction is required across several parts for an
end to end workflow to be supported. One of such components could be
scripts written in other languages such as C++ or Java, or Python scripts, or
even that of different technologies.
There are several ways in which Python supports communication across
applications. It enables mechanisms, such as integration with DotNET and
JAVA components, interfacing with USB devices through serial ports,
loading of C++ and C libraries or vice versa, and interaction using
COM/Silverlight. Python is even capable of exchanging data across networks
through the use of protocols, such as COBRA, XML-RPC, and SOAP.
Taking a look at the program, you can note how relatively easy it is to decode
and write the code in Python.
Run the codes to completion. Proceed to verify the version of Python pre-
installed in the system using these commands:
$ python3 -V
The output should reflect something like:
Python 3.6.1
Since you require some libraries and modules for coding, you have to install
the PIP package. To install it, execute this line of code:
$ sudo apt-get install -y python3-pip
With the PIP tool, you are able to download and update the pre-installed
Python packages on your system, as well as getting others not already in your
system. Follow the code shown below to install Python packages:
$ pip3 install <package_to_install>
Take, for instance; you want to install the numpy package. You write the
code as follows:
$ pip3 install numpy
At this point, it is advisable to begin installing a couple of development tools
and libraries that could come in handy during programming. Execute the
code shown below to include those packages during Python installation:
$ sudo apt-get install build-essential libssl-dev libffi-dev python-dev
At this point, your prompt may differ a little from a standard prompt.
(test_env) pythonforbeginners@pythonforbeginners:~/environments$
Having the virtual environment already set up now, we can proceed to create
the traditional Hello World program. Begin by opening up a command-line
text editor to create a new file. A recommended text editor is vi.
(test_env) pythonforbeginners@pythonforbeginners:~/environments$ vi
world.py
Using the vi text editor ensures the text file is opened in the terminal. Enter
the commands shown below:
print(“Hello, World!”)
Use “.wq” to save the script and quit the text editor. Having exited the text
editor and returned to the shell, proceed to execute the created script.
(test_env) pythonforbeginners@pythonforbeginners:~/environments$
python3 hello.py
You can enter the command “deactivate” to leave the Python environment
and return to the initial directory.
How to set up Python on a Windows PC:
When setting up Python on a Windows system, visit the Download Python
page for Windows OS and download any package of your choice. It is
advisable, though, to opt for version 2.7 of Python as it is more stable than
some of the others. Having concluded the downloading process, initiate
launch, and follow through the steps to complete the installation.
While installing the package, click on the option “Install for all users” and
select the destination directory (C:\Python27) as the default path.
Click to open the “Start” menu on your PC and enter “cmd” (command
prompt) into the search bar. Right-click on “cmd.exe” for options and click to
run as admin.
Proceed to modify the directory to “C:\Python27” and execute the code
shown below to set the Python package into the system’s path:
setx PATH "%cd%;%path%;"
pause
The code shown above (setx) will set-up a Python path for every other future
instance of using cmd.exe; however, this doesn’t affect the current one. As a
result, you have to quit and reopen the command prompt window to access
your Python package.
Click to open the “Start” menu and select “All Programs.” Click on “Python
2.7.” Select the “IDLE (Python GUI)” link to start the editor.
When the IDLE editor window opens, enter the command CTRL + N to start
a new file. Proceed to rename the file “hello.py.” Use the command CTRL +
S to save.
Enter the code shown below into the “hello.py” file:
print(“Hello, World!”)
Save file. Click on the Run option and select Run Module. Alternatively,
click on F5 to run the script.
Step two:
For the three lines that follow, the variables discussed below are used to save
the input a user would provide when using the calculator:
“amount” is a variable used to indicate the principal value borrowed.
“roi” is a variable that stands for the rate of interest placed on the principal
value.
“time” is another identifier standing for the number of years. It represents the
borrowing timeframe.
Take notice that the function input() is used in this source code to show the
user the places to enter the respective values for principal, rate, and time.
Additionally, it can be seen that conversion operators, such as float() and
int(), are used in the source code.
int(value) is used in converting a value into a plain integer.
float(value) is used in converting a value into a float type number.
At this point, we have successfully dissected and explained the first four lines
of the source code. Let’s move on to other steps.
Step Three:
The variable used on the fifth line of the source code is named “total,” and is
used in storing the outcome of the complex assignment.
The total implies the entire amount to be issued once the borrowing period
elapses.
However, the fifth line is quite different from the first four. The reason is that
the first line contained an output statement (print()), and the three ensuing
lines involved simple assignment operations. But on the fifth line, the process
becomes more complex. Now, the total amount is being computed, the
Interest accrued inclusive, using the general compound interest formulae
given as:
A = P + (1 + r/n)nt
Where;
print counter
print miles
print name
In this code sample, 500, 3000.0, and “Jane” serve as the values while mark,
distance, and name are the variables they are assigned to respectively. When
executed, the output is as follows:
500
3000.0
Jane
Dictionary
List
Numbers
Tuple
List
String
Numbers in Python:
The number data type in Python is used for storing numeric values. To create
a number object, you have to assign a value to it. Consider the samples
below:
var3 = 5
var9 = 25
It is also possible to delete the reference to a number object. To do this, the
del statement is used. The del statement uses the syntax shown below:
del var6[,var7[,var8[....,varN]]]]
Also, both single and multiple objects can be deleted using the del statement.
See the example:
del var
del var_x, var_y
In Python, there are four supported numerical types. They are:
Complex: This refers to complex numbers
int: This represents signed integers
float: This includes all the floating-point real values
long: This comprises of all long or lengthy integers. It is possible to represent
them in octal and hexadecimal forms).
Consider the example shown below using numbers to express these different
numerical types:
Int: 50, 250, -300, 070, -0120, -0×450, 0×45, etcetera.
Long: 12345678L, -0×54321L, 0123L, 0×ABCDEFGHIJKLMNOPQRl,
123456789101L, -109876543210L, -1110987654321L, etcetera.
Float: 0.0, 10.30, -33.5, 22.7+e10, -45., -12.34e200, 35.1-E18, et cetera.
Complex: 3.14j (π), 25.j, 9.876e-18j, .543j, -.1234+0j, 5e+13j, 2.31e-4j, et
cetera.
If you noticed, one of the long values has a lowercase l. While it isn’t
frowned upon in Python, it is advisable to use an uppercase L to avoid
confusing it with other characters that make up the value. Also, Python
outputs long integers using an uppercase L.
Complex numbers are made up of ordered pairs of real floating-point
numbers and are denoted by the expression (x + yj), where x and y represent
the real numbers, while j serves as the unit of an imaginary number.
Strings in Python
In Python, strings can be seen as a connected series of characters represented
within quotes, which can either be single or double pairs. To take the subset
of a string, the slice operator ([]) and ([:]) are used, with indexes beginning at
0 from the starting of the string and working their way from -1 at the terminal
point.
The sign of addition (+) is an operator used in string concatenation, and the
asterisk (*) is known as the repetition operator. Consider the sample below:
#!/pythonforbeginners/bin/python
str = “Welcome to Python!”
print str # Prints a complete string
print str[0] # Prints first character of the string
print str[3:6] # Prints characters starting from fourth to sixth
print str[4:] # Prints string starting from the fifth character
print str * 3 # Prints string two times
print str + "YAY!" # Prints concatenated string
Tuples in Python
In Python, a tuple refers to a sequence of data type that shares the similarities
of a list. Tuples are made up of a series of values separated with commas.
However, unlike lists, tuples are placed within parentheses.
Other distinguishing factors between lists and tuples are discussed below:
While lists are enclosed in square brackets ([]) and can have their sizes and
elements changed, tuples are placed between parentheses (()) and cannot be
modified once set. With this distinction, it is safe to say that tuples are a read-
only type of list. Consider the sample below:
#!/pythonforbeginners/bin/python
tuple = ( “ijkl”, 419 , 3.14, 'xena', 22.7 )
smalltuple = (789, ‘data’)
print tuple # Prints complete tuple
print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements starting from second till third
print tuple[2:] # Prints elements starting from the third element
print smalltuple * 2 # Prints tuple two times
print tuple + smalltuple # Prints concatenated tuples
Dictionary in Python
In Python, dictionaries refer to some sort of hash table type. The function in
the same way as the hashes or associative arrays peculiar to Perl
programming, and are made up of key-value pairs. A dictionary key can be
about any type in Python, but they usually take the form of strings or
numbers. On the other hand, values can be used as any arbitrary object in
Python.
Dictionaries are enclosed between curly braces ({}), while square braces ([])
are used in accessing or assigning values. Consider the sample below:
#!/pythonforbeginners/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
This is one
This is two
{‘item’: 'shoes', 'amount':5000, ‘customer’: ‘drery’}
['item', 'amount', 'customer']
[‘shoes’, 5000, 'drery']
Exercise 2:
Syntax:
Functions in Python usually follow after this syntax:
The sample showed above lends clarity to the fact that any two objects can be
passed to the product() function that supports the operator (*). This concept
shown through the example is called polymorphism. Below are some points
worth noting about function polymorphism:
Since Python is a dynamically typed programming language, it means its data
types are in correlation with values rather than variables. As a result,
polymorphism is practiced without restrictions. This property is what sets
Python aside from other statically typed languages like Java and C++.
Also, when coding Python programs, declaring a specific data type is
unnecessary. However, when it is done, the program becomes limited to the
data type expected during the coding process. However, the code would not
allow for other compatible data types that could be required in the future.
Function overloading is not a supported process in Python.
Function Parameters:
The term “parameters” is often used interchangeably with the word
“argument.” Albeit, there is quite a distinction between both terms.
A parameter refers to a variable that is used in defining a function, while an
argument refers to the value that is passed to a function parameter. In Python,
many different forms of passing parameters to a function are supported.
However, before delving into these forms, the following is worth knowing:
Types of Arguments
Standard Arguments:
A standard argument is one that is passed as given in a Python function
definition. That is, standard arguments are passed without skipping any of
them or altering their order of arrangement.
deffn(answer):
print(answer)
return
fn()
When the code above is executed, it throws the error shown below because
the single argument requirement has not been met.
TypeError: fn() missing 1 required positional argument: ‘answer’
Keyword-Based Arguments:
When a parameter is assigned a value (like param = value), and passed to a
function (such as fn(param = value)), it becomes a keyword argument. When
a keyword argument is passed to a function, it is left to Python to determine it
using the parameter name used in the assignment of values. Check out the
sample shown below:
deffn(answer):
print(answer)
return
daysInYear()
daysInYear(True)
In this case, the parameter “is_leap_year” takes the place of a default
argument. And if a value is not passed, then it assumes the default value
stated as False.
When the code sample is executed, the result is:
365 days
366 days
Variable Arguments:
There will be times when it is required to pass additional arguments into a
Python function. The arguments used at such pints is known as variable-
length arguments. A good example is the print() function in Python, as it
supports variable arguments. To define a function using variable arguments,
the parameter will have to be prefixed by an asterisk (*) sign. Check out the
syntax below:
deffn([std_args,] *var_args_tuple ):
"""docstring"""
function_body
return_statement
Let’s analyze an example for more clarity:
def inventory(category, *items):
print("%s [items=%d]:" % (category, len(items)), items)
for item in items:
print("-", item)
return
print(fn(5, 10))
print(temp) # error : can not access 'temp' out of scope of function 'fn'
print(iter) # error : can not access 'iter' out of scope of function 'fn'
In the sample above, we attempted to gain access to the local variable from
outside the body of the function, and it resulted in NameError.
The local variables of a function are incapable of retaining variables between
calls. The names used within a def statement doesn’t conflict with the
variables outside of it, even if the same names have been used in other places.
Variable assignments in Python can be done in three distinct places, namely:
Within a def statement, because it is local to a function.
Within an enclosing def statement, because it isn’t local to nested functions.
Outside all def(s) statements; because it is global to the whole file.
def fn1() :
foo = 'new' # new local foo created
def fn2() :
global foo
foo = 'update' # value of global foo changes
In the second example, note the behavior of the global variable when the
import statement is introduced. At this point, we have three scripts for use,
namely:
mod_global.py: This script comprises of a function that changes and display
values, as well as the global definition.
test1.py: This script is responsible for importing the first file and accessing
the global variable.
test2.py: This script makes use of the clause “from” in accessing the global
variable and importing the first file.
# mod_global.py
def fn1() :
global x
a = [5,6] ; b = [10, 100]
# a local ‘b’ is created – available only within 'f1'
# 'a' can be accessed anywhere after a call to 'f1'
fn1()
try :
print(a, b) # name ‘b’ is not defined – error
except Exception as ex:
print('b ->', ex)
print('a ->', x)
# test1.py
import mod_global
print('test1 ->', mod_global.a)
# test2.py
from mod_global import *
print('test2 ->', a)
varx = 5
vary = [1, 3, 5, 7]
Function Examples:
General Function:
Consider the syntax of a general function call in the sample below:
defgetMin(*varArgs) :
min = varArgs[0]
for x in varArgs[1:] :
if x < min :
min = x
return min
min = getMin(11, -10, 15, -13, 4, 2, -67, 8, 3)
print(min)
The output is as follows.
-67
Recursive Function:
The sample below is of a recursive function:
defcalcFact(num) :
if(num != 5) :
return num * calcFact(num-5)
else :
return 5
print(calcFact(x))
The output is as follows.
XX
Python Functions As Objects:
In Python, everything is handled as an object owing to its object-oriented
design, so, even functions are treated in the same way. As such, it is possible
to assign other names to a function object.
deftestFunc(i, j) : print('testFunc called')
fn = testFunc
fn(11, 'aa')
The output is:
testFunc called
Another possible step involves the embedment of a function object into data
structures. See the sample:
def fn1ai) : print('fn1', i)
def fn2(i) : print('fn2', i)
It is possible to return a function object from within other functions. See the
syntax:
defFuncLair(produce) :
def fn1() : print('fn1 called')
def fn2() : print('fn2 called')
def fn3() : print('fn3 called')
if produce == 1 : return fn1
elif produce == 2 : return fn2
else : return fn3
f = FuncLair(2) ; f()
The output will be:
fn2 called
Attributes of Python functions:
In Python, functions are not without their attributes. These attributes can be
listed through the built-in function dir(). Also, they can sometimes be defined
by the system, although other times, they can be defined by the user. User-
defined attributes can also be listed using the dir() function.
Let’s take a look at an example:
deftestFunc():
print("I'm a python test function.")
testFunc.attr1 = "Hi"
testFunc.attr2 = 5
testFunc()
print(dir(testFunc))
The output is:
I'm just a test function.
['__annotations__', '__call__', '__class__', '__closure__', '__code__',
'__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__',
'__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__',
'__name__', '__ne__', '__new__', '__qualname__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'attr1', 'attr2']
The attributes of a function can be used in archiving the information stated as
an alternative to making use of any non-local or global names. And contrary
to non-locals, function attributes can be accessed from any part within a
function itself, even up to outside the function's code.
Exercise 3:
What is the function of the def keyword in Python?
Why are functions treated like objects in Python?
What’s the difference between a parameter and an argument in terms of use?
Chapter Four
Basic Python Operations
Operations refer to the processes used in generating values from single or
multiple other values known as operands. In Python, operations are
performed using operators. As in several other programming languages,
Python has a reserve of special characters that function as operators. Each of
these operators operates peculiar to it, ranging from addition to multiplication
to manipulation of variables and data. Operands are the values in the form of
variables used in passing inputs into the operator.
Consider the sample below:
>>> 12 - 8
3
In the sample, the sign of subtraction (-) serves as the operator who
determines the difference between both values. Also, the values “12” and “8”
passed into the operation are regarded as the operands, and the outputted
value “3” is the result of the operation performed.
Types of Operators:
Arithmetic Operators:
Arithmetic operators function similarly to the connotation of their names.
They are used in performing arithmetic operations such as exponent,
multiplication, addition, division, subtraction, modulus, among others. In
Python, there are many different methods of performing arithmetic
operations, such as function evaluation, function calls, and calculation and
declaration of variables.
There are certain built-in arithmetic operators in Python. They are:
Greater than (>): It returns true when the operand on the left-hand
side is greater than that on the right and false otherwise. E.g. x > y.
Less than (<): It returns true when the operand on the left-hand side
is lesser than that of the right and false otherwise. E.g. x < y.
Equal to (==): It returns true when both operands on either side are
equal; otherwise, it is false. E.g. x==y.
Not equal to (!=): it returns true when both operands on either side
aren’t equal. E.g., x!=y.
Greater than or equal to (>=): It returns true whenever the operand
on the left-hand sides is greater than or equal to the right-hand
operand. E.g., x>=y.
Less than or equal to (<=): It returns true whenever the operand on
the left-hand sides is less than or equal to the right-hand operand.
E.g., x<=y.
Let’s now consider a sample code comprising comparison operators:
x=7
y=4
print('x > y is',xby)
print('x == y is',x==y)
print('x != y is',x!=y)
Logical Operators:
Logical operators allow users to be able to make decisions according to
several defined conditions. The operands serve as conditions capable of being
outputted as either true or false. As such, the outcome of logical operations is
usually the values true or false. That is Boolean values. However, it is worth
noting that not all the operators in this class of operators return Boolean
values. The operators “or” and “and” tend to return one of the operands
passed to them rather than pure Boolean value, while the operator “not” tends
to always out a Boolean value.
Take a look at the outline below containing brief descriptions of logical
operators, and samples to explain how they work.
if ‘x’ is false, then ‘x’, else ‘y’
x and y
or
if ‘x’ is false, then ‘y’, else ‘x’
x or y
not
if ‘x’ is false, then True, else False
not x
Example-
x=7
Y=4
# Result: x and y is 4
print(‘x and y is’,x and y)
# Result: x or y is 7
print('x or y is',x or y)
Assignment Operators:
As the name connotes, assignment operators are used in Python to assign
values to variables. The statement x = 5 makes use of an ancient assignment
operator, which assigns the value on the right-hand side (5) to the operand on
the left (x). There are a variety of assignment operators in Python, some
simple, others complex. Take, for instance, the instruction x -= 5 subtracts to
the variable before assigning the same value back. When executed, it
evaluates as follows:
x = x – 5.
Below are some of the assignment operators peculiar to Python
programming:
(=): E.g. x = 7.
Evaluation: x = 7.
(+=): E.g x += 7.
Evaluation: x = x + 7.
(-=): E.g. x -= 7.
Evaluation: x = x – 7.
(*=): E.g. x *= 7.
Evaluation: x = x * 7.
(/=): E.g. x /= 7.
Evaluation: x = x / 7.
(%=): E.g. x %= 7.
Evaluation: x = x % 7.
(|=): x |= 7.
Evaluation: x = x|7.
(^=): E.g. x ^= 7.
Evaluation: x = x ^7.
Identity Operators:
Identity operators allow users to make comparisons about the location of two
Python variables or objects in the memory. They enable users to locate and
identify whether or not objects occupy matching addresses in the program’s
memory. For variables, holding the same values doesn’t necessarily imply
that they are identical.
Conversely, identity operators can be used in determining if a value belongs
to a specific data type or class. Below is an outline of the identity operators
used in Python:
is: This operator returns True when the operands in an operation both
refer to a similar object; otherwise, it’s False.
E.g., x is y (True if id(x) and id(y) are the same)
is not: This operator returns True when the operands both refer to
different objects; otherwise, it’s False.
E.g. i is not j (True if id(i) and id(j) are different)
Let’s consider a sample code in which identity operators are used:
# Using the 'is' identity operator
j=5
if (type(j) is int):
print("true")
else:
print("false")
Membership Operators:
Membership operators allow users to check if a value is listed as a member of
other objects in Python from tuples to lists to strings. In C programming
language, iteration is necessary for a membership test to go through every
sequence analyzing all values. However, in Python, it is much easier to
determine membership. Also, it is worth noting that membership operators
are capable of testing against a dictionary, but for its key only, not value.
Below is an outline of the membership operators used in Python:
in: This operator returns True when the value appears in a sequence.
E.g., 5 in [3, 4, 5]
not in: This operator returns True when the value doesn’t appear in a
sequence.
E.g. 4 in [1, 2, 3]
Let’s consider a sample code in which membership operators are used:
# Using Membership operators
str = 'Python operations'
dict = {5:’April’,18:'Dec'}
print('y' in str)
print('Python' in str)
print('python' not in str)
print(5 in dict)
print('Dec' in dict)
Exercise 4:
The if Statement:
As the name implies, the if statement is a conditional one. That is, it is
applied to ascertain specific conditions. Now, if those conditions appear true,
a block of codes known as the if block is executed. If it isn’t, another block of
code known as the else statement is executed instead. The else statement is an
optional clause to the if statement.
Let’s consider a code sample. Save the file by the name “if.py”:
number = 15
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Congratulations, you guessed correctly!’)
print(‘(but there are no prizes to be won. Sorry.)’)
# New block ends here
elif guess < number:
# Another block
print('No, keep going. A little higher now’)
# You can enter anything you want into the comments ...
else:
print('No, it is a lot less low than that’)
# you must have tried > number to get here
print(‘The End’)
# This last statement is always processed,
# after the if statement is executed.
$ python if.py
Enter an integer : 10
No, keep going. A little higher now
The End
$ python if.py
Enter an integer : 15
Congratulations, you guessed correctly.
(but there are no prizes to be won. Sorry.)
The End
How the if statement works:
In the sample code used above, number guesses are obtained from a user and
checked against the number inputted as the correct value. The correct value is
a variable number set to any integer of our choice, in this case, 15. Next, the
guesses from the user are collected using the input() function. We proceed to
pass a string to the built-in input function to output as a result of the screen
while awaiting inputs from the user. Once a value is entered and the kbd:
[enter]key engaged, the input() function returns what was entered in string
format. The next step involves converting the string into an integer with “int”
and assigning it to the variable “guess.”
In the real sense of things, “int” is in a class of its own. Recall from previous
discussions that it is used in converting strings to integers provided the string
comprises of valid integers within the text. Next, the guess entered by the
user is compared to the number set up as the correct value. When there is a
match between the number inputted by the user and the correct value, the
success message is printed. Take note that the indentation levels used in the
sample code are meant to inform Python of the respective blocks to which
each statement belongs. Notice how indentation is essential to the entire
coding process. Take note of the colon (:) at the end of the if statement. It is
used to inform the program of an ensuing block of code.
The next step involves checking whether the entry of the user is lesser than
the correct value. If that is the case, the user is informed to increase the value
of their entry. At this point, the elif clause has been triggered. The elif clause
is a combination of two related if-else to if-else statements. It makes the
program much easier to run and lowers the degree of indentation required for
optimal code readability. Take note that a colon is always introduced at the
end of the else and elif statements followed by their respective blocks of
code, also containing correct indentations. It is possible to introduce another
if statement within the if-block of an if statement. This process is known as
nesting, and this is a case of nested if statement.
Recall that the else and elif statements are optional. The syntax of a valid if
statement is quite minimal:
if True:
print(‘Yes, it is true’)
Once Python has completed execution of the if statement, as well as the
connected else and elif clauses, it goes on to the next statement in the block
of code comprising the if statement. In this case, the main block where the
program’s execution began, followed by the next statement print(‘Done’)
statement. Once both have been processed, Python arrives at the end of the
program and wraps it up.
Although the sample code makes for a simple program, it has been
instrumental in teaching about how the if statement functions. It is a
somewhat simple process, so you should have no trouble getting used to it.
However, you have to take cognizance of every little detail to understand
how to use if statements. But with regular practice and enough study, you
could get used to it in no time and become a natural.
while running:
guess = int(input('Imput an integer : '))
if guess == number:
print('Great, you guessed correctly.’)
# this makes the while loop to stop
running = False
elif guess < number:
print('No, it is a lot higher than that.’)
else:
print('No, it is a lot less low than that.’)
else:
print(‘The while loop is complete.’)
# Add anything else you want to add here
print(‘The End’)
$ python while.py
Enter an integer : 40
No, it is a lot less low than that.
Enter an integer : 9
No, it is a lot higher than that.
Enter an integer : 15
Great, you guessed correctly!
The while loop is complete.
The End
while True:
j = input(‘Write something : ')
if j == 'quit':
break
if lensj) <5:
print(‘Entry is too small')
continue
print('Entry is of sufficient length')
# Process other type of things here...
When the code sample above is executed, the result is as follows:
$ python continue.py
Enter something: x
Entry is too small
Enter something: 515
Entry is too small
Write something: vwxyz
Entry is of sufficient length
Write something: quit
Exercise 5:
B1 = BookShop()
Output
__init__() constructor is called...
b1 = BookShop("", "")
b2 = BookShop("", "")
print("BookShop.instances:", BookShop.instances)
In this code sample, the term “instances” represents a class-level attribute. It
can be accessed through the class name and contains the total amount of
instances created.
Note that two instances of the class <BookShop> have been created. As such,
when the code sample is executed, “2” would be printed as the output.
# output
BookShop.instances: 2
defbookInfo(self):
print("Book title:", self.title)
print("Book writer:", self.writer,"\n")
print("BookShop.noOfBooks:", BookShop.noOfBooks)
Open your IDLE environment or any other IDE of your choice, enter and
save this code sample into a file. Proceed to run the program.
In this code sample, it can be seen that three objects of the BookShop class
were created, that is, b1, b2, and b3. Each one object serves as an instance of
the BookShop class.
Once the sample code is executed, the result outputted takes after this
fashion:
# output
Book title: Animal Farm
Book writer: George Orwell
Book title: Arms and the Man
Book author: Bernard Shaw
Exercise 6:
Chapter Seven
Date and Time in Python (The Datetime module)
While there are a variety of ways time can be manipulated or determined in
Python, including a time module, there seems to be an absence of features,
like the ability to devise Date objects for a specific manipulation. To fix this
problem, Python features a built-in datetime module. This module is used in
modifying time and date objects in many different ways. It is made up of five
classes used in manipulating time and date. These classes include the
following:
The datetime module makes it possible for users to create new objects which
contain different date and time stored for manipulation. The syntax shown
below carries out time and date manipulations:
import datetime
print (datetime.date.today())
Or
from datetime import date
print (date.today())
print (datetime.date.today().day)
print (datetime.date.today().month)
print (datetime.date.today().year)
print
(datetime.date.today().day,datetime.date.today().month,datetime.date.today().year)
As the sample code used here is quite lengthy, we could rewrite it as follows:
from datetime import date
now = date.today()
print (now.day)
print (now.month)
print (now.year)
#You can also write the 3 sentences from before as one sentence
As an alternative to determine the weekday of the present date, you could use
the date class, as well.
from datetime import date
now = date.today()
print (now.weekday())
The image shown below is a depiction of the creation process of a time object
and a date object. The result is as follows:
To change the format of the date and time into a human-readable format, the
function strftime() is applied here within the datetime module.
The sample below lends clarity to how this function can be used and how it
prints the date and time in a styled way:
Today = datetime.now()
In the sample code shown above, the “%d” is used to represent the day,
“%M” represents the month, “%d8” stands for the date, and “%y” represents
the year. This is one of the most widely-used format types in Python.
To display the local time and date with the strftime() function, we could make
use of the following code:
import datetime
Today = datetime.now()
To print the local date alone and local time separately, we could swap out
“%c” using “%x” and “%X” respectively.
1. Mention the five classes that make up the Python datetime module.
2. What is the function of a strftime() function in time and date
manipulations?
3. What is the purpose of the info class?
Chapter Eight
Data Processing, Analysis, And Visualization In Python
For a better understanding of how data is preprocessed in Python, we make
use of sample code. Start by opening a file. Save the file under the name
“prefoo.py” using a text editor or the default IDLE from Python. Proceed to
add the following lines of code to the file:
import numpy as np
#We imported a couple of packages. Let’s create some sample data and add
the line to this file:
input_data = np.array([[3, -1.5, 3, -6.4], [0, 3, -1.3, 4.1], [1, 2.3, -2.9, -4.3]])
Once completed, save the file and exit the environment. This serves as the
sample data we would operate on.
Data Preprocessing strategies in Python
There are several techniques with which data can be processed in Python.
They include the following:
Mean Removal:
This technique involves the removal of the mean from all features, such that
the data is centered on zero. The mean removal technique aids in taking out
any form of bias from the features.
The code shown below can be used in performing the mean removal
technique:
data_standardized = preprocessing.scale(input_data)
print "\nMean = ", data_standardized.mean(axis = 0)
print "Std deviation = ", data_standardized.std(axis = 0)
Open your command prompt (Windows) or terminal (Mac OS and Linux),
and enter the following command:
$ python prefoo.py
Scaling:
All the features found in a data point contain values that tend to vary between
other random values.
As a result, it is imperative that they are scaled so that it matches the
specified conventions. To perform the scaling techniques, you can use the
code shown below:
data_scaler = preprocessing.MinMaxScaler(feature_range = (0, 1))
data_scaled = data_scaler.fit_transform(input_data)
print "\nMin max scaled data = ", data_scaled
When you execute the code sample, the output produced is:
Min max scaled data = [ [ 1. 0. 1. 0. ]
[ 0. 1. 0.27118644 1. ]
[ 0.33333333 0.84444444 0. 0.2 ]
]
Take notice of the fact that every value has been scaled to the range specified.
The Normalization Technique:
Normalization is a technique of data processing that deals with adjusting the
values within a feature vector such that it measures them on a common scale.
At this point, a feature vector’s values are adjusted in such a way that their
collective sum is 1. Open the saved prefoo.py file and introduce the following
lines of code:
The lines of code added are used in performing the normalization technique:
data_normalized = preprocessing.normalize(input_data, norm = 'l1')
print "\nL1 normalized data = ", data_normalized
Proceed to execute the code. You would observe the following in the output:
Encoded vector = [[ 0. 0. 1. 0. 1. 0. 0. 0. 1. 1. 0.]]
In the code sample treated above, take note of the third feature in all the
feature vectors. The values are depicted by 1, 5, 2, and 4. By count, there are
four distinct values here, and thus implies that the one-hit encoded vector
would have a length of 4. When attempting to encoded the value 5, it would
be written in the vector form [0, 1, 0, 0]. Recall that only one value can
appear as one in the one-hot encoding technique. And since the second
element is 1, it is an indication that the corresponding value is 5.
Proceed to execute the code sample. You will note the following as output:
Class mapping:
bmw --> 0
kia --> 1
mack --> 2
cat --> 3
As noted in the sample code used, the words have been converted to 0-
indexed digits. Now, when dealing with a series of labels, it is possible to
convert them in the following ways:
labels = ['mercedes', 'kia', 'mack']
encoded_labels = label_encoder.transform(labels)
print "\nLabels =", labels
print "Encoded labels =", list(encoded_labels)
Proceed to execute the code sample. You will note the following as output:
Labels = ['mercedes', 'kia', 'mack']
Encoded labels = [3, 1, 2]
It is a more efficient technique than having to manually maintain the mapping
between both words and numbers. To check their correctness, you can easily
convert the numbers back into their corresponding word labels. To do this,
see the code sample below:
encoded_labels = [3, 2, 0, 2, 1]
decoded_labels = label_encoder.inverse_transform(encoded_labels)
print "\nEncoded labels =", encoded_labels
print "Decoded labels =", list(decoded_labels)
Proceed to execute the code sample. You would note the following as output:
Univariate Plots:
These plots are representations of every one variable. Take a case in which
the entry values are numeric, for instance, and we are required to devise box
and whisker plots for every of those variables. We can do this by executing
the code shown below:
import pandas
import matplotlib.pyplot as plt
data = 'iris_df.csv'
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = pandas.read_csv(data, names=names)
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False,
sharey=False)
plt.show()
Multivariate Plots:
Multivariate plots help in providing clarity about the interrelationship
existing between the variables.
Exercise 8:
scikit-learn: This library is used for data analysis, data mining, and
machine learning.
pylearn2: This library offers more flexibility for machine learning
than scikit-learn.
PyBrain: It is a modular machine learning library having a strong,
flexible, and easy to use machine learning algorithms. It also has a
predefined environment for testing and comparing algorithms.
Orange: This is an open-source library for data analysis and
visualization. It contains specific components aimed at machine
learning and comes equipped with extensions for text mining and
biometrics. It also supports data mining via Python scripting or
visual programming and contains features of data analytics.
PyML: This library is an interactive, object-oriented framework
coded in Python for ML.
Milk: This Machine Learning toolkit contains decision trees, k-NN,
SVMs, random forests, and carries out feature selections.
Shogun: This is a machine learning toolkit aimed at SVMs and large-
scale kernel methods.
Tensorflow: This is a high-level neural network library in Python.
Having discussed the relationship between Python and machine learning, let
us now proceed to the applications of the latter with the former.
Filtering of Malware and Spam:
Machine learning is primarily used by organizations, such as Google, to
detect and filter malware and spam. The databases used in this application are
continually being updated; hence, they are capable of holding out their own
effectively.
Filtering results from search engines:
The queries run on search engines such as Bing, Google, and DuckDuckGo
monitor the responses of users. When users browse the top listings for their
query and generally peruse the page or keep scrolling page by page and exit
without using any result provided, these search engines collect the findings
based on user interaction to improve search results and speed.
Online-based Customer Support Systems:
In many webpages in recent times, there is often an option to contact a
customer support representative when users are on the site. The majority of
the time, though, it is a chatbot handling this option and not a real person.
These bots serve to gather information from the site, providing it to users as a
form of assistance to questions asked. Over time, the chatbots grow to know
and understand the queries entered by user, thus becoming able to provide
more helpful answers. This characteristic of learning and growing is made
possible by machine learning.
Automatic Language Translation:
Machine learning allows users to translate text from one language to another.
The machine learning algorithms used in such cases decipher how the words
combine and use the knowledge gathered to boost the quality of text
translation further. In this vein, translating the text in images via neural
networks to recognize letters is made possible.
Detecting of Cyber-fraud:
To maintain security in cyberspace, machine learning is used in tracking
monetary transactions to detect fraud. For instance, PayPal makes use of
machine learning algorithms to mitigate against money laundering. The
company applies a set of tools that compares many different transactions
performed online to distinguish between illegal and legal transactions carried
out by both buyers and sellers.
Social Media Services:
At the time of this writing, some common features on social media giants,
Facebook, include Face Recognition and People You May Know. Both
features are possible because the machine learning algorithms embedded in
the platform monitor the activities of users ranging from the profiles viewed
to the people whom users send requests to the requests accepted to tags,
among other activities. With the data gathered from this, Facebook seeks to
provide its user base with a better, richer experience to facilitate the use of
the platform.
Analysis and Predictions of Traffic congestion:
GPS navigation services track the location and speed of users, using the data
to create a map of traffic within an area. This service aims to reduce and
avoid traffic congestions. In such cases, machine learning is applied to obtain
an estimate of areas more susceptible to traffic congestions according to
previous histories.
Virtual Assistants:
Brands like Google, Amazon, Samsung, and Apple have taken the world by
storm with their virtual software, Google Assistant, Alexa, Bixby, and Siri,
respectively. These programs serve as virtual personal assistants that can do
just about anything from playing music to making calls to asking about the
weather forecast of the day. Also, users are allowed to set up reminders and
alarms, read the news, and be read their texts. What’s more, is how seamless
they work. All a user needs to do is speak some commands, which the
programs would interpret and perform. This feature is especially handy for
people with disabilities. The virtual assistants monitor the interaction with
users and use the data obtained to improve user experience over time.
Face Recognition:
One of the latest features added to Facebook is the Face Recognition feature.
This feature kicks in when photos are uploaded, in which it automatically
identifies the people in the picture. At the heart of Computer Vision, a
technique used in extracting vital information from videos and images is
machine learning. Other social media platforms such as Pinterest also make
use of computer vision in identifying pins or objects in the images, thus
recommending similar or related pins to a user.
Product Recommendations:
E-commerce platforms such as eBay, Jabong, AliExpress, and Amazon,
among others, monitor the activities of users based on the products they view
and recommend related or similar products to them. When this data obtained
provides users with a favored product that ends up being purchased, it
becomes a successful process for them. To understand the preferences of its
users, these platforms also utilize the contents of carts and wish lists of users.
Limiting Mail Spam:
Many different mail platforms make use of rule-based filtering. However,
spammers have found numerous ways around this filter. This has caused mail
platforms, such as Gmail, to incorporate machine learning into their database
to update their spam filters continuously. Spam is also a major problem for
search engines, like Google and the likes, explaining why search results
always appear filtered. Some conventional techniques for spam filtering
include the use of the C 4.5 Decision Tree Induction and the Multi-Layer
Perceptron.
Video Surveillance Systems:
Technology is in a state of continually pushing towards new frontiers every
day. In terms of crime and security, many different methods are being tested
to decrease the crime rate, even better, prevent certain crime altogether.
Because, in the sense of it, many different crimes can be nipped in the bud
before they occur under proper conditions. With video surveillance systems,
questionable behaviors, such as suspicious loitering, sleeping in a public
bench, and following after others can be easily picked up on. Furthermore,
security agencies would be contacted, and the crime averted.
Exercise 9:
class Vehicle(Taxi):
def __init__(self, model, capacity, variant, color):
# call parent constructor to set model and color
super().__init__(model, capacity, variant)
self.__color = color
defvehicleInfo(self):
return self.getModel() + " " + self.getVariant() + " in " + self.__color +
" with " + self.getCapacity() + " seats"
Take note that the getName() method used in the sample code for the vehicle
class is unspecified. The reason is linked to the fact that the vehicle class
receives it from its parent class.
So, when the sample code is executed, the result will be the following:
# output
i20 Active SX in Bronze with 4 seats
i20 Active
Fortuner MT2755 in White with 7 seats
Fortuner
In the same vein, it is possible to income the parent class constructor from the
sub or child class __init__ making use of the command below:
super().__init__()
def implicit(self) :
print (“Super-Class with Implicit function”)
class sub(super) :
pass
su = super()
sb = sub()
su.implicit()
sb.implicit()
Exercise 10:
Rationale:
The __iter__ method can be called at any one time a new iterator is
created. It serves as a good platform for initializing the iterator with
original values.
The __next__() method can be called at any point in time; the next
value is retrieved from an iterator.
The __reversed__() method is a rare method. It collects an already
existing sequence, returning an iterator, which outputs the items in
the sequence in a reversed order, that is, from last to first.
From the discussion on return statements, take note that for loops are capable
of acting on iterators. Consider the sample loop shown below:
for j in seq:
print(j)
In Python 3, the seq.__iter__() method is called by the program to create an
iterator. Then, the __next__() method is called next on the iterator to obtain
each value of j. Afterward, whenever the __next__() method raises the
exception StopIteration, the for loop is gracefully terminated.
Computed Attributes:
Rationale:
>>>dyn = Dynamo()
>>>dyn.design 3
‘CrazyJean’
>>>dyn.design = 'FlareBottoms'
>>>dyn.design 4
‘FlareBottoms’
Rationale:
>>>dyn = SuperDynamo()
>>>dyn.design 1
'CrazyJean'
>>>dyn.design = 'FlareBottoms'
>>>dyn.design 2
'CrazyJean'
Rationale:
Here, the method __getattribute__ is called to provide dyn.design
with a value. [1]
Even after dyn.design has been explicitly set, the __getattribute__()
method is called to provide dyn.design with a value still. When
present, the method __getattribute__() is called unconditionally for
all the method and attribute lookup, even extending to set attributes
after an instance has been created explicitly. [2]
If a class defines the __getattribute__() method, it is recommended
that you also define a __setattr__() method and alternate between
both to keep a record of the values of attributes. Otherwise, any
attribute set after the creation of an instance vanishes during the
execution process. Take note to be extra careful in using the
__getattribute__ method, as it is the same method the program calls
when looking up the name of a method within a class.
class Jodie:
def __getattribute__(self, key):
raise AttributeError 1
def run(self):
pass
The zipfile module uses this method to define a class that is capable of
decrypting a zip file encrypted using a specified password. During
decryption, the algorithm in charge of zip decryption requires that the state is
stored. When you define the decryptor as a class of its own, it enables you to
keep this state in a single instance (row) of the decryptor class. The __init__()
method is where the state is initialized and updated as decryption of the file is
carried out. However, since the class is callable, as well, like a function, it is
possible to pass the instance as the first argument of the function map().
Check below for syntax:
# excerpt from zipfile.py
class _ZipDecrypter:
.
.
.
def __init__(self, pwd):
self.key0 = 305419896 1
self.key1 = 591751049
self.key2 = 878082192
for p in pwd:
self._UpdateKeys(p)
def __call__(self, c): 2
assert isinstance(c, int)
k = self.key2 | 2
c = c ^ (((k * (k^1)) >> 8) & 255)
self._UpdateKeys(c)
return c
.
.
.
zd = _ZipDecrypter(pwd) 3
bytes = zef_file.read(12)
h = list(map(zd, bytes[0:12])) 4
Rationale:
The ZipDecryptor class regulates state with three rotating keys, all of
which are later updated using the _UpdateKeys() method not
included in this code sample. [1]
A __call__ method is defined by the class, making the class
instances exhibit the property of being callable, similar to functions.
In this case, though, the __call__() method initiates the decryption
I’d a single byte from the zip file before proceeding to update the
rotation keys according to the byte, which is decrypted from the zip
file. [2]
‘zd’ serves as an instance to the ZipDecryptor class. The __init__
method is passed the variable ‘pwd,’ which it promptly stores and
uses in updating the rotating keys for the first time in the execution
process. [3]
Provided with the first 12 bytes of the zip file, you can decrypt them
through mapping each byte to the instance’ zd.’ In essence, zd is
called 12 times, according to the number of bytes, and the __call__()
method is ]invoked a similar number of times (12). Conversely, the
internal state will be updated, and a resulting byte will be returned 12
times.
This outline would suffice under the condition that a is an instance of a class
that implements these special methods. However, what happens in a case
when it is unable to implement any one of them? Or worst-case scenario, it
implements it but can’t deal with specific types of arguments. Consider the
sample below:
>>> from fractions import Fraction
>>> a = Fraction(1, 3)
>>> 1 / x
Fraction(3, 1)
In that sense, it isn’t a case of obtaining a fraction and dividing it using an
integer, like in the sample before. That was a more streamlined case, where, j
/ 3 calls the method j.__truediv__(3), and the method of the Fraction class
deals with the math. But integers are unwise to how to perform arithmetic
operations using fractions. If so, how does the example work? There is
another set of special methods for arithmetic comprising of reflected
operands. Using an arithmetic operation that requires two operands, for
example, a / b, there are two methods to use:
Telling x to divide itself with y; or
Telling y to divide itself into x.
Exercise 11:
To out the Python try statement to efficient use, here is an outline of things
worth noting:
One single try statement can contain several except statements based
on the requirement. In the case of the code sample here, the try block
comprises of multiple statements that a capable of raising various
types of exceptions.
To handle every possible type of exception that can be raised, we can
introduce the generic except clause into the try block.
After the except clause, we can further introduce an else clause. The
command within the else block only runs once the code within the
try block fails to raise any exceptions.
Examples of exception handling in Python
We are considering a sample code to lend clarity to how the try-except
statement is implemented in Python:
try:
fob = open("test", "f")
fob.write("This is a test file for python exception handling.")
except IOError:
print "Error: can\'t locate the file or read data"
else:
print "Write operation was successfully executed on the file"
fob.close()
The sample code above produces the output shown below upon execution:
>>Write operation was successfully executed on the file.
Let’s look into a second sample code in which we attempt to open a file in
READ mode. We start by performing a WRITE operation on the file. When
executed, the file throws an exception as seen in the code below:
try:
fob = open("test", "x")
fob.write("This is a test file to verify the use of exception handling in
Python!!")
except IOError:
print "Error: can\'t locate the file or read data"
else:
print "Write operation was successfully executed on the file"
The sample code above produces the output shown below upon execution:
>>Error: can't locate the file or read data
Using the Except clause to handle all types of Exceptions
When a bare “except” clause is used, it catches any exception raised within a
program. Albeit, it is neither recommended for use by anybody nor is it
considered good practice in programming. The reason is that a try-except
block in Python is capable of handling every type of exception, but cannot
help a programmer in finding out the very exception that triggered a problem.
For better alternatives on how to track and locate exceptions within a code,
consider the code sample shown below:
try:
Perform all your operations here;
.....................
except:
If there is an exception, then execute this block.
......................
else:
If there are no exceptions, then execute this block.
Say the file is opened in the READ mode, and then a write operation is
attempted on it. In that case, the code sample below can be used in handling
the exception raised:
try:
fob = open('test', 'r')
try:
fob.write("This is a test file to verify the try-finally statement in exception
handling!"
)
print 'try block executed'
finally:
fob.close()
print 'finally block executed to exit the file'
except IOError:
print "Error: can\'t locate the file or read data"
For this code the Python interpreter raises an exception, displaying the output
shown below:
>>finally block executed to exit the file
>>Error: can\'t locate the file or read data
In the syntax;
The name is specified under the “Exception”
The keyword “args” is optional and is used to depict the exception argument's
value.
“traceback” which is the final argument is optional, as well, and when
present, represents the traceback object used in the exception.
>>> try:
x = int(input("Enter a positive integer value: "))
if x<= 0:
raise ValueError("The entry is not a positive number!!")
except ValueError as VE:
print(VE)
class InputTooSmallError(Error):
"""Raised when thealphabet inputted is lesser than the correct one"""
pass
class InputTooLargeError(Error):
"""Raised when the alphabetinputted is larger than the correct one"""
pass
#our main program
#the user guesses an alphabet until he/she gets it correctly
while True:
try:
xyz = raw_input("Enter an alphabet: ")
if xyz< alphabet:
raise InputTooSmallError
elifxyz> alphabet:
raise InputTooLargeError
break
except InputTooSmallError:
print("The alphabet inputted is too small, try again!")
print('')
except InputTooLargeError:
print("The alphabet inputted is too large, try again!")
print('')
Enter an alphabet: j
This value is too small, try again!
Enter an alphabet: c
This value is too small, try again!
Enter an alphabet: v
This value is too large, try again!
Enter a number: q
Congrats! Your guess was correct.
From the outline of the sample, it can be deduced that a base class known as
Error has been defined within the program. It is responsible for raising bother
exceptions (“InputTooLargeError” and “InputTooSmallError”) obtained from
the base class. This is the standard method of defining user-defined
exceptions in Python.
Python Assertions
An assertion refers to a sanity-check, which can be turned on or off when a
programmer has concluded testing on a program. The easiest method of
describing an assertion is that it is similar to a raise-if statement or a raise-if-
not statement precisely. A code block is tested, and it raises an exception if
the result return as false.
Assertions are performed with the use of an assert statement, which is one of
the late additions to Python keywords. The asset statement was added in
Python 1.5. When put to use, programmers tend to introduce assertions at the
beginning parts of a function as a means of determining the validity of the
input. Conversely, it can also be added to the end of a function call to
determine the validity of input, as well.
The Python assert keyword:
Anytime the Python interpreter encounters an assert statement; it proceeds to
perform evaluations on the expressions accompanying the statement, which
in any case, may be true. However, if eventually, the expression returns false,
an AssertionError exception is raised by the program. The syntax for the
assert statement is shown below:
assert Expression[, Arguments]
Python makes use of ArgumentExpression as an argument for an
AssertionError anytime the assertion fails. While the AssertionError
exception can be easily caught and handled as in the case of other exceptions
that make use of the try-except statement, if it goes without being handled, it
causes the program to terminate and print a traceback.
Let’s consider an example. Below is the outline of a function used in
converting temperature from the Kelvin scale to the Fahrenheit scale. As zero
Kelvin is the coldest temperature possible for anybody, the function is
promptly terminated when it identifies a negative temperature:
#!/pythonforbeginners/bin/python
defKelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
1. PyBrain.
2. Machine learning makes chatbots capable of learning and growing
with information gathered.
3. To understand the preferences of its users, these platforms also
utilize the contents of carts and wishlists of users
By
Computer Programming Academy
TABLE OF CONTENTS
Introduction
Basics of SQL
Meaning of SQL
Uses of SQL
1. Data Definition
2. Data Manipulation
3. Data Control
4. Database Transaction Management
Basic Commands That Work Well in SQL
Data Definition Language (DDL)
Truncate Statement
Data Manipulation Language (DML)
Data Control Language (DCL)
Rules for SQL Commands
Introduction to Relational Database Management Systems
What is a Record?
What is a field?
The Advantages of a Relational Database Management System
Keys in Relational Database System
Knowing Database
The functions of a Database Management Systems
Benefits of Database
Classification of Database
Types of Databases
The basic classification of NoSQl based on data model
Syntax
The Importance of Syntax in Computer Programming
Levels of Syntax
Types of Syntax Programming
Syntax in SQL
SQL Data Types
CHARACTER [(length)] or CHAR [(length)]
VARCHAR (length)
BOOLEAN
SMALLINT
INTEGER or INT
DECIMAL [(p[,s])] or DEC [(p[,s])]
NUMERIC [(p[,s])]
REAL
FLOAT(p)
DOUBLE PRECISION
DATE
TIMESTAMP
CLOB [(length)] or CHARACTER LARGE OBJECT [(length)] or CHAR
LARGE OBJECT [(length)]
BLOB [(length)] or BINARY LARGE OBJECT [(length)]
OPERATORS IN SQL (STRUCTURED QUERY LANGUAGE)
What is an Operator in Structured Query Language (SQL)?
Structured Query Language SQL Arithmetic Operators
Structured Query Language SQL Comparison Operators
Structured Query Language (SQL) Logical Operators
Structured Query Language SQL Compound Operators
Structured Query Language, (SQL) Character Operators
Structured Query Language SQL Concatenating Character Strings
Structured Query Language SQL Wildcard operators
MANAGING OBJECTS IN SQL
SMO Classes
Instance Classes
Utility Classes
Functioning of SMO
WMI Provider
Optimized Performance
Capture Execution
Scripting
Unique Resource Names
Snapshot Databases
Service Broker
RELATIONAL DATABASE CONCEPTS
You have reached yet another enlightening chapter. It is great that you are
so invested in learning. First we will define some common basic terms to
further explain this chapter.
What is Data?
What is a Database?
What is a Database Management System (DBMS)?
Types of DBMS
Relationship between (Relational) Database management system and SQL
The Relational Model
Normalisation and Denormalisation
Elements of a Relational Database Schema
1. Tables
2. Indexes
3. Key
4 Constraints
5 Views
Popular Relational Database Management Systems
3 Oracle DB
4 SQL Server
5 SQLite
HOW TO DEFINE DATA IN SQL
Relationship between Data Description Language (DDL) and Structured
Query Language (SQL)
The concept of DDL
CREATE statement
CREATE TABLE statement
One of the most commonly used CREATE command out of all the
commands is the CREATE TABLE command. Below is a typical
example of how this command is used;
DROP statement
Deleting a table
ALTER statement
TRUNCATE statement
COMMENT
RENAME
WORKING WITH INDEXING, VIEWS AND QUERIES
INDEXING
Index Types
Composite Index:
Unique Index:
Covering Index:
VIEWS
QUERIES
THE RELATIONSHIP BETWEEN INDEX, VIEWS and QUERIES
DATABASE SECURITY
Data preservation
1. Software
2. Physical controls
3. Administrative controls
Importance of Database security
Database security in SQL
Securing the database server
2. Tailor the Database Installation
3. Keep it Updated
4 Restrict the Database Processes
5 Restrict SQL Traffic
6 Set a Strong Admin Password
7 Secure Your Backups
DATABASE ADMINISTRATION
What Does a Database Administrator Do?
Important Tools for Database Administrators
Specializations of Database Administrators
Basic responsibilities of a database administrator
Learning database administration
How t Use SQL in Real World Situations
Application areas of SQL in real world scenarios
1. eCommerce
2. Healthcare provider database
3. Security
4. Online Television Streaming
5. Social Gaming
6. Personal Cloud Storage
7. Sports
8. Finances
9. Government Organizations
10. Social Media
11. Weather Forecast
12. Advertisement Corporations
13. Library and book retrieval systems
14. Telecommunication Firms
15. University management system
Introduction
As it is commonly said, we live in a fast-speed generation, because of the use
of computers that executes actions in seconds. Every day we carry out
strategic activities on our personal computer, save data on spreadsheet, write
mails and archive them, launch online library to store books as databases, etc.
All of these are done because of the presence of the computer.
Basics of SQL
Data has to be stored. We write information on papers, but when they need to
be stored on a computer, they are stored into a database.
As simple as this may look, we will not be able to understand the language of
this database without the help of the SQL.
SQL is a programming language that was designed by two American
computer scientists, Donald D. Chamberlain and Raymond F. Boyce to allow
easy access, retrieval and manipulation of relational databases.
Relational database is a digital database, that is based on relational model.
This relational model is a way of representing data in tables. Relational
database has the capacity to store, and provide access to data points. These
data points can be related to one another. However, a lot of relational
database systems use SQL to maintain and manipulate the database.
Meaning of SQL
At first, SQL was called SEQUEL, which has its full meaning as Structured
English Query Language, it was created by two American scientists, to
manipulate and retrieve the stored data in IBM's original quasi-relational
database management system. This QRDMS has been developed by the
research team at IBM also in the 1970s. The first language that was attempted
by Chamberlin and Boyce's was SQUARE which has its full meaning as
Specifying Queries As Relational Expressions.
However, SQUARE was too difficult to use because it had subscript notation.
In the year 1973, Chamberlin and Boyce moved to the San Jose Research
laboratory where they were able to work on SEQUEL. In the year 1974,
SEQUEL was proposed and successfully published, the publication detailed
their refinements to SQUARE, and this gave an introduction to the data
retrieval character of SEQUEL. SEQUEL was one of the first query
languages to use Edgar F. Codd's relational model. Afterward, the SEQUEL
name was changed to SQL. The name was changed because SEQUEL was a
prominent trade mark registered under the UK based Hawker Siddeley
Aircraft Company. In history of computer programming, SQL has become
the most used computer language.
SQL was tested at different customer test sites to determine the authenticity
and practicality of the system. IBM developed products based on their new
tested system for commercial purpose, which was available in the market for
three years, I979, 1981 and 1983, respectively.
In the year 1986, the American National Standards Institute (ANSI) made
SQL the standard language for relational database management systems. SQL
also became a standard language of the International Organization for
Standardization (ISO) in 1987. In simpler words, SQL is a communication
bridge between databases. The standard were updated and published to
include better and more features in 1989, 1992, 1996, 1999, 2003, 2006,
2008, 2011 and the most recent version was updated in 2016. Despite all of
these revisions, most SQL are not portable compared to several other
database systems that are existing without an updated version.
Uses of SQL
Data are gathered daily, people receive information and turn it into blog post,
or customer care information, and all of this information are stored in
database. Knowing how the database works is where SQL is needed. SQL is
a game changing concept that makes computer programming, and data
storing easy for everyone.
SQL communicates with database for your needs, but there are more to what
you can achieve with SQL.
SQL is used to retrieve data from a database or update data on a database.
SQL is also used in a lot of relational database management systems like
Oracle, Sybase, Access, Ingres, Microsoft SQL Server and other common
relational database systems. Despite the fact that these database systems use
SQL, they have their own proprietary extensions which is an additional
characteristic, that can only be used on their system.
However, SQL's standard commands are, "insert", "select", "update",
"delete", "drop" and "create", and these commands can be useful when
working on any take that needs to be done with database. The SQL
commands can be used in almost everyday task.
The benefits of SQL are numerous; however, SQL has greater advantages
over older read-write APIs such as ISAM and VSAM. The first advantage is
the introduction of the accessing multiple records or data with one command.
Aside from this easy concept of accessible data, SQL also helps in
eliminating the need to specify when you need to access a record.
SQL at creation was based upon relational algebra and tuple relational
calculus, and it consists of many types of statements that can be informally
classified as sub-languages. These sub-languages include: a data query
language (SQL), a data definition language (DDL), a data control language
(DCL), and a data manipulation language (DML).
1. Data Definition
Data in relational database are stored in form of tables, and SQL commands
give you permission to create other elements like tables, indexes, domains,
character sets, schemas and new databases inclusive. It also has the ability to
remove existing elements, modify features of a database object, rename a
database and delete any data or all data in a table.
Data Definition Language statements are parts of SQL, and its function is to
assist in achieving your task, by allowing you to define the data you are
using.
2. Data Manipulation
After defining your data, you need to learn how to manage it. You can make
any command like select, delete, insert or update any data from a table with
the help of a Data Manipulation Language. The maintenance of a database
becomes easier when you can manipulate the data records. Compared to
DDL, DML can only help you alter the data stored in the database and not the
schema.
3. Data Control
You can control the access to your data effectively with the help of SQL by
using the Data Control Language. The essence of controlling access to your
data is to increase the security sensitivity, avoid misusing or hacking of your
database and prevent unauthorized access. With DCL, you can give or
withdraw permission to any user, and this will prevent anyone from
modifying any data in a database.
4. Database Transaction Management
It is a great thing if you can modify any data on your database; however,
modifications made on your database can corrupt your data sometimes. SQL
helps to avoid such occurrence from happening through the Transaction
Control Language (TCL). TCL helps you manage changes made, and also
saves your changes permanently. Aside from these uses, SQL also helps you
identify the stages in your transaction that you need to go back on and
restore, to prevent error.
Platforms compatible
Commands like INSERT, ORDER BY and SELECT work on all platforms,
and they allow administrators access to create, or remove a data in and out of
a table.
Use Case Examples
It helps company owners keep a record of their clients easily.
SQL scope
SQL scope includes data query, data manipulation with commands like
insert, update and delete, data definition and data access control. Albeit, SQL
is importantly a declarative language that includes procedural elements. It
was the first language commercialized to utilize the Edgar's relational model,
which had been described in 1970 as the perfect relational model of data for
large shared data banks. Although, SQL did not completely adhere to the
Edgar F. Codd model, it still became the most used database language in the
world.
SQL has deviated in several forms from its foundational, relational model
and its tuple calculus. In the original model, a table represents a set of tuples,
while in SQL tables and query are lists of rows. The same row may occur
many times, and queries can employ these orders of rows.
However, critiques have created an argument that there should be a
replacement for SQL, and the replacement should be a language that strictly
returns to the original foundation. Despite these critiques, there has not been
any specific proof or theory on why such features should be added to SQL, or
the various versions of SQL. Although it is also necessary that you bear in
mind that SQL can be reviewed as regards this critique, or improved in the
size to avoid their audiences from switching to a completely different
language, or a competitor's product. This debate has been left open with no
further step made by the developers of SQL
SQL language is divided into several forms of language; these includes:
- Clauses are parts of statements and queries, they can be optional
- Expressions can either produce a scalar value or tables with columns and
rows.
- Queries retrieve data based on specific criteria. It is also an important
element of SQL
Statements may have effects on data and schemata, it may also control
program flows, sessions, transactions or diagnostics features.
There are other SQL statements such as the semicolon, which is statement
terminator and it is defined as a standard element of the SQL grammar. The
semicolon is not required on every platform or system. The presence of
insignificant whitespace is generally ignored in SQL statements, or queries,
and this makes it easier to format SQL code to a readable state.
Chapter 2
Create Statement
Create commands are the most commonly used to establish new database,
tables or index.
The SQL-create statement is used to create a fragment in a relational database
management systems (RDBMS). These fragments created are schemas,
tables, views, character sets, collations, domains, translations and assertions.
Examples:
CREATE TABLE [table name] ([column definitions]) [table parameters]
The column definitions are: a comma-separating list consisting of following:
- The primary key definition
- Column definition
- Constraints
- Relational database management systems specific functionality
Some parts of the create command may interaction and collaborate with data
manipulation language.
Drop Statement
The drop statement in SQL is used to destroy an existing database, table, or
index. A drop statement removes some fragments from a relational database
management system (RDBMS). The RDBMS determines the types of objects
that can be dropped, and also support the dropping of tables, database, and
enabled users. Systems like PostgreSQL allow DROP statements and other
DDL commands to effectively occur I a transaction and then be rolled back.
Here is an example of how to use the drop statement. The first is the typical
template of how the statement looks like
The drop statement functions are similar to the delete statements, however,
the DROP statements are different in some way from the DELETE and
TRUNCATE statements, because they do not remove table by themselves.
For instance, DELETE statement may delete some or all data files from the
table without deleting the table in the database, while a DROP statement
destroys the whole table from the database.
Alter Statement
An alter statement is used to modify database object. It modifies objects by
changing the components of an object in a relational database management
system (RDBMS). The RDBMS also influences and determines the objects to
be altered. Example of how to use the alter statement.
Truncate Statement
A truncate statement is used to delete the entire data file in a database table. It
is very effective than the DELETE statement because it is faster.
This command is also a part of SQL commands that are used in managing
changes that affects the data in the database. The commands used include
COMMIT, ROLLACK, and SAVEPOINT.
2. DQL (Data Query Language)
Data Query language are used to fetch data from a relational database. The
only command present in DQL is the SELECT command. The SELECT
command is equivalent to the projection in relational algebra. When this
command is given, it selects the attribute, and this selection is usually made
based on the condition described by the WHERE clause.
Example:
SELECT Name, Address FROM ORDER BY Name
SELECT Name, Address FROM Customer ORDER BY Name DESC;
I believe you must be familiar with SQL by now, having read through chapter
one. However, there are other important SQL commands that have not been
mentioned, but can be used while performing an action on your programs.
SELECT is used for the extraction of stored data from a database
The select command is used to provide query proficiency, and it is also used
in the retrieval of information within the table. The SELECT statement has
three elements which are basic, and these elements are: SELECT, FROM and
WHERE.
These three elements are keywords, and the select keyword is used to specify
the column that you want to retrieve the data from.
The FROM is a clause, and it is used to choose the table that the column
which needs to e retrieved be belongs to. While, the WHERE clause to limit
the rows in a table. It usually written after the FROM clause, it is useful in
comparing values, arithmetic expressions and several other functions that ca
found in a column.
INSERT INTO is used in inserting new data or records into a database. The
Insert into statement can be written in two ways. The first way specifies
which column names and values needs to be inserted.
INSERT INTO table_name (column1, column2, column3, column4, …)
VALUES (value1, value2, value3, value4, …);
Demo Table
Application
INSERT INTO Students (StudentName, Age, Course)
VALUES (‘Rachel’,27, Public Health);
The value changes after insertion
ID NAME AGE COURSE
O1 Rush 23 Nursing
Informatics
O2 Janet 20 Accounting
03 Jack 25 Strategy
Management
04 Rachel 27 Public Health
The second method is to insert only data into specified columns
Example
INSERT INTO STUDENTS (StudentName, Course)
VALUES (‘George, Business Strategy)
Application
ID NAME AGE COURSE
O1 Rush 23 Nursing
Informatics
O2 Janet 20 Accounting
03 Jack 25 Strategy
Management
04 George Null Business Strategy
By placing a semicolon (;) at the end of the last clause in the command
You can also place a semicolon (;) in front of slash / that is on the last
line in the buffer
Make sure you point a RUN command at the SQL command you are
writing
Also, place a slash in front of a SQL prompt
The truth is SQL commands are simple, and can be easily learnt.
Chapter 3
What is a Record?
A record can also be referred to as a row of data. It consists of fields and
contains all the information about one particular subject or person in a
database. A record is also called as a row of data is each individual entry that
exists in a table. For example, there are 5 records in the above PATIENTS
table. Following is a single row of data or record in the CUSTOMERS table.
A record is a horizontal entity in a table.
Example of a record
What is a field?
A table is also broken into smaller entities and these entities are called fields.
A field is a part of a record, and single pieces of data on a subject in a record
are found in a field. Fields in the above table contains ID, NAME, AGE,
MARITAL STATUS and DIAGNOSE. A field is designed to maintain
information about every record in a table.
What is a column?
A column in a table is a vertical entity that contains data that are associated to
a specific field in a table. For example, a column in the table above is the age
of the patients.
See the example below.
AGE
23
65
35
40
15
Knowing Database
A database is properly organized and collected data that are stored and can be
accessed electronically from a computer. Databases are often developed using
formal design and modeling techniques. Before a designer develops a
database, his first assignment is to create a conceptual data model that reflects
the type of information to be kept in the database.
The database management system provides the access to the stored data. The
DBMS is the software that interacts with the application users, and the
database to analyze and capture the stored data. It is also allows end users to
interact with more than one database. Although there may be restrictions in
accessing some data, however this will be based on the security level made
by the programmer or database owner. The functions of a database are
diverse; it allows entry of information, storage of data and also retrieval of
large files of information. Aside from doing all of these, it also provides ways
in which the data stored can be managed and organized effectively.
The functions of a Database Management Systems
A database is known as the collection of data and a common example is a
spreadsheet or card index form. The DBMSs manages the data stored in the
below four categories.
Data Definition: I mentioned in chapter 1 that data definition consists of
defining the structure of your data, creation and modification of your data.
Update: After you have saved your data on your database, the DBMS gives
you the permission to insert new information, alter or modify the former
information, or even delete any of the information stored.
Retrieval: DBMS helps you provide information in a readable and usable
form. The stored data when retrieved may be available in the exact format it
was saved, or a new format.
Administration: For every data stored, there is an end-user, data and a future
need for the data. Every data stored needs to be secured properly, and DBMS
makes it easy for the application administrator to register and monitor the
data effectively, enforces data security to prevent unauthorized personnel
from accessing the data, to maintain the integrity and value of the data
without any corruption.
Benefits of Database
Database is helps to facilitate the development of a new application, improves
factors like data security, data access to enabled users, promotes data
integrity and also reduces data errors and redundancy.
Classification of Database
Database can be classified using the following criteria; type of the contents
stored, application area and technicality of the database, such as the structure
of the database. The classification you are about to read is made based on
database distribution, and there are four major distribution systems for
DBMS.
Centralized Systems: Databases that are stored in a single location so that
the data can be accessed and used by other systems are stored with a
centralized database system.
Distributed Database System:
The actual databases in this system are distributed evenly from different
locations, which are connected to a computer network.
Homogenous Distributed Database System: The same DBMS is used in
this database system, though they are from different location.
Heterogonous Distributed Database System: In this database system,
different DBMS are used by different sites, however there is a presence of
additional software to support easy exchange of data.
Types of Databases
The type of database you want is based on the usage requirements. You are
about to learn the available database in the market today.
Centralized database
Centralized database is abbreviated as CDB, it is a database that is stored,
located and maintained in a single location, and this location can be a
database system or in the central computer. Centralized database is often used
by organizations like a business company or a university.
The centralized database has a good number of advantages compared to other
types of databases. CBD maximizes the quality of a data properly, helping
the data to maintain its integrity, accuracy, and reliability. For the fact that
there is only one storage location, there is a higher level of security, and
better data preservation. Although CBD is easy to maintain and change at any
time, given it needs to be updated, yet it is highly dependent on network
connectivity.
The disadvantages of CBD are few, but they are however detrimental to the
organization. If for any reason the unexpected occurs, all data will be lost and
it may be difficult to retrieve the data, because it was saved in one location.
Distributed database
When information is stored on multiple storage devices, or locations, it is
called distributed database. This information may be stored on difference
computers in the same physical place, but they are not stored on the same
processor. Distributed database can be subdivided into two groups namely,
homogenous database and heterogeneous database.
Distributed database involves two processes, the replication and duplication.
Replication is the use of specific software that looks for changes in the
distributed database. The replication process is complex and time consuming.
While duplication identifies one of the stored databases as the master and
duplicates what it does. However, both replication and duplication can keep
the integrity of the data in all distributed locations.
The distributed database should not be confused for centralized database.
Although the distributed database has a multiple storage location, it still relies
on the central DBMS which manages the storage devices remotely. The
benefits of having a distributed database will increase the reliability and
availability of your data, easy expansion improved performance and it is also
a mean of saving cost.
DBAs are very complex, which makes it a disadvantage because it needs
extra effort to ensure that all data are evenly distributed to all locations. It
also needs experienced hands to be able to manage the data, and provide
maximum security on the stored data.
Personal database
A personal database is a stored data on a personal computer, it is created to
be used, organized and managed by one person. It can be created by a
computer programming language like Practical Extraction and Reporting
Language (PERP). A personal database only support one application, makes
use of one computer.
End-user database
An end user is not usually concerned about the about the kind of transactions
and operations done, but it is only concerned about the software or
application. The end user database is specially meant for the end user, who
can be a manager who summarizes the collected information in a database.
Commercial database
Commercial databases are information collected and presented electronically,
which are managed by commercial entities. These databases are stored, and
maintained for customers’ services, they are available to customers for
commercial purposes. There are 5 reliable sources where you can access a
commercial database; a commercial database retailer, internet sources, library
or places with site license, a help of a professional, and personal subscription
source.
Commercial databases have advantages and disadvantage, like every other
database.
The commercial database requires no physical space, since it is online, unlike
printed materials that need library or bookshelf. Aside from this part, the
database can be easily monitored, and can be accessed by multiple users at
the same time.
The disadvantages of commercial database are that it needs constant network
connectivity and cost of management can be expensive for both the
administrator and user.
NoSQL database
A NoSQL database was originally referred to as non SQL or non relational
database. It is used in managing big data, and real time web applications. It is
a database that is built to provide mechanism for retrieval and storage of data
that are modeled in other means used in relational database. There are
different classifications, and sub-categories of NoSQL database.
The basic classification of NoSQL based on data model
Column
Column is the lowest level NoSQL object in a key space, which consists of a
name, value and timestamp. The name is a unique factor that is used to
reference the column. On other hand, the content of the column is referred to
as the value and the timestamp is used to determine the validity of the
content.
- HBase is an open source non-relational database written in Java
language and modelled after Google’s Bigitable
- Cassandra is a Java based system that is designed to manage large
data across commodity servers, and provide availability without any
iota of error or failure.
- Scylla is an open source distributed database that was designed to
work with the Casandra database.
- Accumulo is a popular NoSQL database that is written in Java
language. It is ranked as the third most popular column database.
Document
This is a computer program that was designed for the storage and retrieval of
document oriented information. The document NoSQL category is also sub-
divided into fourteen.
- Apache
- CouchDB
- ArangoDB
- BaseX
- Clusterpoint
- Couchbase
- Cosmos
- DB
Operational database
An operational database is used to manage stored data in real time.
Organizations make use of operational database because things like clients’
information, payroll records and employees bio-data
Relational database
A relational database consists of set of tables where data can be accessed in
various ways without an enabled user having to reorganize the tables.
Relational database allows users to access and categorize stored data that can
later be filtered to retrieve data. Relational database shares few similarities
with a database; however, the major difference between a database and a
relational database is that the later stores data in rows and columns while the
former stores data in files or document.
Cloud database
This is a database that is kept and managed on a cloud application. The
benefits of cloud database include fast automated recovery for lost files,
increased accessibility, maintenance of in-house hardware, and a better
performance. Despite all of these advantages, cloud databases have their own
drawbacks such as security issues and potential loss of data in case of
bankruptcy or disaster.
Object-oriented database
This is a database management system that represents information as objects.
Graph database
Graph database (GDB) is a database that uses graph structures for semantic
queries that have nodes and edges to store data. It is a part of NoSQL
database, created for the purpose of addressing limitations attached to the
existence of relational databases. GDB is designed to allow a fast retrieval of
complex data.
There are notable graph database that have used for various purpose and here
are their descriptions.
- AllegroGraph was designed as a metadata data model, and its
programming language is C, C#, Common Lisp, Java and Python.
- Amazon Neptune is a graph database that is managed Amazon.
Notable users of Amazon Neptune databases include Samsung
Electronics, Intuit, FINRA, Siemens, AstraZeneca, LifeOmic,
Blackfynn and Amazon Alexa.
- AnzoGraph was developed to interact with sets of semantic data. Its
programming is C, C++
- ArangoDB is a multi-model database that supports key, documents
and graphs which are the three important data models. It uses
languages like C++, JavaScript, .NET, Java, Python, Ruby, Node.
- DataStax is a distributed real time database that supports Cassandra.
It is a Java only database.
- Microsoft SQL Server is software developed by Microsoft, to store
and retrieve data requested by other software applications.
Chapter 5
Syntax
Syntax is known as the grammar, and spelling of a computer programming
language. The computer has its own specific language, and the computer can
only perform an action, if it is typed in the language that it understands. This
language is called the syntax. Syntax of a computer programming is also
defined as a set of rules that describes the combinations of computer symbols
that are part of any element in a computer language or known to be an
appropriately structured document. Syntax programming usually contains
strings that are like words, if these strings are properly synthesized, it
produces correct and valid sentences. Communication flow may differ
because of the difference in programs, however syntax is remains the
communication flow between programmers and their computers. It defines
how a program should be written and interpreted, and if the language of a
program is not well understood by a programmer, syntax error is bound to
occur.
The Importance of Syntax in Computer Programming
Syntax is simply the use of structured language that the computer can
interpret, and when a user fails to use a language that the computer can
understand, it can cause errors and the execution of the programming
command will be unsuccessful. The syntax is also referred to as a bridge or a
means of communication between your computer and you. The essence of
syntax is to be able to work on the computer effectively without any error.
Furthermore, the quality of syntax makes a task easier and simpler. It also
makes reading or understanding code easier.
In the above examples, p which is an integer which stands for the precision
and while s is also an integer but stands for the scale.
However, for the DECIMAL data type, an error occurs if you exceed the
actual number of digits expected to the left of the decimal point. Whereas,
extra digits are truncated if you exceed the number of expected digits to the
right of the decimal point.
NUMERIC [(p[,s])]
This shares a little similarity with the DECIMAL data type. The PointBase
usually treats the NUMERIC data type just the same way as the DECIMAL
data type.
REAL
This is another data type which usually accepts an approximate numeric
value, up to a precision of 64. While declaring a REAL data type, no
parameters are required. An error occurs when you attempt to assign a value
with a precision greater than 64.
FLOAT(p)
This is also similar to the FLOAT data type. It equally accepts approximate
numeric values, for which the precision is defined up to a maximum of 64.
Unless a precision is specified during the declaration, the default precision is
taken as 64. Also, an error is raised when you attempt to assign a value larger
than the already declared precision
DOUBLE PRECISION
The REAL data type usually accepts approximate numeric values, up to a
precision of 64. When declaring DOUBLE PRECISION data type, always
note that no parameters are required. Just like the REAL data type, an error is
raised when you attempt to assign a value larger than the already declared
precision
DATE
This is another data type which accepts date values. While declaring the
DATE data type, it is important to note that no parameters are required. The
Date values should be specified in the defined form which is YYYY-MM-
DD. However, single digit entries are also accepted by PointBase for month
and day values.
Furthermore, month values must always be between 1 and 12, while day
values should be between 1 and 31. This depends on the month and year
values and this should be between 0 and 9999.
Also, values assigned to the DATE data type should be enclosed in a single
quote, and should be preceded by the case insensitive keyword “DATE”; For
instance, DATE '1999-04-04'.
TIMESTAMP
This data type usually accepts timestamp values. This time stamp values
comprises of both a DATE value and a TIME value. When declaring the
TIMESTAMP data type, note that no parameters are required. There is a
defined form in which the Timestamp values should be specified which is
YYYY-MM-DD HH:MM:SS. It’s important to also note that there is a space
separator between the date and time portions of the timestamp.
The specifications and restrictions noted for the TIMESTAMP data type is
also the same for the DATE and TIME data types.
While entering values for the TIMESTAMP data type, the values should be
enclosed in single quotes, and should be preceded by the case insensitive
keyword “TIMESTAMP”; For instance, TIMESTAMP '1999-04-04
07:30:00'.
CLOB [(length)] or CHARACTER LARGE OBJECT
[(length)] or CHAR LARGE OBJECT [(length)]
The Character Large Object (CLOB) data type is quite different from the
CHARACTER [(length)] or VARCHAR (length) data types in that it accepts
character strings which are quite longer than those that are allowed in the
latter. There is a specific syntax that is adopted by the CLOB declaration to
specify the length of the CLOB and it is always in bytes:
n [K | M | G]
In the above syntax, “n” which is an unsigned integer stands for the length.
While K, M, and G stands for Kilobytes, Megabytes or Gigabytes,
respectively. However, if K, M, or G is specified in addition to n, then the
actual length of n is described below:
K = n * 1024
M = n * 1,048,576
G = n * 1,073,741,824
It is noteworthy that the maximum size allowed for CLOB data types is 2
gigabytes. But a default length of 1 byte is used if a length is not specified. It
is also possible for CLOB values to vary in length from one byte up to the
specified length.
Also note that the CLOB data type usually supports Unicode data.
BLOB [(length)] or BINARY LARGE OBJECT [(length)]
BLOB stands for The Binary Large Object data type and it accepts binary
values. There is a unique syntax which the BLOB declaration uses to specify
the length in bytes. Which is;
n [K | M | G]
As seen in the above syntax, “n” is said to be an unsigned integer that stand
for the length. While K, M, and G correspond to Kilobytes, Megabytes or
Gigabytes, respectively. And if K, M, or G is specified in addition to n, then
we can then infer that the actual length of n is the following:
K = n * 1024
M = n * 1,048,576
G = n * 1,073,741,824
However, the maximum size allowed for BLOB data types is just 2
gigabytes. If at all a length is not specified, then a default length of one byte
is used automatically. BLOB values usually vary in length from one byte up
to the specified length.
NOTE: BLOB data types cannot be used with SQL scalar functions.
Chapter 7
1. Arithmetic operators
2. Logical operators
3. Comparison operators
4. Compound operators
5. Character operators
6. Wildcard operators
We shall discuss these operators in this session.
Structured Query Language (SQL) Arithmetic Operators
This Structured Query Language assume 'variable a' holds 10 and 'variable
b' holds 20-
Examples:
2 -= Subtract equals
3
*= Multiply equals
4 /= Divide equals
5 %= Modulo equals
8
|*= Bitwise OR equals
Functioning of SMO
WMI Provider
The WMI Provider objects are usually wrapped by SMO. This then provides
the SMO programmer with just a simple object model which is closely
similar to SMO, without the requirement to understand the programming
model that is represented by the namespace and the details of the SQL Server
WMI Provider. The WMI Provider allows you to configure SQL Server
services as well as client, aliases, and also the server network libraries.
Optimized Performance
The SMO architecture is very efficient in terms of its memory. This is
because objects are only partly instantiated at first, and a limited property
information is requested from the server. There is always a delay in full
instantiation of objects until the object is conspicuously referenced.
For an object to be fully instantiated, then a property needs to be requested
which was not initially in the set of properties that were first retrieved. In
other words, it can also be said that when a particular method is called that
requires such property.
Furthermore, there is always a transition between partially instantiated and
fully instantiated objects which is mostly transparent to the user.
Additionally, most properties which use lots of memory are never retrieved,
unless the property is clearly referenced. A typical example of this is the Size
property of the Database object property. However, partial instantiation might
not be the best performing option for your application because it requires
even more network round trips.
It is very possible to control instantiation just to suit the system environment.
The amount of memory require by the application can be minimized if you
rely on delayed instantiation.
For instance, classes, there are three levels of instantiation that objects that
represent real database objects can exist. These levels are minimal-
instantiated (in which only the minimal required properties are read in one
block), another level is the partially instantiated (in which all the properties
which use a relatively large amount of memory are all read in one block), and
finally, fully instantiated.
Un-instantiated and fully instantiated both refers to the traditional states of
instantiation. Efficiency is increased with a partially instantiated state. This is
because a partially instantiated object does not really contain values for the
full set of object properties. An object that is not directly referenced is said to
be in a partial instantiation state in which most times that is the default state
for such object. But whenever any of these properties is referenced, a fault is
usually generated that prompts a full instantiation of the object.
Capture Execution
The usual method of execution is the direct execution. Usually statements are
sent to an instance of SQL Server directly as they are incurred. An alternative
to this is the capture execution.
This type of execution is useful to capture the Transact-SQL batches which
would typically be executed. This lets the SMO programmer to either defer
the script, store the script for later execution, or even provide a preview for
the end-user.
For instance, a create table, a create database, and also a create index
statement which can first be sent in one batch and then run as three sequential
steps. The user controls this functionality by using the Server object.
Scripting
In SMO, scripting has been improved and then moved into what is referred to
as the Scripter class. The Scripter class can discover various dependencies,
understand the relationships between objects, and enables manipulation of the
different dependency-hierarchy. The Scripter object is the main scripting
object. There are also other supporting objects that handle the dependencies
and respond to the progress or error events.
There are some advanced scripting options that the Scripter object supports.
These include:
Snapshot Databases
This is a read-only copy of a specified database as a specific point in time.
This database can be specified by using the IsDatabaseSnapshot property of
the Database object.
Service Broker
The functionality of the Service Broker is represented by a group of objects
Index Enhancements
SQL Server index enhancements are represented by new properties in the
Index object.
Chapter 9
Types of DBMS
There are four different types of DBMS which are;
Hierarchical
Network DBMS
Object-Oriented DBMS
Relational DBMS
Hierarchical- which is rarely used nowadays and usually supports the
"parent-child" relationship of storing data.
Network DBMS - this type of DBMS employs many-to-many relationships.
And this usually results in very complex database structures. An example of
this DBMS is the RDM (Raima Database Manager) Server.
Object-Oriented DBMS - new data types employ this DBMS. The data to be
stored are always in form of objects. An example of this DBMS is the
TORNADO.
Relational DBMS (RDBMS) - This is a type of Database Management
System that defines database relationships in form of tables, which is also
known as relations. In other words, in a relational database, information is
usually grouped according to its type, which is generally in tables. For
instance, in a logistics company with a database designed which is used to
record fleet information, for effectiveness, you may include a table which
contains list of employees and another table which contains vehicles used by
the employee. In such case, these two different types of structured data would
definitely be held separately because they hold fundamentally separate
information.
Unlike other Database Management Systems such as Network DBMS, the
RDBMS does not support many-to-many relationships. Relational Database
Management System do not support all data types, they usually have already
pre-defined data types which they can support. The Relational Database
Management System is still the most popular DBMS type in the market
today. Common examples of relational database management systems
include Oracle, MySQL, as well as Microsoft SQL Server database.
Relationship between (Relational) Database management
system and SQL
An example of database management system is Microsoft SQL Server. This
terminology should not be confused with the term "database". A Database
Management System is the software which provides the facilities needed to
create and also maintain databases as well as manipulate the information that
is stored within it. Whereas for SQL Server, the databases which are created
are relational databases , so the end product is usually known as a
relational database management system or RDBMS .
The Relational Model
This model proposes that;
The table contains three columns for the payroll ID, name and type of cell
phone used; these being defined in the table's schema. The table has four
rows of data, one for each employee that has access to a cell phone. This is
the first in a series of articles describing the use of Microsoft's SQL Server
Database Management System (DBMS).
2. Indexes
The ease of quick retrieval of information is one major benefit of keeping
information in the database. No one wants to save a document and then
struggles to find it or locate it. There may be times that you even forget what
the file or information was saved with. But with this feature you can always
easily retrieve the document or data from the database.
So it is possible to apply some criteria for arrangement of file in the database
especially in a row or column.
If the DBMS is needed to scan through all of the data stored within a table in
order to retrieve the desired information, then be sure that the entire process
would be very slow, especially if the table contains thousands of rows.
Therefore, in order to improve retrieval efficiency, an index can be
introduced to the table. Each of the index makes retrieval of file easy. It
provides a quick "look-up" facility for the rows. This is useful because when
an index is in a book, it allows all the possible references in a document or
topic to be quickly located without having to read up every page.
For instance, in the table above, an index may be created for the cellphone
column. This would facilitate prompt queries that require data to be filtered
using the column.
3. Key
Microsoft SQL Server databases has two major keys. The first of these keys
is the primary key while the second is the foreign key.
A primary key is said to be a single column, or may be group of several
columns ( compound key ), which helps to distinctly identify rows in a table.
It is possible for each table in a particular database to have a single primary
key.
Once this is defined, then the data in the primary key column can then be
unique, that is no two rows in the table may contain matching data.
For instance, in the example above, the distinct Payroll ID value could be the
primary key for the employees’ table.
On the other hand, foreign keys are used whenever you are defining a
relationship between different tables. A foreign key is a single column, or
group of columns, in a table that reference the primary key in another table.
The information in foreign key columns does not necessarily have to be
unique. There may be some files that share the same information. For
instance, from the example above, there may be two employees using the
same type of cell phone. For this reason, relationships are often called "one-
to-many links", as one value in the primary key of a table may link to many
rows in related tables.
4 Constraints
Information on a database have rules that apply to them, these rules are
called constraints. They are rules that help to ensure that information on the
database are organized and not distorted. They help to enforce business rules
on a tabular data.
5 Views
A view helps to gather information from diverse sources and then present the
same information in the defined format of a single table. Although the
information gathered may be filtered to remove information that are not
relevant.
Popular Relational Database Management Systems
There are some popular relational database management systems, and they
will be discussed in this chapter.
1 MySQL
This is the most popular open source SQL database which is usually used for
development of web application. The main benefit of this is that it is reliable,
inexpensive and also easy to use. It is therefore widely used by a broad
community of developers over the years. The MySQL has been in used since
1995.
One of the disadvantages, however, is that it does not contain some recent
features that most advanced developers would like to use for better
performance. The outcome is also poor when scaling and the open source
development has also lagged since MySQL has been taken over by Oracle.
2 PostgreSQL
This is one of the open source SQL databases which is independent of any
corporation. It is also used basically for development of web application.
Some of the advantages of PostgreSQL over MySQL is that it is also easy to
use, cheap and used by a wide community of developer. In addition, foreign
key support is one of the special features of the PostgreSQL. And it does not
require complex configuration.
On the other hand, it is led popular that the MySQL and this makes it hard to
access, it is also slower than the MySQL.
3Oracle DB
The code for Oracle Database is not open sourced. It is owned by Oracle
Corporation. It is a Database employed by most multinational around the
world especially top financial institutions such as banks. This is because it
offers a powerful combination of comprehensive, technology, and pre-
integrated business applications. It also has some unique functions built in
specifically for banks.
Although it is not free to use by anyone, it can be very expensive to acquire.
4SQL Server
This is owned by Microsoft and it is not open sourced. It is mostly used by
large enterprise and multinationals. Well, there is a free version for trial
where you can test the features but for bogger features. Then, it becomes
expensive to use. This test version is called Express.
5SQLite
This is a very popular open source SQL database. It has the ability to store an
entire database just in one file. It has a major advantage of SQLite which is
its ability to save or store data locally without necessarily using a server.
It is a popular choice for companies that use cellphones, MP3 players, PDAs,
set-top boxes, and other electronic gadgets.
Chapter 10
CREATE statement
Whenever a new database needs to be created, then the ‘create’ command
becomes very useful and relevant. However, it is not just used to establish
and create a separate or new database, it is also equally used to create index,
tables, or even stored procedure.
In Structured Query Language (SQL), the CREATE statement has been
found to be useful in creating a component in a RDBMS (Relational
Database Management System). For instance, In the Structured Query
Language (SQL) 1992 specification, there are specific types of components
that can be created. Some of these components that can be created include the
tables, domains, views, schemas, character sets, translations, collations, and
also the assertions.
However, there are many other implementations which extend the syntax in
other to allow the creation of more elements. Some of these additional
elements include indexes and also the user profiles. Moreover, there are also
some systems which enables or allows CREATE. Some of these systems
include Structured Query Language (SQL), SQL Server as well as the
PostgreSQL among others. But it should also be noted that there are some
other data description language (DDL) commands, which are found just
inside a typical database transaction and this may cause them to be rolled
back
CREATE TABLE statement
One of the most commonly used CREATE commands out of all the
commands is the CREATE TABLE command. Below is a typical example of
how this command is used;
CREATE TABLE [table name] ( [column definitions] ) [table parameters]
However, below are also some of the column definitions which are:
Deleting a table
It is very much possible to delete an existing table using the DROP
command. Take for instance, the command below will delete the books table:
DROP TABLE books
ALTER statement
For a situation where the existing database needs to be modified. Then the
ALTER statement command is used in such situation.
In Structured Query Language (SQL), an ALTER statement completely
changes the properties of an object which is inside of a RDBMS (Relational
Database Management System). However, the type of RDBMS (Relational
Database Management System) that is used goes a long way to determining
the types of objects that can be altered.
Below is a typical way in which the ALTER statement can be used;
ALTER objecttype objectname parameters.
Take for instance, the command to add and also to remove a column named
buby for an already existing table named silk is seen below:
ALTER TABLE silk ADD buby INTEGER;
ALTER TABLE silk DROP COLUMN buby;
TRUNCATE statement
Perhaps you desire to delete all the data on a table, then the TRUNCATE
statement is useful for such. What about the DELETE command you may
ask? Is it not doing the same work as the DELETE command?
Well, the TRUNCATE statement command deletes faster than even the
DELETE command. It tends to clear the data in the table quicker than the
DELETE statement command.
Below is a typical usage of the TRUNCATE statement.
TRUNCATE TABLE table_name;
COMMENT
The COMMENT statement is useful to add comment to the data dictionary. It
is a very important part of the Structured Query Language (SQL) also.
RENAME
This command helps to rename an object. Perhaps you desire to change the
name used to save a data on the SQL server into another suitable one either
for easy navigation or for quick search. It can be achieved by using the
RENAME command statement.
CHAPTER 11
VIEWS
Views are virtual tables consisting of rows and columns which are
specifically separated to service the result of queries sent. It could also be
said to be a composition of the data in a table in the form of predefined SQL
query. They are saved on the database for easy access following the SELECT
statement. It is able to join data from multiple tables resulting in a newer and
easier view. However, for views to exist as a stored set of data values, it has
to be indexed. It serves as a protective layer and a security feature that grants
people access to specific data without exposing the underlying base tables.
Views can be built on top of a single or multiple table, as well as upon pre-
existing views. Views could also be deleted as much as created. However,
some certain conditions are required to have been met before any update
could be made, they are:
The SELECT statement used to create the view must not include
a GROUP BY clause or ORDER BY clause.
The SELECT statement must not have the keyword
“DISTINCT”.
The View must ensure it has NOT NULL values.
The view must not be created using nested or complex queries.
The view must be created from a single table, given that any
view created using multiple tables does not allow for an update.
The CREATE OR REPLACE VIEW statement are available to
add or remove relevant fields from a view.
The SELECT clause must not contain summary functions.
The SELECT clause must not contain set functions.
The SELECT clause must not contain set operators.
The WHERE clause must not contain subqueries.
Calculated columns cannot be updated.
Some of the advantages of views include:
QUERIES
A query, as it sounds, is simply a question or request for data, values from a
database. One can simply send in a question based on the set of information
contained, and expect reply based on the data the tables in a database
contains; the sent questions are the queries. A query could either be a select
query which basically serves as a data retrieval query, or an action query
which requires more operations to be carried out on the data set, such as
deletion, updating or insertion. Query has languages which are used in
making requests from a database, and the standard is Microsoft Structured
Query Language (SQL). However, there are several other extensions of the
language under the SQL umbrella which includes Oracle SQL, MySQL, and
NuoDB. There are however different ways to query, but once the basics are
understood, the question formats become adaptive.
It is important to remember that a database stores information in tables,
which is made up of rows that contains the data and columns telling the
database what to store. To help ask a well-defined and directional question,
there is need for knowledge about the following:
What column is the data supposed to be gotten from? What table holds the
required information?
What is it to be selected? What fields are necessary for the particular
question?
Are there influencing conditions to the selection?
In SQL, there are keywords that matches the knowledge statements above.
When the SELECT command is sent, it defines which database to get
information from, the FROM command determines which table(s) to look at,
and the WHERE command requests special conditions which are required for
processing of such data.
A close to great example of how query works is the web search, however,
they do not require keywords or positional parameters as in the case of SQL
Languages. Once texts are typed into a search engine, such as Google, Yahoo
or Bing, there is a request for information on a specific topic, and the request
is finalized upon the selection of “ENTER”. Afterwards, the search engine
deploys an algorithm to determine the best results basing on the search
engine’s set significance which are not accessible to the public.
Types of search queries includes Navigational searches which directs
searches that are intended to find a particular website/blog, Informational
searches which are designed to span across broad subject matters like
comparisons, and Transactional searches which aims at completing a
transaction/purchase.
THE RELATIONSHIP BETWEEN INDEX, VIEWS and
QUERIES
The index, view and query are all tied to one point of a database. The query
happens to be at the top of the chart as it is the request that brings forth a
programmed view which searches through an index for results to present.
DATABASE SECURITY
One of the aspects of information technology that most people are careful
about is the aspect of security. A lot of privacy goes into developing a
software and the last thing anyone would want is to see his work in the wrong
hands. Data is the key and some files are for national security, so they must
be well protected and secured as well as to safe the lives and property of the
citizens.
Hence the subject of securing the information on the database is the key.
Database security refers to strict regulations. Users of various platforms
especially online platform expect their information to be kept confidential
and their privacy taken very seriously. For multinational organizations with
online database, they must have necessity priorities database security. This
will ensure that the classified information of the organization do not fall into
the wrong hands especially their rivals or close competitors.
Examples of such strict regulations are The General Data Protection
Regulation (GDPR), which was enacted on the 25th May, 2018. Also in
Australia, there is the Notifiable Data Breaches Scheme (NDB).
Data preservation
There are some ways in which the stored data can be preserved:
DATABASE ADMINISTRATION
There is so much about data, database, and database administration when it
comes to SQL. Database administration is the act of managing, and
continuously maintaining a database management systems (DBMS) software.
Database management system software such as Microsoft SQL Server,
Oracle, and IBM DB2 has been found needing ongoing management as it is
being used. Database administration is the brain behind the creation of new
databases, and updating of pre-existing ones based on the data collection
needs of a company. Database administration requires in-depth knowledge in
areas related to the type of data an organization is dealing with. Data being
the focus of the modern information world makes it the core of applications,
and systems being used.
Database administration is responsible for the structures designed from
models produced by the data administration area itself. Information regarding
where applications will run, and the system surrounding how it would be
used in order to organize and structure appropriately are inputted here.
Database administration also entails the ability to make available databases
when needed. At different tiers of architecture, a new focus comes to bear in
the information processing community which is managing and controlling of
multiple DBMSs. The database administration area is saddled with the
responsibility of responding to pressures in a rapid way and using a pattern
that is sound on the infrastructural end.
In a database administration environment, there are a lot of factors which
contribute to uncertainties, some of which are:
By
Computer Programming Academy
Cоруright 2020 bу Computer Programming Academy
All rightѕ rеѕеrvеd
Thiѕ dосumеnt iѕ gеаrеd tоwаrdѕ рrоviding еxасt аnd rеliаblе infоrmаtiоn in
rеgаrdѕ tо thе tорiс аnd iѕѕuе соvеrеd. Thе рubliсаtiоn iѕ ѕоld with thе idеа
thаt thе рubliѕhеr iѕ nоt rеquirеd tо rеndеr ассоunting, оffiсiаllу реrmittеd, оr
оthеrwiѕе, quаlifiеd ѕеrviсеѕ. If аdviсе iѕ nесеѕѕаrу, lеgаl оr рrоfеѕѕiоnаl, a
рrасtiсеd individuаl in thе рrоfеѕѕiоn ѕhоuld bе оrdеrеd.
- Frоm a Dесlаrаtiоn оf Prinсiрlеѕ whiсh wаѕ ассерtеd аnd аррrоvеd еquаllу
bу a Cоmmittее оf thе Amеriсаn Bаr Aѕѕосiаtiоn аnd a Cоmmittее оf
Publiѕhеrѕ аnd Aѕѕосiаtiоnѕ.
In nо wау iѕ, it lеgаl tо rерrоduсе, duрliсаtе, оr trаnѕmit аnу раrt оf thiѕ
dосumеnt in еithеr еlесtrоniс mеаnѕ оr in рrintеd fоrmаt. Rесоrding оf thiѕ
рubliсаtiоn iѕ ѕtriсtlу рrоhibitеd аnd аnу ѕtоrаgе оf thiѕ dосumеnt iѕ nоt
аllоwеd unlеѕѕ with writtеn реrmiѕѕiоn frоm thе рubliѕhеr. All rightѕ
rеѕеrvеd.
Thе infоrmаtiоn рrоvidеd hеrеin iѕ ѕtаtеd tо bе truthful аnd соnѕiѕtеnt, in thаt
аnу liаbilitу, in tеrmѕ оf inаttеntiоn оr оthеrwiѕе, bу аnу uѕаgе оr аbuѕе оf
аnу роliсiеѕ, рrосеѕѕеѕ, оr dirесtiоnѕ соntаinеd within is thе ѕоlitаrу аnd uttеr
rеѕроnѕibilitу оf thе rесiрiеnt reader. Undеr nо сirсumѕtаnсеѕ will аnу lеgаl
rеѕроnѕibilitу оr blаmе bе hеld аgаinѕt thе рubliѕhеr fоr аnу rераrаtiоn,
dаmаgеѕ, оr mоnеtаrу lоѕѕ duе tо thе infоrmаtiоn hеrеin, еithеr dirесtlу оr
indirесtlу.
Rеѕресtivе аuthоrѕ оwn аll соруrightѕ nоt hеld bу thе рubliѕhеr.
Thе infоrmаtiоn hеrеin iѕ оffеrеd fоr infоrmаtiоnаl рurроѕеѕ ѕоlеlу, аnd iѕ
univеrѕаl аѕ ѕо. Thе рrеѕеntаtiоn оf thе information iѕ withоut соntrасt оr аnу
tуре оf guаrаntее аѕѕurаnсе.
Thе trаdеmаrkѕ thаt аrе uѕеd аrе withоut аnу соnѕеnt аnd thе рubliсаtiоn оf
thе trаdеmаrk iѕ withоut реrmiѕѕiоn оr bасking bу thе trаdеmаrk оwnеr. All
trаdеmаrkѕ аnd brands within thiѕ bооk аrе fоr сlаrifуing рurроѕеѕ оnlу аnd
аrе thе оwnеd bу the оwnеrѕ thеmѕеlvеѕ, nоt аffiliаtеd with thiѕ dосumеnt.
PHP: The Ultimate Crash Course to Learn PHP
with Practical Computer Coding Exercises
By
Computer Programming Academy
Table of Contents
Introduction
Chapter One
Introduction to PHP
History of PHP:
PHP 3& 4:
Exercise 1:
Chapter Two
Why Learn PHP?
Features of PHP:
Creating A Simple Program in PHP:
How PHP is Applied:
Setting up a PHP Environment on Your System:
How to Install the PHP Parser:
Setting up the Development Environment
Setting Up A Production Environment:
Exercises 2:
Chapter Three
Basic Syntax
Escaping to PHP:
Using Canonical PHP Tags:
Using SGML-style (short-open) Tags:
Using ASP-style Tags:
HTML Script Tags:
How to Comment in PHP Codes:
Single-line Comments:
Multi-lines Printing:
Multi-lines Comments:
Whitespace Insensitivity:
Case Sensitivity:
Statements are Expressions Ended using Semicolons:
Braces Form Blocks:
How to Execute PHP Scripts from the Command Prompt:
Exercise 3:
Chapter Four
Variables in PHP
Integers:
Doubles:
Booleans:
NULL:
Strings:
Arrays:
Objects:
Resources:
Interpreting Other Variable Types as Booleans:
The Here Document:
The Variable Scope:
Naming Variables in PHP:
Exercise 4:
Chapter Five
Constants in PHP
The constant() function:
Valid and Invalid Constant names:
Magic Constants in PHP:
Exercise 5:
Chapter Six
Operators in PHP
Arithmetic Operators:
Comparison Operators:
Logical Operators:
Assignment Operators:
Conditional Operators:
Categories of Operators:
Binary Operators:
Operator Precedence in PHP:
Exercise 6:
Chapter Seven
Decision Making In PHP
The If…else Statement:
The If Statement:
The Elseif Statement:
The Else Statement:
The Switch Statement:
Exercise 7:
Chapter Eight
Loops in PHP
The While Loop:
The for Loop:
PHP do…while loop:
The Distinction Between do…while and do loops:
The Foreach Loop:
The Break Statement:
The Continue Statement:
Exercise 8:
Chapter Nine
Arrays in PHP
How Arrays are Created:
Types of Arrays:
Exercise 9:
Chapter Ten
Strings in PHP
Quoted String Types:
Manipulating Strings in PHP:
Length of Strings:
Calculating the Length of a String:
Replacing Text in Strings:
How to Use the strpos() Function:
Exercise 10:
Chapter Eleven
Functions in PHP
How Functions Work:
Creating User-defined Functions:
Function Arguments in PHP:
Passing Arguments Through Reference:
Default Argument Values in PHP:
Functions with Parameters in PHP:
Returning Value Functions in PHP:
Creating Default Values for Function Parameters:
Dynamic Function Calls:
PHP Return Type Declarations:
Exercise 11:
Chapter Twelve
Files in PHP
File Operations in PHP:
File System Functions:
Exercise 12:
Chapter Thirteen
Web Concepts in PHP
Randomly Displaying Images:
How to Use HTML Forms in PHP:
Browser Redirection:
Exercise 13:
Chapter Fourteen
Get and Post Methods in PHP
The GET method:
The POST Method:
The $_REQUEST variable:
Exercise 14:
Chapter Fifteen
File Inclusion in PHP
The include() Function:
The require() Function:
Exercise 15:
Chapter Sixteen
Coding Standards and Conventions in PHP
Line Length and Indentation:
Control Structures:
Function Calls:
Function Definitions:
Exercise 16:
Chapter Seventeen
Cookies in PHP
Setting up Cookies in PHP:
Deleting Cookies in PHP:
Exercise 17:
Answers
Exercise 1:
Exercise 2:
Exercise 3:
Exercise 4:
Exercise 5:
Exercise 6:
Exercise 7:
Exercise 8:
Exercise 9:
Exercise 10:
Exercise 11:
Exercise 12:
Exercise 13:
Exercise 14:
Exercise 15:
Exercise 16:
Exercise 17:
Introduction
The internet is a miracle that is used across the world in a variety of ways. A
good part of the internet is made up of webpages connected to one service or
another. In turn, these services are useful in our everyday lives. Webpages are
primarily built using PHP programs. So, in all, it goes to say that PHP forms
an integral part of our lives even without our knowledge. In this vein, it
cannot now be overstated how vital PHP can be to a learner regardless of
how or where it is applied. It is for this reason this book was written. That it
might intimate beginners on the basics of the language and introduce them to
the vast potentials, it holds. Contained in this book is a well-detailed content
with a simplistic style and unmatched practicality. Journey into the world of
PHP, and grow in the knowledge of knowing what makes the internet go
round. You'll be glad you did.
Chapter One
Introduction to PHP
PHP is a recursive acronym for Hypertext Pre-processor. It is an open-source
programing language that can be put to a variety of uses, accounting for its
popularity and broad applications. However, as its name must have spelt out,
PHP is particularly well suited for application in hypertext Markup Language
(HTML) and web development, as a result of its original scripting as created
in 1994 by Rasmus Lerdorf. Among contemporary programming languages,
PHP does well for itself, earning it a high place as one of the most used and
powerful languages there is in the world today. Its versatility points at why
Facebook and WordPress, some of the most significant outfits in their
respective niches in present times, use them for their programming. The
flexibility, speed, and pragmatism of the language make it even more
endearing to programmers to whom such qualities are of the highest import.
Coding style:
<!DOCTYPE html>
<html>
<head>
<title>Samplecode</title>
</head>
<body>
<?php
echo "Hello, this is a PHP script!";
?>
</body>
</html>
History of PHP:
<!--include /selectedtext/header.html-->
<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_resultChrome-->
Hello, you are using Netscape!<p>
<!--endif-->
<!--include /selectedtext/footer.html-->
The earliest forms of PHP weren't created with the intent of becoming a
programming language; hence, its growth and spread were organic. Even
Lerdorf acknowledged this when he confessed to having no idea how to stop
the widespread use, as he had no intention whatsoever of coming up with a
programming language of his own. He owned up to not knowing how to
create a programming language and resorted to including all the logical steps
as he went by. A development team was assembled to work on the language,
and after an extended period of working and beta tests, PHP/FI 2 made its
public debut in 1997, November. The sheer knowledge of PHP not being
expressly designed as a programming language, but instead was organically
developed has resulted in a bit of inconsistency in areas such as the naming
of functions, and the ordering of their respective parameters. Other cases for
inconsistency can be seen in how function names were picked to complement
the lower-level libraries undergoing "wrapping" from PHP. In some earliest
versions of the language, the length of a function name was internally applied
as a hash function, as such, names were picked as a means of improving the
grouping of hash values.
PHP 3& 4:
In 1997, Andi Gutmans and Zeey Suraski jointly wrote the parser, and are
both credited with the fundamental parts of PHP 3, as well as the change of
the languages name into the recursive acronym it now means. Public testing
began on PHP 4 afterwards, but the official launch wasn't until 1998 in June.
At this point, Gutmans and Suraski had begun to rewrite the core of the
language, leading to the production of the Zend Engine in 1999. Both
programmers are also credited with the creation of Zend Technologies in
Israel (Ramat Gan region). In May of the year 2000, PHP 4 was published. It
ran on the new Zend Engine 1.0. By the August of 2008, PHP reached
version 4.4.9 and was discontinued; so no further releases or updates would
be done on it.
Exercise 1:
Features of PHP:
Five important features contribute to the practical nature of PHP and make it
possible:
Familiarity
Efficiency
Flexibility
Simplicity
Security
Creating A Simple Program in PHP:
The Hello World Program
To help you get started on PHP programming, we attempt to create the
traditional Hello World program. It is a simple program, which, when
executed, produces "Hello World!"
<html>
<head>
<title>Hello World Program</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
On Windows systems:
Installing a Windows server is rather expensive, so you might have to turn to
cheaper alternatives in third-party apps which can be installed and set up to
provide a server environment suitable for coding. Some of such apps that can
be used include WAMP and XAMPP. Every one of these apps performs the
same function of installing PHP, MySQL, and Apache within the program.
Of both mentioned apps, XAMPP is most preferred by users. You can get the
latest XAMPP from the link www.apachefriends.org because it is cross-
platform. XAMPP I an acronym that stands for cross-platform (X), Apache
(A), MariaDB (M), PHP (P), and Perl (P). The installation process for
XAMPP is pretty easy to carry out, so it shouldn't be a problem. Also, keep in
mind that it is possible to install Laravel with XAMPP. When the installation
wizard pops up, click next, and I agree when necessary. Albeit, in terms of
the development environment, you have to install the development
environment that is required to convert the php.ini file and enable error
messages to be shown. Should error messages not be displayed, visit the path
c:xampp/php/ and click on the php.ini file. Ensure that everything placed
under the logging and error handling in line 463, has been switched on, then
start your Apache server again.
When the XAMPP has been completely installed, a dashboard should open
that can be used to initialize, end, and set up the services. When you have
completed the installation of XAMPP and have it ultimately set up and
running. Visit the Webroot that can be found in c:xampp/htdocs/, which is the
work environment for creating sites and applications. To check out your
work, proceed to visit the localhost into the address bar of your browser.
Doing this should start the launch of the index file within htdocs.
On Mac systems:
The installation on Mac systems is quite similar to that of the Windows
system. The least expensive and most straight forward to set up the
development environment is by installing third-party applications. In this
case, you can use MAMP and XAMPP even. Albeit, your choice of
installation doesn't matter because they all perform similar functions. Also,
you must install all the development files. On Mac, the Webroot is somewhat
different from that of Windows because it is located in the path
applications/xampp/htdocs, aside from this, there is no other noticeable
difference.
Exercises 2:
Multi-lines Comments:
This type of comment usually serves as a means of Introducing concise
explanations or pseudocode algorithms when coding. The multi-line style
used in PHP is similar to that of the C programming language. Shown below
is a sample of a multi-line comment for better understanding:
<?
/* This is a comment with multi-line
Author: Jane Doe
Purpose: Multiline Comments Demo
Subject: PHP
*/
<?php
$profit = 34;
print("Variable profit is $profit<br>");
print("Variable PrOfiT is $PrOfiT<br>");
?>
</body>
</html>
When executed, the results of this code will be:
Variable profit is 34
Variable PrOfiT is…
Statements are Expressions Ended using Semicolons:
In PHP, a statement refers to by form of expression that is terminated using a
semicolon (;). A series of valid statements in PHP represents a valid PHP
program, especially if it is encased in PHP tags. Take an example of a
common PHP statement shown below that is used in assigning a set of
characters to the variable $greeting:
$greeting = "Welcome to PHP!"
Expressions are a combination of tokens:
Tokens are the smallest, indivisible building blocks that make up a PHP
program. They could get constants (e.g. FALSE), variables (e.g. $greeting),
numbers (e.g. (π) 3.14159), and strings (e.g. .two.). Tokens could also include
the special characters that contribute to PHP syntax, such as for, else, if,
while, among others.
Braces Form Blocks:
Even though it is impossible to combine statements similarly to expressions,
it is possible to place a set of statements in all the places a statement can be in
by encasing them within a pair of curly braces.
Consider the sample below containing two statements of which both are
equal:
if (7 == 4 + 3)
print("Great - I haven't completely lost my mind.<br>");
if (7 == 4 + 3) {
print("Great - I haven't completely");
print("lost my mind.<br>");
}
Proceed to execute this script shown above using your command prompt in
the following ways:
$ phptest.php
Hello PHP!!!
Exercise 3:
1. What is the use of a semicolon in PHP?
2. What are tokens?
3. Define the term 'comments.'
4. Explain the case-sensitive nature of PHP.
5. What constitutes a valid program in PHP?
6. Explain the insensitivity of PHP to whitespaces.
7. What are multi-line comments used for?
8. State the conditions necessary for processing short tags in PHP.
9. What is the function of the Escaping to PHP mechanism?
10. What type of tag in PHP assures a user of correct
interpretations of tags regardless of the condition?
Chapter Four
Variables in PHP
There is one primary process of storing information within the body of a PHP
program. This process is done with the help of a variable. To better
understand the concept of variables in PHP, below are some crucial points to
take into consideration:
1. Every variable used in PHP is represented with a preceding $ (dollar
sign).
2. Any value outputted by a variable is an indication of the most recent
value assigned to it.
3. To assign a variable, the equal to (=) operator is used, with the
variable placed on the left-hand area while the evaluated expression
takes the spot to the right of the operator.
4. Although it is possible to declare variables before assigning them, it
is not compulsory to do so.
5. The variables used in PHP have no intrinsic types, meaning a
variable has no prior or future knowledge of what it would be used
to store, be it a set of characters or a distinct number.
6. Any variable that is introduced before any value is assigned to it
adopts a default value.
7. In PHP, the process of converting from types from one state to
another is automatically performed when needed.
8. The variables in PHP are similar to those in Perl.
Simple type:
Integers:
Integers are the most basic forms of variables in PHP, and they are similar to
basic mathematical whole numbers in that they can be either negative or
positive. It is possible to assign an integer to a variable; however, it is also
possible to use them in expressions in like fashion:
$int_var = 678910;
$another_int = -678910 + 678910;
Integers can take on any form, including but not limited to base 8 (octal),
base 10 (decimal), and base 16 (hexadecimal). By default, base 10 (decimal)
is used while base 8 or octal integers are indicated using a preceding zero (0),
and base 16 or hexadecimal proceed with 0x. On the majority of common
platforms, the smallest known integer is (.2,147,483,647) or (2**31 . 1),
while the largest is (2,147,483,647) or (2**31 . 1).
Doubles:
In a default state, doubles are printed with the required number of decimal
places. Take a look at the sample below for better understanding:
<?php
$many_a = 1.3422220;
$many_b = 2.1111345;
$few = $many_a + $many_b;
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
All of the variables shown below have an embedded true value to their names
when applied and executed in a Boolean context:
$true_num = 3 + 0.14200;
$true_str = "Tried and true"
$true_array[23] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 777 - 777;
$false_str = "";
NULL:
To provide a variable with the NULL value, proceed with the assigning
process in like manner:
$my_var = NULL;
NULL is a special constant that is capitalized as a result of convention;
however, it isn't necessarily insensitive to case. So, you could type it as
follows:
$my_var = null;
Any variable which has been assigned the value NULL exhibits the following
qualities:
1. FALSE is returned when tested with an IsSet() function.
2. In a Boolean context, it evaluates to FALSE.
Strings:
Below is a valid sample of a string:
$string_1 = "It is a string encased in double quotes";
$string_2 = 'It is a slightly longer, singly quoted string';
$string_56 = "This string has fifty-six characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are used in a literal manner; however, doubly quoted
strings take the place of variables and their values, even to the point of
specially interpreting some character sets.
<?php
$variable = "class";
$literally = 'The $variable will not print!';
print($literally);
print "<br>";
<channel>
<title>How Are You</title>
<link>http://menu.sample.org/ </link>
<description>It’s been a rather long while.</description>
</channel>
_XML_;
echo <<<END
This line makes use of the "here document" syntax to return multiple lines
with variable interpolation. Keep in mind that the here document terminator
has to appear on a line having just a semicolon with no extra whitespace!
END;
print $channel;
?>
Running this script will output the following results:
This makes use of the "here document" syntax to output multiple lines using
a variable interpolation. Keep in mind that the here document terminator has
to appear on a line having just a semicolon with no extra whitespace!
<channel>
<title>How Are You<title>
<link>http://menu.sample.org/<link>
<description> It’s been a rather long while.</description>
The Variable Scope:
A variable scope is a term used to describe the range of availability that a
variable has in the program in which it is assigned. Variables in PHP tend to
adopt one of four types of scopes. These types include:
1. Static variables
2. Function Parameters
3. Local variables
4. Global variables
Exercise 4:
1. What is a variable scope?
2. List five characters prohibited from use in variable names.
3. What does the statement "there add no artificial limits" mean for the
length of a string?
4. What is the difference between singly and doubly quoted strings?
5. What is the evaluation of NULL in a Boolean context?
6. What two constants are used as Booleans in PHP?
7. How are octal integers indicated?
8. What are variables?
9. How is the here document used?
10. Explain the term "integers."
Chapter Five
Constants in PHP
A constant is a term used to identify a simple value. The value of a constant
can't be altered while a script is being executed. Constants are sensitive to
case by default, although constant identifiers always begin with uppercases,
usually by convention. The name of a constant usually begins with an
underscore or a letter quickly succeeded by any amount of underscores,
numbers, or letters. When a constant is defined, it cannot be undefined or
changed throughout the execution. The function—define() is used in defining
a constant, and in retrieving the value assigned to a constant, you have to
specify its name. Unlike with other variables, you need not have a constant
beginning with a dollar sign ($). It is also possible to make use of the
constant() function when reading the value of a constant, especially when you
need to collect the name of the constant dynamically.
The constant() function:
As the name connotes, the function outputs the value assigned to the
constant. This function is especially helpful when you need to output the
value of a constant, but have no idea what its name is. That is, it is outputted
using a function or is stored in a variable. Consider the example shown
below:
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data, such as strings, floats, integers, and Boolean, can only be
stored in constants.
The distinction between variables and constants:
1. There is no point of using a dollar sign ($) before introducing any
constant, whereas, in the case of variables, it is essential to use the
dollar sign.
2. Constants can't be defined using mere assignment as they can only
be defined with the function—define().
3. Constants could be accessed and defined from any place with no
regards given to the rules regarding variable scoping.
4. When the constants have been set and may be undefined or
redefined.
Exercise 5:
1. What kind of data can be stored in constants?
2. How does the _FILE_ constant work in PHP?
3. What is the naming condition for constants?
4. What is the constant() function used for?
5. What property do constants exhibit during the execution of scripts?
6. What are the five magic constants in PHP?
7. In terms of assigning values, how do constants differ from variables?
8. What are constants?
9. How is the constant() function used?
10. What factor is the value of a _LINE_ constant dependent on?
Chapter Six
Operators in PHP
The definition of an operator can be better explained with the aid of an
example, so, let's consider the expression: 3 + 7, which is equal to 10. In this
example, the numbers 3 and 7 are known as the operands, and the sign of
addition (+) is regarded as the operator. In this sense, an operator is a
construct used in performing operations between several variables. In PHP
programming, there are five categories of supported operator types. They are:
1. Logical or Relational Operators
2. Arithmetic Operators
3. Assignment Operators
4. Comparison Operators
5. Conditional or Ternary Operators
Comparison Operators:
The comparison operators supported in PHP are discussed below:
For better understanding, examples will be included to indicate their
functions. In the samples, variable X holds a value of 5 and variable Y holds
a value of 15.
1. ==: This operator is used to find out whether or not the value of two
operands is equal. E.g. (X == Y) is not true.
2. !=: This operator is used to check whether or not the values of two
operands are equal. If the values are unequal, then the condition is
returned as true. E.g. (X != Y) is true.
3. >: This operator is used in checking whether the value of the left
operand is greater than that of the right operand. The condition is
returned as true if the answer is yes. E.g. (X > Y) is not true.
4. <: This operator is used in checking whether the value of the left
operand is lesser than that of the right operand. The condition is
returned as true if the answer is yes. E.g. (X < Y) is true.
5. >=: This operator is used in checking whether the value of the left
operand is greater than or equal to that of the right operand. The
condition is returned as true if the answer is yes. E.g. (X >= Y) is not
true.
6. <=: This operator is used in checking whether the value of the left
operand is lesser than or equal to that of the right operand. The
condition is returned as true if the answer is yes. E.g. (X <= Y) is
true.
Logical Operators:
The logical operators supported in PHP are discussed below:
For better understanding, examples will be included to indicate their
functions. In the samples, variable X holds a value of 5 and variable Y holds
a value of 15.
1. and: This operator is known as the Logical AND operator. When
both operands are true, the condition is returned as true. E.g. (X and
Y) is true.
2. or: This operator is known as the Logical OR Operator. When both
of the two operands are non-zero, then the condition is returned as
true. E.g. (X or Y) is true.
3. &&: This operator is known as the Logical AND Operator. When
both of the operands are nonzero, the condition is returned as true.
E.g. (X && Y) is true.
4. ||: This operator is called the Logical OR Operator. When both of the
two operands are non-zero, then the condition is returned as true.
E.g. (X || Y) is true.
5. !: This operator is known as the Logical NOT Operator. It is used to
reverse the logical state of operands. When a condition is true, the
Logical NOT Operator turns it to false. !(X && Y) is false.
Assignment Operators:
The assignment operators supported in PHP are discussed below:
1. =: This is a simple assignment operator which assigns a value from
the right side operand(s) to that of the left side operand. E.g. Z = X +
Y will assign the value of the operation (X + Y) to Z.
2. +=: This is the Add AND assignment operator. It is used to add the
right operands to the operands on the left and assign the returned
value to the left operand. E.g. Z += X is the same thing as Z = Z + X.
3. -=: This is the Subtract AND assignment operator. It is used to
subtract the right operand from the operand on the left and assign the
returned value to the left operand. E.g. Z -= X is the same thing as Z
= Z - X.
4. *=: This is the Multiply AND assignment operator. It is used to
multiply the right operand from the operand on the left and assign
the returned value to the left operand. E.g. Z *= X is the same thing
as Z = Z * X.
5. /=: This is the Divide AND assignment operator. It is used to divide
the right operand from the operand on the left and assign the
returned value to the left operand. E.g. Z -= X is the same thing as Z
= Z - X.
6. %=: This is the Modulus AND assignment operator. It is used to
subtract the right operand from the operand on the left and assign the
returned value to the left operand. E.g. Z %= X is the same thing as
Z = Z % X.
Conditional Operators:
Conditional Operators are used in evaluating expressions for a true or false
value before one of the two outputted statements is then executed depending
on the outcome of the evaluation process. The conditional operators
supported in PHP have the syntax shown below:
1. ?: in PHP, this operator represents a conditional expression. E.g.
When the condition is true? Then value A: Otherwise value B.
Categories of Operators:
Asides the types of operators, there are four other categories under which the
operators in PHP are classified. As such, all the operators discussed above
can be classified into one of the categories outlined below:
Unary prefix operators:
This refers to the operators that precede an operand in an operation.
Binary Operators:
This refers to operators that require two operands to carry out a series of
logical and arithmetic operations.
Conditional operators:
This category of operators is also known as Ternary operators. They require
three operands to be used and evaluate any of the second or third operations
depending on the outcome of the first operation.
Assignment operators:
This refers to operators that are used to assign values to variables in an
expression.
<html>
<body>
<?php
$t = time("H");
if ($t == "Morn")
echo "Have a great day!";
else
echo "Good night! Sleep well.";
?>
</body>
</html>
The result that is produced reads as follows:
Have a great day!
The If Statement:
The if statement serves as a means of taking control of how a statement that
follows it is executed — in this case, a block of code or single statement
contained in braces. The if statement evaluates the expression contained in
parentheses. Should the expression result in a value considered to be true, the
execution process is initiated. If not, the whole statement is abandoned.
Doing this allows your PHP script to make decisions on its own based on a
range of factors selected.
Syntax:
if ( expression ) {
// code to run if the expression outputs as true
}
Sample:
The following code would display x is greater than y if $x is greater than $y:
<?php
$x=5;
$y=2;
if ($x > $y)
echo "x is bigger than y";
?>
The Elseif Statement:
This statement is used alongside the if…else statement during the execution
of a series of codes, should one of a variety of conditions be true. As the
name connotes, the elseif statement is a mixture of both if and else
statements. As with the else statement, the elseif statement extends the if
statement to run another statement in the event that the main if expression is
evaluated as FALSE. Albeit, contrary to the else statement, the elseif
statement runs the alternative expression only when the assigned conditional
expression is evaluated to be TRUE. So, put simply, whenever you wish to
run a set of code when one of many different conditions evaluate to true, the
elseif statement should be used.
Syntax
if (condition)
code to be run if the condition evaluates to true;
elseif (condition)
code to be run if the condition evaluates to true;
else
code to be run if the condition evaluates to false;
Sample:
The sample shown below produces “Good morning. Rise and shine!” if the
period of the day is Morning, and “Good night! Sleep well.” when it is night.
Otherwise, it produces “Have a great day!”
<html>
<body>
<?php
$t = time("T");
if ($t == "Morn")
echo "Good morning. Rise and shine!";
</body>
</html>
When executed, the result shown below will be outputted:
Good morning. Rise and shine!
The Else Statement:
When making use of the if statement, it would often be required of you to
define another set of code to be run when the expression being tested
evaluates as false. To do this; the else statement is added to the if an extra set
of code succeeds statement and.
Syntax:
if ( expression ) {
// code to run if the expression outputs as true
} else {
// code to run in any other cases
}
Sample:
The example described below will output x to be greater than y when $x is
greater than $y, and x is NOT greater than y otherwise:
<?php
$x=5;
$y=2;
if ($x > $y) {
echo "x is greater than y";
}
else {
echo "x is NOT greater than y";
}
?>
As is seen in the example, the else statement cannot be executed until the if
statement is evaluated to be FALSE.
The Switch Statement:
The switch statement is used when you have to pick and run one of a series of
codes. The switch statement shares a bit of similarity to a set of If statements
included in a single expression. But rather than indulge in repetitive usage of
If and Elseif statements, the switch statement is used instead. Many times,
you might want to contrast a single expression or variable with a host of other
different values and run a distinct block of code depending on the outcome of
the value it evaluates as. In such a case, the switch statement is your go-to
decision-maker.
Syntax:
switch (expression){
case labelA:
code to be run if expression = labelA;
break;
case labelB:
code to be run if expression = labelB;
break;
default:
code to be run
if the expression is not
Similar to both labelA and labelB;
}
Sample:
How the switch statement works are quite unusual. It begins by evaluating a
particular expression before moving on to search for a label that matches the
evaluated value. When a value that matches a label is located, the code
assigned to the matched label will be run. However, should none of the labels
matches the value, then the statement will be run using any default code
specified in the program.
<html>
<body>
<?php
$t = time("T");
switch ($t){
case "Mon":
echo "It’s Monday today";
break;
case "Tue":
echo "It’s Tuesday today";
break;
case "Wed":
echo "It’s Wednesday today";
break;
case "Thu":
echo "It’s Thursday today";
break;
case "Fri":
echo "It’s Friday today";
break;
case "Sat":
echo "It’s Saturday today";
break;
case "Sun":
echo "It’s Sunday today";
break;
default:
echo "What day is it today?";
}
?>
</body>
</html>
The result shown below will be outputted upon execution:
It’s Monday today
Exercise 7:
1. The statement evaluated by the If statement is enclosed in what?
2. What statement is a combination of both else and if statements?
3. What statement is used with an if statement when the evaluated
statement turns out as false?
4. What expression is the elseif statement responsible for running?
5. In switch statements, when no label matches a value, how is the
statement evaluated?
6. When one condition is true, and another isn’t, what statement is
used?
7. Statements that have no purpose are called what?
8. What is a statement-group?
9. In what case would an expression be abandoned in an if statement?
10. Why is the switch statement used?
Chapter Eight
Loops in PHP
In PHP, loops are tools used in executing a single block of code over and
over, given that a particular condition is reached. The fundamental idea
behind the concept of looping is to introduce automation to repetitive actions
in a program as a way of conserving effort and time. In PHP programming,
there are four supported types of loops. They are:
1. While loops
2. For loops
3. Do…while loops
4. Foreach loops
In this section, we delve deep into the concept of loops, how they work, and
how to loop through a set of values in an array; especially for loops directly
targeted at arrays like the foreach loop.
The While Loop:
As long as the specified condition to a while loop evaluates as true, a while
statement continuously loops through a series of codes. As such, when the
evaluated expression outputs as true, it kick-starts the execution of the block
of code. Once the code has entirely executed the test expression, the process
begins again with evaluation, and the loop goes on until the test expression or
statement reaches a point of being false.
Syntax
while(expression){
// Code to be run
}
Consider the sample shown below of a loop that begins with $x = 2. The loop
will continue being executed as long as the value for $x equals or is less than
4. An increment of 1 will be added to $x for each time the loop is executed.
<?php
$i = 1;
while($i<= 3){
$i++;
echo "The number is " . $i . "<br>";
}
?>
Consider another example. In this case, a variable value is decreased with
each iteration of a loop while the counter is increased until it gets to 15 when
the evaluation is given to be false and the loop terminates.
<html>
<body>
<?php
$a = 0;
$num = 30;
</body>
</html>
The outcome of executing this script is shown in the result below:
Loop stopped at a = 15 and num = 30
The for Loop:
The for Loop is used in repeating a particular set of code for the duration in
which a specific condition is reached. It is usually used when there is a need
to run a block of code over a certain amount of times. In the for loop, the
initializer is applied as a means of setting up the start value for the counter of
the number of loop iterations. For this reason, a variable can be declared at
this point, and it is only normal to term it $i.
Syntax:
for(initialization; condition; increment){
// Code to be run
}
In for loops, there are a variety of parameters. They include:
Initialization:
As the name implies, it is used in initializing all counter variables and is
unconditionally evaluated before the initial running of the entire body of the
loop.
Condition:
At the start of every iteration process, the condition is processed. If it is
evaluated as true, then the loop goes on, and all the nested statements will be
executed. However, should it evaluate as false, the loop execution is stopped.
Increment:
The increment is used in updating the loop counter with a new value after
each iteration. The increment is processed at the end of every iteration
process.
Sample:
The example shown below outputs up to five iterations and alters the given
value of two variables after each cycle of the loop.
<html>
<body>
<?php
$x = 0;
$y = 0;
</body>
</html>
do {
$x++;
}
while( $x < 15 );
echo ("Loop stopped at x = $x" );
?>
</body>
</html>
The result that will be produced from the execution of this script is as
follows:
Loop terminated at x = 15
The Distinction Between do…while and do loops:
For the while loop, the main distinction from the do…while loop exists in
how execution is carried out. In the while loop, the expression being
evaluated is processed at the start of every loop iteration. As a result, when an
expression is evaluated as false, no execution whatsoever will be made. For
the do…while loop, on the other hand, execution will be made right away on
the loop even when the conditional expression evaluates as false. And since
the condition is being evaluated at the terminal point of the loop iteration
instead of the starting.
<?php
$array = array( 5, 6, 7, 8, 9);
</body>
</html>
The result of executing this script is as follows:
Answer is 5
Answer is 6
Answer is 7
Answer is 8
Answer is 9
There are other statements in PHP also. They are:
The Break Statement:
In PHP, the break statement is applied in prematurely terminating the
execution of loops. For better functionality, the break statement is added
within a statement block. Doing this accords you absolute control for
whenever you deem necessary to leave the loop and break out. Once you
have successfully left the loop, the statement directly next to the loop begins
to run.
Sample:
In the sample condition shown below, the test evaluates as true whenever the
counter values attain a value of 5, and the loop is cancelled.
<html>
<body>
<?php
$x = 0;
</body>
</html>
When the script is executed, the result outputted will be as follows:
Loop stopped at x = 5
<?php
$array = array( 5, 6, 7, 8, 9);
// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
In this case, the key could either be a string of integer while the value could
attain any form.
In addition, the following vital casts tend to happen:
1. Strings that hold valid decimal integers, except in cases where a +
sign precedes the number, are cast to the integer type. Take, for
instance, the key "5" can be started in 5. On the other hand, it is
impossible to cast "08" because it doesn't exist in a valid decimal
state.
2. Floats can also be cast to integers, meaning that it is possible for
even a fractional part to undergo truncation. For example, the key
5.7 can be stored under 5.
3. Booleans can also be cast to integers, as well. That is, the key true
can be stored under 1, even when it is false under 0.
4. Null can be cast to an empty string. That is, the main null can be
stored as "".
5. Objects and arrays cannot be applied as keys because doing so only
triggers a warning of some illegal offset type.
6. Many different elements in a single array declaration tend to make
use of a similar key, and only the last would survive typically
because others get overwritten in the process.
Types of Arrays:
In PHP, there are three varying types of arrays, and for each array, a value is
accessed with an ID that is known as an array index. The types of arrays are
discussed below:
Numeric array:
A numeric array is one that has a numeric index. The values can be stored
and accessed in a linear manner. Numeric arrays are capable of storing
strings, numbers, and objects, however, their indexes are always represented
with numbers. And by default, every numerical array index begins from the
number zero.
Sample:
The sample being considered here shows how to create a numeric array and
access it. Here, the array() function is used in the creation process.
<html>
<body>
<?php
/* First method of creating an array. */
$digits = array( 5, 6, 7, 8, 9);
Associative Arrays:
Associative arrays are arrays that have strings as their indexes. They are
capable of storing the values of elements in conjunction with critical values
instead of in a direct linear index fashion. An associative array is quite
synonymous to a numerical array in that that their functionalities are similar,
although disparities do exist in the way their indexes are represented. For
associative arrays, their indexes are typically represented as a string so that it
is possible to establish a strong sense of connection between the keys and
values. Take, for instance, when storing the wages of workers in an array, an
array with a numerical index wouldn't appear to be the finest choice in this
instance. Instead, it is more plausible to make use of the names of the
workers as the keys in an associative array, and the resulting value turns out
as the respective wages of the workers.
Keep in mind to not keep an associative array within a double quote during
printing; otherwise, no value whatsoever would be returned.
Sample:
<html>
<body>
<?php
/* First method to associate create array. */
$wages = array("kaleb" => 3000, "karen" => 1500, "tara" => 700);
echo "Wages of kaleb is ". $wages['kaleb'] . "<br />";
echo "Wages of karen is ". $wages['karen']. "<br />";
echo "Wages of tara is ". $wages[tara]. "<br />";
</body>
</html>
When the script is executed, the result that produced is as follows:
Wages of kaleb is 2000
Wages of karen is 1000
Wages of tara is 500
Wages of kaleb is high
Wages of karen is medium
Wages of tara is low
Multi-dimensional Arrays:
A multi-dimensional array is an array that comprises of one or more values
and arrays which can be accessed with a variety of indexes. In a multi-
dimensional array, every element contained by the main array can also be an
array of its own. Also, every element contained by the sub-array can be
arrays in themselves, among other things. The values evaluated by a multi-
dimensional array can be accessed via multiple indexes.
Sample:
In the sample shown below, a two-dimensional array is created to store the
marks obtained by three students in a test comprising of three subjects. The
sample follows the outline of an associative array and a numeric array can be
created similarly.
<html>
<body>
<?php
$scores = array(
"kaleb" => array (
"english" => 40,
"biology" => 45,
"agric" => 31
),
</body>
</html>
When this script is executed, the result produced takes after this fashion:
Scores for kaleb in english : 40
Scores for karen in biology : 42
Scores for tara in agric : 37
Exercise 9:
1. How can the values of a multi-dimensional array be accessed?
2. What are the three types of arrays in PHP?
3. What is the key distinction between numeric and associative arrays?
4. What form of arrays can be accessed with many different indexes?
5. How are the values of a numeric array stored and accessed?
6. Strings are associated with which form of arrays?
7. What is the default number that begins the index of a numerical
array?
8. Why is it essential to not enclose associative arrays between double
quotes when printing?
9. How can the values of a multi-dimensional array be accessed?
10. What is a map?
Chapter Ten
Strings in PHP
In PHP, a string refers to a set of arithmetic values, special characters,
numbers, and letters or sometimes, a combination of every one of them. The
simplest method used in creating strings involves enclosing a string literal,
which refers to the characters in a string, between two single quotation marks
('). Consider the syntax below:
$my_string = 'Hello World';
It is also possible to use double quotation marks ("). Albeit how double and
single quotation marks are used differ. Strings encased in single quotes are
used in an almost literal way, while the strings encased in double-quotes are
used to replace the variables with a string representation of their values and
specially translating a variety of escape sequences. The escape-sequence
replacements used usually include the following:
\\ is replaced using a single backlash (\)
\n is replaced using the newline character
\" is replaced using the single, double quote (")
\r is replaced using the carriage-return character
\$ is replaced using the dollar sign alone ($)
\t is replaced using the tab character
Consider the sample shown below of a valid string:
print($lyrics);
print "<br />";
print($lyrics);
?>
When executed, the result of the codes takes after this fashion:
My $output will not print!\n
My song will print!\n
Manipulating Strings in PHP:
There are lots of built-in functions in PHP that are used in string
manipulation activities, such as finding characters or substrings, taking a
string apart, calculating a string length, replacing a certain fraction of a string
using various characters, among others. Below are some of the functions
manipulation of strings in PHP:
Length of Strings:
There are no defined limits to which the length of a string can be, as such,
you have to be able to create arbitrarily long strings that fit the bounds of the
memory available to you. Strings with double quotes (such as "this") undergo
preprocessing in the following ways:
1. Some character sequences that start with a backslash (\) are swapped
out and replaced using special characters.
2. Variable names (like those beginning with $) are replaced using the
string representations of their values.
<?php
$string4="Hey there!";
$string5="abcd";
echo $string4 . " " . $string5;
?>
When this script is executed, the result is as follows:
Hello there! Abcd
When we take an in-depth look at how the sample shown above works, it can
be seen that the concatenation operator is used multiple times (two precisely).
The reason being that a third-string was added into the fray. An empty space
was used to separate the two variables, and a string containing a single
character was introduced between the two string variables.
Exercise 10:
1. What case-sensitive function is used for binary-safe comparisons
between two strings?
2. What is the strstr() function used for?
3. What operator is used in the concatenation of two strings variables?
4. What is the use of the strlen() function in PHP?
5. How are strings with single quotes treated in PHP?
6. What are strings?
7. What are the two types of quoted strings?
8. What function is used in repeating a string for a given amount of
times?
9. How does the function printf() differ from the print() function?
10. To remove PHP and HTML tags from a string, what function
is used?
Chapter Eleven
Functions in PHP
Functions in PHP are almost no different from those in other programming
languages. Functions refer to the pieces of code which takes in inputs, usually
in the form of parameters, processes and returns values. By now, you are
quite familiar with many different functions in PHP like those used in string
operations. Those functions are the built-in functions of the PHP
programming language; however, you can make a function of your own, too.
Although it is somewhat unnecessary to bother creating functions of your
own, especially as PHP doesn't exactly lack in functions of its own, there are
lots of built-in library functions with various applications suitable for use at
your beck and call.
How Functions Work:
1. Functions are blocks of code which can be applied at any point in a
program, and repeatedly too.
2. Functions will not automatically run when a program is initiated.
3. Functions are only executed when they are called in a program.
<head>
<title>Coding in PHP</title>
</head>
<body>
<?php
/* Defining the PHP Function */
function noteWriter() {
echo "It is a fine day today. Have a great day ahead!";
}
The opening curly brace is an indication of the starting of the function code,
while the closing curly brace is used to indicate the terminal point of the
function. The function prints "Welcome to PHP." To access the function, all
we need do is write it out (or call it) and attach brackets () to it:
<?php
function noteWriter() {
echo "Welcome to PHP!";
}
matricNumber("131");
matricNumber ("132");
matricNumber ("133");
matricNumber ("134");
matricNumber ("135");
?>
Passing Arguments Through Reference:
Passing arguments to functions through reference is a possible argument
operation. In the process, a function manipulates the reference of a variable
instead of a copy of the value assigned to the variable. As a result, alterations
made to the argument in such a case modifies the value of the first variable.
An argument can be passed by reference through the inclusion of an
ampersand into a variable name in either the function definition or function
call.
Take a look at the sample shown below for a better understanding of both
cases:
<html>
<head>
<title>Passing Argument through Reference</title>
</head>
<body>
<?php
function addTen($num) {
$num += 10;
}
function addFifteen(&$num) {
$num += 15;
}
$initnum = 20;
add10( $initnum );
addFifteen( $initnum );
echo "Initial Value is $initnum<br />";
?>
</body>
</html>
When the code is executed, the result outputted is as follows:
Initial Value is 30
Initial Value is 35
Default Argument Values in PHP:
The sample shown below depicts how default parameters are used in PHP.
When the function setLength() is called without any arguments, it assumes a
default value as an argument:
Sample
<?php declare(strict_types=5); // strict requirement
function setLength(int $minlength = 25) {
echo "The length is : $minlength<br>";
}
setLength (100);
setLength (); // will use the default value of 25
setLength (150);
setLength (75);
?>
Functions with Parameters in PHP:
In PHP, you are given the option to pass parameters within a function. Like
arguments, many different parameters can be passed at the same time. The
parameters function similarly as variables within the function. Take a look at
the sample below between two integer parameters that are added and then
printed out:
<html>
<head>
<title>Functions with Parameters in PHP</title>
</head>
<body>
<?php
function addFunction($num5, $num10) {
$sum = $num5 + $num10;
echo "Sum of the both numbers is : $ans";
}
addFunction(30, 50);
?>
</body>
</html>
When executed, the result of the sample code above is as follows:
Sum of both numbers is: 80
<head>
<title>Coding Functions in PHP that return values</title>
</head>
<body>
<?php
function addFunction($num5, $num6) {
$add = $num5 + $num6;
return $add;
}
$return_value = addFunction(15, 25);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
When the code is executed, the result returned will take after this fashion:
Returned value from the function : 40
printIt("This is a test");
printIt();
?>
</body>
</html>
When the code is executed, the returned value will be as follows:
This is a test
Dynamic Function Calls:
Assigning function names to variables and strings is a fairly common and
possible activity in function operations. In this case, though, the variables are
regarded in the same manner as the function name would itself. The sample
shown below clearly depicts how this occurs:
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function offerGreetings() {
echo "Hi!<br />";
}
$function_holder = "offerGreetings";
$function_holder();
?>
</body>
</html>
When this sample code is executed, the outputted result will be:
Hi!
PHP Return Type Declarations:
The type declaration for the "return" statement is supported in PHP 7. In the
same vein as the type declaration for function arguments, introducing the
strict requirement declaration throws a "Fatal Error" statement whenever a
type mismatch occurs. A colon (:) is applied any time the type for a function
return is declared, and the type follows directly after, but just before the
opening curly braces ({) when a function is declared. In the sample shown
below, the return type specified for the function is specified.
Sample:
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $i, float $j) : float {
return $i + $j;
}
echo addNumbers(1.5, 7.2);
?>
It is possible for a different return type to be specified instead of the argument
types. However, ensure that the return is right type:
Sample:
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $i, float $j) : int {
return (int)($i + $j);
}
echo addNumbers(1.5, 7.2);
?>
Exercise 11:
1. How does a return keyword work?
2. When a type mismatch occurs in a block of code with a strict
requirement declaration, what happens?
3. Why are default values assigned to parameters?
4. How can an argument be passed by reference?
5. What is a function?
6. What is the naming rule and convention for function names in PHP?
7. What is an argument, and what does it do?
8. When was type declarations introduced, and what do they do?
9. For smoother execution and better readability, how are multiple
arguments separated in PHP?
10. What is the meaning of an opening and closing curly braces in
function operations?
Chapter Twelve
Files in PHP
In PHP, files refer to webpages which hold Hypertext Pre-processor (PHP)
codes. These files could contain PHP functions which are capable of
processing online forms, accessing data from a database, or obtaining time
and date. The PHP engine located in web servers is responsible for parsing or
processing the PHP code found in the webpage, thus resulting in the dynamic
generation of HTML. Keep in mind that content of the webpage is contained
in the HTML, and it is it (the HTML) that is forwarded to the web browsers
of users. As a result, users are seldom ever aware of the real PHP codes that
webpages hold, even when the page sources are viewed.
Any time the web browsers of users require directories from PHP-enabled
web servers, the file loaded by default is usually the index.php file. Take for
instance, when a sample page http://myexample.org/ is requested, the page
that is loaded is usually http://myexample.org/index.php
Should any attempt to open a file fail, then the fopen() function returns the
value false; otherwise, a file pointer is returned to be used for writing or
reading the said file even further. Once changes have been made to an opened
file, the fclose() function must be applied to close it. A file pointer is required
to serve as an argument for the fclose() function. In turn, it returns as true
once the closure is successful, and false when it doesn't.
How to read a file in PHP:
Once the fopen() function is applied to open a file, the fread() function can be
applied to read the file. In both cases, it has to be both the length of the file
shown in bytes, and the file pointer itself. The length of the files can be
discovered by making use of the filesize() function that uses the name of the
file for an argument, returning the size of the file as an expression in bytes.
Outlined below are some step necessary for reading a file in PHP:
Use the fopen() function to open the file.
Obtain the length of the file with the filesize() function.
Use the fread() to read the content of the file.
Finally, use the fclose() function to close the file.
The sample shown below is of a variable assigned to the content of a text file
which then portrays the contents on the web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );
</body>
</html>
When the code is executed, the result that will be outputted will be as
follows:
File size: 278 bytes
The PHP Hypertext Pre-processor (PHP) is a programming language that
enables web developers to design dynamic content which is capable of
interacting with databases.
PHP is used in the development of web-based software applications. This
tutorial helps you to create a base using PHP.
How to write a file in PHP:
It is possible to write a new file in PHP, and a text can also be appended into
an already existing one through the fwrite() function in PHP. The function
needs about two arguments that specify a string of data that should be written
and an agile pointer. As an alternative, a third integer argument, but it can be
introduced into the fray to express the length of the data to be written. When
the third argument is introduced, writing is terminated once the given length
has been attained.
Consider the sample shown below, which creates a new text file that
introduced a brief text header within it. Once this file has been successfully
closed, the file_exist() function is called to confirm its existence and take the
file name as an argument:
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
<head>
<title>Writing a file using PHP codes</title>
</head>
<body>
<?php
$filename = "phpfile.txt";
$file = fopen( $filename, "r" );
fclose( $file );
</body>
</html>
When the code is executed, the result outputted is as follows:
File size: 23 bytes
This is a sample code
file name: phpfile.txt
File System Functions:
File system functions are applied for use in accessing and manipulating file
systems in PHP that are provided to equip users with every possible function
necessary for file manipulation.
Installation:
The logging and error functions form an integral aspect of the core in PHP.
As a result, these functions don't require any form of installation to work.
Exercise 12:
1. Describe the process of generating HTML with PHP code.
2. What is the function of the fwrite() function in PHP?
3. How is the length of a file identified in PHP?
4. What is anindex.php file?
5. What happens when opening a file is unsuccessful?
6. What is the purpose of file system functions?
7. What is the function of a file_exist function in a script?
8. What function is used in opening a PHP file?
9. What serves as an argument of the fclose() function?
10. What are files?
Chapter Thirteen
Web Concepts in PHP
Web concepts are merely the demonstration of how PHP is capable of
providing dynamic content based on browser type, user input, and randomly
created numbers.
Identifying platforms and browsers:
Important environment variables are created by PHP and can be found on the
page phpinfo.php, which is used in the setting up of PHP environments.
HTTP_USER_AGENT is one of the many environment variables set by PHP
to identify the operating system and browser of a user. Furthermore, the
getenv() function is provided by PHP for gaining access to the values of
every environment variable. The data held by the HTTP_USER_AGENT
environment variable can be applied in the creation of dynamic content
suitable to the browser. The sample shown below is a demonstration of how
both the operating system and browser of a client can be identified.
<html>
<body>
<?php
function getBrowser() {
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version = "";
// now try it
$ua = getBrowser();
$yourbrowser = "Your browser: " . $ua['name'] . " " . $ua['version'] .
" on " .$ua['platform'] . " reports: <br>" . $ua['userAgent'];
print_r($yourbrowser);
?>
</body>
</html>
When the sample code is executed, many results may be produced depending
on your computer, operating system, browser, among others. The result that
produced is as follows:
Your browser: Google Chrome 54.0.2840.99 on windows reports:
Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko)
Chrome/54.0.2840.99 Safari/537.36
<?php
srand( microtime() * 1000000 );
$num = rand( 1, 4 );
switch( $num ) {
case 1: $image_file = "/php/images/logo.png";
break;
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
The result outputted will be as follows:
Name:
Age:
Submit
The default variable $_PHP_SELF in PHP can be used as the name of a PHP
script. And on clicking on the submit button, the same script in PHP is called
to produce a similar result.
The method "POST" can be used in posting the data of users onto the server
scripts. In posting data onto a server script, there are two main methods used.
Browser Redirection:
The function header() in PHP works to supply a browser with raw HTTP
headers, and can also be applied in redirecting it to other locations. To avoid
the loading of other parts of a page; the redirection script must be placed at
the topmost area of the page. "Location" is used to specify the target, while
header serves as the argument assigned to the function header(). After once
the function has been called, the exit() function is applied in pausing the
processing of the remainder of the code. The sample shown below contains a
demonstration of how a browser request can be redirected to other web pages.
Try your hands at this test sample by placing the source code into a test.php
script.
<?php
if( $_POST["location"] ) {
$location = $_POST["location"];
header( "Location:$location" );
exit();
}
?>
<html>
<body>
</select>
<input type = "submit" />
</form>
</body>
</html>
Exercise 13:
name1=value1&name2=value2&name3=value3
Spaces are usually eliminated and replaced using the + character, and all
other non-alphanumeric characters are swapped out for hexadecimal values.
And once the information has been successfully encoded, it is transmitted
directly into the server.
This method is used for requesting data from a given resource. For the GET
method, the data is forwarded in URL parameters which are typically strings
of value and name pairs separated using ampersands (&). On a general note, a
URL containing GET data tends to take after this fashion:
Sample :
http://www.example.com/action.php?name=Jerry&height=5" 5
Rationale :
In the URL, the bold part represents the GET parameters, while the italic
parts represent the values assigned to those parameters.
More than a single parameter can be embedded in an URL through
concatenation using ampersands (&).
In the GET method, one is only capable of sending simple text data.
Input :
<?php
if( $_GET["name"] || $_GET["weight"] ) {
echo "Welcome ". $_GET['height']. "<br />";
echo "You are ". $_GET['height']. " cms in height.";
exit();
}
?>
<html>
<body>
</body>
</html>
The GET method creates a long string which can be found in the
server logs of the Location: box of the browser.
Keep in mind to not make use of a GET method anytime you have a
password or other high precedence data to be sent into a server.
1. Given as the data sent through the GET method is displayed in the
URL, bookmarking the page using a specified query string values is
entirely possible.
2. It is also possible to cache GET requests and GET requests tend to
stay in the browser's history.
3. It is also possible to bookmark GET requests.
The post method is used in submitting the data to be parsed into a given
resource. For the POST method, information is transferred through HTTP
headers. The information is encoded in a similar way to the encoding process
for the GET method, and then it is placed into a header known as
QUERY_STRING. For POST method, the data is forwarded to the server in
the form of a package contained in clear communication with a processing
script. The data forwarded through the POST method tends to be invisible in
the URL.
Sample :
POST /test/demo_form.php HTTP/1.1
Host: gfs.com
JIM=350&DEC=43
Rationale:
The query string (me/height) is forwarded into the body of the HTTP
message of a POST request.
Input :
<?php
if( $_POST["name"] || $_POST["weight"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['weight']. "kgs in weight.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Weight: <input type = "text" name = "weight" />
<input type = "submit" />
</form>
</body>
</html>
Output :
The POST method has no restrictions whatsoever regarding the size of the
data to be sent.
It is possible to use the POST method in sending binary data, as well as
ASCII.
The data forwarded using the POST method tends to go through the HTTP
header. As a result, security is dependent on the HTTP protocol. By making
use of Secure HTTP, you can ensure the safety and security of your
information.
PHP uses the POST method in providing $_POST associative array in
accessing every information sent.
Consider the sample shown below and try to place the source code into a
test.php script.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "Your ". $_POST[‘mobile number']. " is.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Mobile number: <input type = "text" name = "mobile number" />
<input type = "submit" />
</form>
</body>
</html>
1. The POST method has a higher level of security than the GET
method as the information entered by the user is never shown in the
query string of the URL or the logs of the server.
2. POST method has a much larger boundary for the amount of data
which can be passed at a time, and a user can easily forward binary
data (uploading a file or image) and text data.
1. Since the data forwarded through the POST method is not displayed
in the URL, it is impossible to bookmark the page under any given
query.
2. Also, the requests of POST methods do not get cached.
3. The requests of POST methods are not saved in the browser's
history, so it has no logs.
</body>
</html>
In the sample shown above, the variable $_PHP_SELF holds the name of the
self script within which it is called. As a result, the result produced is as
follows:
Name:
Height:
Submit
Exercise 14:
1. In terms of security, how is the POST method better than the GET
method?
2. What method can have its request bookmarked?
3. How does HTTP work?
Chapter Fifteen
File Inclusion in PHP
It is possible to add the content of a PHP file into another file before
processing it with a server. In general, two types of PHP functions can be
applied in adding a PHP file into a second PHP file. They are:
The require() function; and
The include() function
</body>
</html>
When the script is processed, the result obtained is as follows:
This is a sample to demonstrate how an incorrect PHP file can be included!
Having done that, let’s try out the same sample using the require() function
this time:
<html>
<body>
</body>
</html>
When the file is processed in this case, it draws to a halt, and nothing is
outputted.
Keep in mind that there is a tendency of fatal error or plain warning messages
to be reported. In some cases, nothing even. Everything all boils down to the
set-up of your PHP server.
Exercise 15:
1. What function takes all texts contained in a file and copies them to a
file with an include() function?
2. What is the purpose of the include() function?
Chapter Sixteen
Coding Standards and Conventions in PHP
For every organization, there is a specific standard of coding that is in line
with what they consider to be their best practices. Coding standards and
conventions are necessary since many developers may sometimes be working
on diverse modules. And should they begin developing standards of their
own, the source becomes quite difficult to manage indeed, and managing
source codes in coming times becomes difficult, if not impossible altogether.
Below are many different rationales behind the use of coding standards and
conventions:
In PHP, there are specific standards that ought to be followed when coding.
They are including but not limited to the following:
Control Structures:
Control structures are made up of while, if, switch, for, among others. When
coding, control statements should be written with a space between the
opening parenthesis and the control keyword. The reason for this is to
differentiate control keywords from function calls. It is strongly advised to
use curly braces at all times, even in conditions where they see technically
optional.
Samples:
if ((condition1) || (condition2)) {
action1;
}elseif ((condition3) && (condition4)) {
action2;
}else {
default action;
}
It is possible to write switch statements in the manner shown below:
switch (condition) {
case 1:
action1;
break;
case 2:
action2;
break;
default:
defaultaction;
break;
}
Function Calls:
Functions ought to be called without any space placed between the name of
the function, the first parameter, and the opening parenthesis. Also, there
ought to be spaces between each parameter and ensuing commas, and no
space used between the final parameter, a semicolon, and the closing
parenthesis. Consider the sample shown below:
$var = foo($open, $close, $value);
Function Definitions:
Function declarations are usually tailored according to the BSD/Allman style.
function fooFunction($arg1, $arg2 = '') {
if (condition) {
statement;
}
return $val;
}
Comments:
Standard C++ comments (//) and C-styled comments (/* */) are not a
problem. However, making use of shell-styled or Perl comments (#) is
drowned upon.
Variable names:
Exercise 16:
1. What is the function of "g" in a code?
2. What is the coding standard and convention for writing function
calls?
3. What is the ideology behind the concept of coding standard for
control structures?
4. What is the reason behind the development of coding standards and
conventions?
5. What is the recommended character length per line for good
readability?
Chapter Seventeen
Cookies in PHP
Cookies refer to text files that are stored on the computer of a client and are
kept to track use. PHP readily supports HTTP cookies. In identifying
returning users, there are three methods involved. They include the
following:
In this section, you learn the basics of setting cookies, gaining access to them,
and the how's of deleting them.
The Basics of a Cookie:
Cookies are typically built in an HTTP header, even though it is possible to
set up a cookie on a browser directly in JavaScript. A PHP script that
develops a cookie forward headers which look something of the following:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
Access to the cookie can then be made possible to a PHP script through the
environmental variable $_COOKIE, and $HTTP_COOKIE_VARS[] that
contains all the values and names of cookies. Above, it is possible to reach
cookies with the use of $HTTP_COOKIE_VARS["name"].
Value:
The value variable is used in setting up the value of a named variable and
represents the content that is being stored.
Expiry:
The expiry variable is used in specifying a future period in seconds as
00:00:00 GMT+1 on 1st Jan 1963. After this period, the cookie attains a state
of inaccessibility. If expiry parameter isn't already set by the time, then the
cookie expires automatically anytime the web browser is terminated.
Path:
The path variable is used in specifying the directories in which a cookie has
validity. A solo forward-slash (/) character enables the cookie to maintain
validity across every directory.
Domain:
The domain variable is used in specifying the domain name of large domains
and has to have a minimum of two periods to be considered valid. Every
cookie only exhibits validity towards the domain and host in which they were
created.
Security:
It's possible to set the security variable to 1 and specify that a cookie ought to
be forwarded only through secure transmission by HTTPS. Otherwise, it is
set to 0, which implies that the cookie could be transferred through regular
HTTP.
Going with the sample shown below will lead to the formation of two
cookies; name and department. Both cookies have a validity period of an
hour (3600 seconds) after which they are expired.
<?php
setcookie("name", "Jane Doe", time()+3600, "/","", 0);
setcookie("department", "English", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
Gaining access to Cookies using PHP:
In PHP, there are many different ways in which cookies can be accessed. The
simplest method is usually done through the use of either
$HTTP_COOKIE_VARS or $_COOKIE variables. Proceeding with the
sample shown below grants access to every cookie that is set in the sample
shown above:
<html>
<head>
<title>Gaining Access to Cookies using PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["department"] . "<br />";
?>
</body>
</html>
To check the status of the cookie; whether or not it is set, the isset() function
is applied:
<html>
<head>
<title>Gaining Access to Cookies using PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome, " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Name not recognized" . "<br />";
?>
</body>
</html>
<head>
<title>Deleting Cookies in PHP</title>
</head>
<body>
<?php echo "Cookies Deleted" ?>
</body>
</html>
Exercise 17:
Exercise 2:
1. Windows servers are quite expensive to set up.
2. The system is up to date.
3. phpmyadmin makes setting up and altering your database easier and
faster.
4. XAMPP.
5. It means the language can be applied in managing databases,
dynamic content, and session tracking, as well as being used in the
building and designing of e-commerce sites.
6. PHP supports major protocols used in programming, like the LDAP,
IMAP, AND POP3.
7. A parser is used in generating HTML outputs that can be sent to a
web browser.
8. PHP has lots of integration with a variety of popular databases, such
as Microsoft SQL Server, MySQL, Oracle, Informix, PostgreSQL,
and Sybase.
9. PHP parser, web server, and database.
10. It works in gathering the data from files, saving the data to
files, forwarding data through emails, and returning data to a user.
Exercise 3:
1. A semicolon is used in terminating a statement in PHP.
2. Tokens refer to the smallest, most indivisible building blocks that
make up a PHP program.
3. Comments are the parts of a program which are written for human
users and are cut out before the results of a program are outputted.
4. PHP interprets variables in different cases differently.
5. A series of valid statements in PHP represents a valid PHP program,
especially if it is enclosed in PHP tags.
6. The number of whitespace characters in a row is inconsequential
because a single whitespace character is seen the same way as many
whitespace characters in PHP.
7. Multi-line comments are used in introducing concise explanations or
pseudocode algorithms while coding.
8. First, pick the configuration option to enable short tags. Secondly, go
to the settings part of your php.ini file and click to turn on
short_open_tag.
9. It is used when a PHP parsing engine is required to distinguish
between other elements on a page and PHP codes.
10. Canonical PHP tags.
Exercise 4:
1. A variable scope is a term used to describe the range of availability
that a variable has in the program in which it is assigned.
2. Addition sign (+), subtraction sign (-), ampersand (&), Modulus (%),
and opening parenthesis (().
3. It means that with the value of memory available, a user should be
able to create as many arbitrarily long strings as possible.
4. Singly quoted strings are used in a literal manner; however, doubly
quoted strings take the place of variables and their values, even to
the point of specially interpreting some character sets.
5. In a Boolean context, it evaluates to FALSE.
6. FALSE and TRUE.
7. Base 8 or octal integers are indicated using a preceding zero (0).
8. Variables are used for storing information within the body of a PHP
program.
9. In a single string variable, the here document is used in assigning
multiple lines.
10. Integers are the most basic forms of variables in PHP, and
they are similar to basic mathematical whole numbers in that they
can be either negative or positive.
Exercise 5:
1. Only scalar data, such as strings, floats, integers, and Boolean, can
only be stored in constants.
2. When applied within an included file, it returns the name of the
included file.
3. The name of a constant ought, to begin with, an underscore or a
letter which is quickly succeeded by any amount of underscores,
numbers, or letters.
4. The constant() function outputs the value assigned to the constant.
5. When a constant is defined, it cannot be undefined or changed
throughout the execution.
6. _LINE_, _CLASS_, _FUNCTION_, _FILE_, and _METHOD_.
7. Constants can’t be defined using mere assignment as they can only
be defined with the function—define().
8. Constants refer to the terms used in identifying simple values.
9. The constant() function is used when reading the value of a constant,
especially when you need to collect the name of the constant
dynamically.
10. The value of __LINE__ is depended on the line where it is
applied in a script.
Exercise 6:
1. Modulus (%).
2. Relational operators.
3. An operator is a construct used in performing operations between
several variables.
4. The precedence of operators dictates how terms are grouped in an
operation.
5. Binary operators are operators that require two operands to carry out
a series of logical and arithmetic operations.
6. The decrement operator is used to decrease the value of an integer by
one.
7. Higher precedence operators ought to first be evaluated in any
expression before lower precedence operators.
8. Ternary operators require three operands to be used and evaluate any
of the second or third operations depending on the outcome of the
first operation.
9. Assignment operator.
10. Addition (+) and subtraction (-).
Exercise 7:
1. Braces or parenthesis.
2. The elseif statement.
3. The else statement.
4. The alternative expression.
5. The statement is executed using any default code specified in the
program.
6. The if statement
7. Empty statements.
8. A statement-group is a group of statements.
9. When the expression evaluates into a value considered to be false by
the if statement
10. To avoid the repetitive use of if and elseif statements.
Exercise 8:
1. Loops are tools used in executing a single block of code over and
over, given that a particular condition is reached.
2. The foreach loop.
3. The for loop is used in repeating a particular set of code for the
duration a specific condition is reached.
4. Loops are used to introduce automation to repetitive actions in a
program as a way of saving energy and time.
Exercise 9:
1. The values evaluated by a multi-dimensional array can be accessed
via multiple indexes.
2. Numerical, multidimensional, and associative arrays.
3. The main difference is in the way their indexes are represented.
4. The multi-dimensional array.
5. The values of a numeric array are stored and accessed in a linear
manner.
6. The associative array.
7. By default, every numerical array index begins from the number
zero.
8. Using a double quote during printing would result in no value being
returned.
9. The values evaluated by a multi-dimensional array can be accessed
via multiple indexes.
10. A map is a data type that links values to keys and can be
optimized for many different reasons.
Exercise 10:
1. The strcmp() function.
2. It is used to locate the first appearance of a string within another
string. It is case-sensitive.
3. The dot (.) operator
4. It is used for calculating the number of characters found in a string,
including the blank spaces used within the string.
5. Strings with single quotes are treated literally.
6. Strings are a set of arithmetic values, special characters, numbers,
and letters or sometimes, a combination of every one of them.
7. Single-quoted and double-quoted strings
8. The str_repeat() function.
9. The printf() function is used in outputting formatted strings while the
print() function merely outputs a string.
10. The strip_tags() function.
Exercise 11:
1. It stops the execution of a function and sends the value to the code
that called the function.
2. The strict requirement declaration throws a “Fatal Error.”
3. So that when the program that calls the function is unable to execute,
parameters have a value to run with.
4. By the inclusion of an ampersand into the name of the variable in
either the function call or function definition
5. A function can be seen as a piece of code which takes in inputs,
usually in the form of parameters, processes and returns values.
6. All function names have to begin with an underscore or letter.
7. An argument is quite similar to a variable; however, it is usually
specified inside the parenthesis attached to the name of a function. It
is used in the transfer of information to functions in a code
8. Type declarations were introduced in PHP 7. It grants users the
ability to specify any expected data type while declaring a function,
and by introducing the “strict” declaration, a “Fatal Error” is thrown
in the occurrence of a mismatch in the data type.
9. Multiple arguments are separated using commas in PHP.
10. The opening curly braces is an indication of the starting of the
function code, while the closing curly brace is used to indicate the
terminal point of the function.
Exercise 12:
1. The PHP engine located in web servers parses or processes PHP
codes in webpages, resulting in the dynamic generation of HTML.
2. The fwrite() function makes it possible to write a new file in PHP, as
well as to append a text into an already existing one.
3. The length of the files can be discovered by use of the function
filesize() which uses the name of the file as an argument and returns
the size of the file as an expression in bytes.
4. An index.php file is a file loaded by default any time the web
browsers of a user request for directories from PHP-enabled web
servers.
5. The fopen function returns the value FALSE.
6. File system functions are used in accessing and manipulating the file
systems provided to equip users with every possible function
necessary for file manipulation.
7. The file_exist() function is used to confirm the existence of a file and
take the file name as an argument.
8. The fopen() function.
9. A file pointer.
10. Files are webpages that contain Hypertext Pre-processor
(PHP) codes.
Exercise 13:
1. The function header() in PHP is used in redirecting a browser to
other locations.
2. The function rand() is used in the generation of random numbers
within a specific range.
3. HTTP_USER_AGENT is used to identify the operating system and
browser of users.
4. Web concepts are the demonstration of how PHP is capable of
providing dynamic content based on browser type, user input, and
randomly created numbers.
5. To avoid the loading of other parts of a page the redirection script
must be placed at the top area of the page.
Exercise 14:
1. The POST method has a higher level of security than the GET
method because the information entered by the user is never shown
in the query string of the URL or the logs of the server.
2. The GET method.
3. HTTP serves as a protocol of request and response between the
server and clients.
Exercise 15:
1. The require() function.
2. It is used in taking all the texts contained in a selected file and
copying it into a file that the include function is applied in.
Exercise 16:
1. “g” is used to prepend the global variables within a code.
2. Functions ought to be called without spaces between the name of the
function, the first parameter, and the opening parenthesis.
3. The reason is so that control keywords can be differentiated from
function calls.
4. For easier management of source codes.
5. 75 to 85.
Exercise 17:
1. The generally accepted method of deleting cookies involves calling
the setcookie() function using just the name argument.
2. Gaining access to cookies with PHP.
3. The path variable.
4. In the expires field.
5. Tracking client usage.
By
Computer Programming Academy
Table of Contents
Introduction
Chapter One
Overview of C++
History of C++
C++ Theory
Standardization
Language
Storing Objects
Formats or Templates
Objects
Encapsulation
Inheritance
Operators
Polymorphism
Virtual Member Functions
Conclusion
What is C++
Object-Oriented Programming
Standard Libraries
Learning C++
Utilization of C++
Advantages of C++ over C Language
Exercise 1:
Chapter Two
Variables
Kinds of variables
Types Of Variables Dependent On Their Degree Or Scope
Can Global And Local Factors Have The Same Name in C++?
Exercise 2:
Chapter Three
Knowing Databases
An Overview
Database Connectivity utilizing C++
Executing a basic SQL Command
Exercise 3:
Chapter Four
Syntax
C++ Identifiers
C++ Keywords
Whitespace in C++
Exercise 4:
Chapter Five
Data Types
Crude Data Types:
Derived Data Types:
User-Defined or Abstract Data Types in C++:
Datatype Modifiers
Data Type Size (in bytes) Range
Exercise 5:
Chapter Six
Constants or Literals
Characterizing Constants:
Sorts of Literals in C++ with Examples
Exercise 6:
Chapter Seven
Operators
Operators In C++
Kinds Of Operators In C++
Logical Operators
Relational Operators
Bitwise Operators
Assignment Operators
Other Operators
Exercise 7:
Chapter Eight
Loop Constructs in C++
Loops In C++
Do While Loop
Break And Continue Statements
Infinite Loop
Exercise 8:
Chapter Nine
Decision Making
Decision-Making Constructs In C++
Exercise 9:
Chapter Ten
Numbers
Characterizing Numbers in C++
Math Operations in C++
C++ Program To Add Two Numbers Utilizing Function Overloading
Addition Utilizing Class and Function
Complex Numbers in C++
Exercise 10:
Chapter Eleven
Arrays in C++
Arrays
Perks of an Array in C++
Hindrances of an Array in C++
Realities about Array in C/C++
Arrays versus Pointers
What is a Vector in C++?
Vectors in C++ STL
Iterators
Exercise 11:
Chapter Twelve
Strings
std:: String versus Character Array
Activities on strings
Iterator Functions/Capacity
Manipulating Functions/Capacity
String Class And Its Applications In C++
Applications
String and Character Array
Some Valuable String Functions
Different Ways to Create an Array of Strings in C++
Exercise 12:
Answers
Conclusion
Introduction
One of the upsides of technological advancement is that by inputting a few
lines of command, often called codes; you can build helpful websites and
other aspects of technology. And it is beautiful that you are interested in
coding, and you would love to learn C++ programming language.
Many newbies, when it comes to this programming language, are often
scared when they start, but as they progress, they learn, and it becomes easier
for them. So, do not worry, you will get the hang of it soon.
Resource materials are also helpful for accelerating your growth when it
comes to proficiency in the programming language. With this in mind, this
book was written to serve as a guide.
For you to successfully make use of the book, ensure that you have a laptop
or computer with you. This is because examples which you should use as
practice exercises have been provided in every chapter of the book to help
you learn better.
Enjoy.
Chapter One
Overview of C++
History of C++
In 1979, Bjarne Stroustrup, a Danish PC researcher, decided to take a shot at
"C with Classes," the ancestor to C++. The inspiration for making another
language began from Stroustrup's involvement with programming for his
Ph.D. paper. Stroustrup found that Simula had highlights that were
exceptionally useful for huge programming advancement. However, the
language was unreasonably slow for practical use, while BCPL was quick yet
too low-level to be appropriate for huge programming improvement. When
Stroustrup began working in AT&T Bell Labs, he had the issue of dissecting
the UNIX piece as for conveyed registering. Recollecting his Ph.D.
experience, Stroustrup set out to upgrade the C language with Simula-like
features. C was picked because it was broadly useful, quick, convenient, and
generally utilized. Just as C and Simula's persuasions, different languages
additionally affected this new language, including ALGOL 68, Ada, CLU,
and ML.
At first, Stroustrup's "C with Classes" added highlights to the C compiler,
Cpre, including classes, determined classes, solid composing, inlining, and
default arguments.
In 1982, Stroustrup began to build up a successor to C with Classes, which he
named "C++" (++ being the augmentation administrator in C) in the wake of
experiencing a few different names. New highlights were included, including
virtual capacities, work name, and administrator over-burdening, references,
constants, type-safe free-store memory portion (new/erase), improved type
checking, and BCPL style single-line remarks with two forward slices (//).
Besides, Stroustrup built up another, independent compiler for C++, Cfront.
In 1985, the main version of The C++ Programming Language was
discharged, which turned into the complete reference for the language, as
there was not yet an authorized standard. The principal business execution of
C++ was discharged in October of the equivalent year.
In 1989, C++ 2.0 was discharged, trailed by the refreshed second release of
The C++ Programming Language in 1991. New highlights in 2.0
incorporated various legacy, theoretical classes, static part works, const part
works, and ensured individuals. The Annotated C++ Reference Manual was
distributed in 1990, becoming the reason for the future standard. Later
component augmentations included formats, exemptions, namespaces, new
throws, and a Boolean kind.
In 1998, C++98 was discharged, institutionalizing the language, and a minor
update was discharged in 2003.
After C++98, C++ generally advanced gradually until, in 2011, the C++11
standard was discharged, including various new highlights, augmenting the
standard library further, and giving more offices to C++ software engineers.
After a minor C++14 update discharged in December 2014, different new
augmentations were presented in C++17, and further changes got ready for
2020.
Starting in 2019, C++ is presently the fourth most mainstream programming
language behind Java, C, and Python.
On January 3, 2018, Stroustrup was declared as the 2018 champ of the
Charles Stark Draper Prize for Engineering, for conceptualizing and building
up the C++ programming language.
Stroustrup stayed that the name means the transformative idea of the
progressions from C. This name is credited to Rick Mascitti (mid-1983) and
was first utilized in December 1983. When Mascitti was interviewed casually
in 1992 regarding the naming, he demonstrated that it was given in a passing
moment. The name originates from C's ++ administrator (which increases the
estimation of a variable) and a typical naming show of utilizing "+" to
demonstrate an improved PC program.
During C++'s improvement period, the language had been alluded to as "new
C" and "C with Classes" before securing its last name.
C++ Theory
For an amazing duration, its improvement and advancement have been
guided by many principles:
- Genuine issues must drive it, and its highlights ought to be quickly helpful
in true projects.
- Each component ought to be implementable (with a sensibly evident
approach to do as such).
- Software engineers ought to be allowed to pick their very own
programming style, and that style ought to be completely upheld by C++.
- Permitting a valuable element is a higher priority than anticipating each
conceivable abuse of C++.
- It ought to give offices to sorting out projects into isolated, well-
characterized parts, and give offices to joining independently created parts.
- No implicit infringement of the type system (however permit specific
infringements which are those unequivocally mentioned by the developer).
- Client-made types need to have similar help and execution as implicit kinds.
- Unused highlights ought to not contrarily affect made executables (for
example, in lower execution).
- There ought to be no language underneath C++ (aside from low-level
computing construct).
- C++ should work close by other existing programming dialects, as opposed
to cultivating its very own different and contrary programming conditions.
- If the developer's aim is obscure, enable the software engineer to indicate it
by giving manual control.
Standardization
Standardization for the C++ programming language is credited to the
International Organization for Standardization (ISO), with the most recent
standard adaptation sanctioned and distributed by ISO in December 2017 as
ISO/IEC 14882:2017 (casually known as C++17). The C++ programming
language was at first institutionalized in 1998 as ISO/IEC 14882:1998, which
was then changed by the C++03, C++11 and C++14 norms. The current
C++17 standard overrides these with new highlights and a developed
standard library. Before the underlying institutionalization in 1998, C++ was
created by Danish PC researcher Bjarne Stroustrup at Bell Labs since 1979 as
an augmentation of the C language; he needed a productive and adaptable
language like C that likewise given elevated level highlights to program
organization. C++20 is the following arranged standard, keeping with the ebb
and flow pattern of another rendition every three years.
Another standardization for the programming language came through an ISO
working group called the JTC1/SC22/WG21. Up until now, it has distributed
five modifications of the C++ standard and is presently taking a shot at the
following amendment, C++20.
The ISO working group standardized C++ as ISO/IEC 14882:1998 in the
year 1998, which is casually known as C++98. In 2003, it distributed another
form of the C++ standard called ISO/IEC 14882:2003, which fixed issues
distinguished in C++98.
The following significant update of the standard was casually alluded to as
"C++0x", yet it was not discharged until 2011. C++11 (14882:2011) included
many increases to both the center language and the standard library.
In 2014, C++14 (otherwise called C++1y) was discharged as a little
augmentation to C++11, highlighting bug fixes and little improvements
essentially. The Draft International Standard polling form methods finished
in mid-August 2014.
After C++14, a significant modification C++17, casually known as C++1z,
was finished by the ISO C++ Committee in mid-July 2017 and was endorsed
and distributed in December 2017.
As a feature of the standardization procedure, ISO additionally distributes
specialized reports and determinations:
- ISO/IEC TR 18015: 2006 on the utilization of C++ in inserted frameworks
and on execution ramifications of C++ language and library highlights,
- ISO/IEC TR 19768: 2007 (otherwise called the C++ Technical Report 1) on
library expansions for the most part incorporated into C++11,
- ISO/IEC TR 29124: 2010 on exceptional numerical capacities,
- ISO/IEC TR 24733: 2011 on decimal drifting point math,
- ISO/IEC TS 18822: 2015 on the standard filesystem library,
- ISO/IEC TS 19570: 2015 on parallel renditions of the standard library
calculations,
- ISO/IEC TS 19841: 2015 on programming value-based memory,
- ISO/IEC TS 19568: 2015 on another arrangement of library expansions,
some of which areas of now incorporated into C++17,
- ISO/IEC TS 19217: 2015 on the C++ ideas, coordinated into C++20
- ISO/IEC TS 19571: 2016 on the library augmentations for simultaneousness
- ISO/IEC TS 19568: 2017 on another arrangement of universally useful
library augmentations
- ISO/IEC TS 21425: 2017 on the library augmentations for ranges,
incorporated into C++20
- ISO/IEC TS 22277: 2017 on coroutines
- ISO/IEC TS 19216: 2018 on the systems administration library
- ISO/IEC TS 21544: 2018 on modules
- ISO/IEC TS 19570: 2018 on another arrangement of library augmentations
for parallelism
- Progressively specialized determinations are being developed and pending
endorsement, including static reflection.
Language
The C++ language has two primary parts: a direct mapping of hardware
highlights given fundamentally by the C subset and zero-overhead
abstractions, which are dependent on those mappings. Stroustrup portrays
C++ as a light-weight abstraction programming language designed for
building and utilizing useful and exquisite abstractions, and offering both
hardware access and deliberation is the premise of C++. Doing it proficiently
is the thing that differentiates it from other languages.
C++ acquires the majority of C's sentence structure.
The example below is Bjarne Stroustrup's form of the Hello world program
that uses the C++ Standard Library stream office to compose a message to
standard output. This would give you a better understanding of the language
in practice.
1 #include <iostream>
2
3 int main()
4{
5 std::cout << "Hi, world!\n";
6}
Storing Objects
As in C, C++ underpins four kinds of storage management: static storage
span objects, thread storage span objects, automatic storage spam objects, and
dynamic storage span objects.
Static storage span objects are made before “main()” is entered and
obliterated in backward order of creation after “main()” exits. The precise
request of creation isn't determined by the standard (however, there are a few
principles characterized underneath) to permit executions some opportunity
in how to arrange their usage. All the more officially, objects of this sort have
a span that "keeps going for the length of the program."
Static storage span objects are instated in two stages. To start with, "static
initialization" is performed, and after all static instatement is performed,
"dynamic initialization" is performed. In static initialization, all objects are
first instated with zeros; from that point onward, all items that have a steady
instatement stage are instated with the consistent articulation (for example,
variables introduced with a literal or “constexpr”). In spite of the evidence
that it isn't indicated in the standard, the static instatement stage can be
finished at the accumulate time and spared in the information parcel of the
executable. The dynamic introduction includes all article instatement done
employing a constructor or capacity call (except if the capacity is set apart
with constexpr, in C++11). The dynamic introduction request is characterized
as the request for assertion inside the accumulation unit (for example, a
similar document). No certifications are given about the request for
initialization between gathering units.
Variables of this sort are fundamentally the same as static stockpiling span
objects. The principle contrast is the creation time is only before thread
creation and annihilation is done after the thread has been joined.
The most popular variable sorts in C++ are localized variables inside a
function or block and impermanent variables. The standard component about
automatic variables is their span, which is restricted to the extent of the
variable. They are made and possibly instated at the purpose of the
announcement and devastated in the turnaround request of creation when the
extension is left. This is actualized by assignment on the stack.
Localized variables are made as the purpose of execution passes the assertion
point. Should the variable contain a constructor or initializer, this is utilized
to characterize the underlying condition of the item. Localized variables are
wrecked when the local block or function that they are pronounced in is
closed. C++ destructors for localized variables are called toward the finish of
the lifetime of the object, permitting a control for automatic resource
management named RAII, which is broadly utilized in C++.
Member variables are made when the parent object is made. Cluster
individuals have introduced from zero to the last individual from the exhibit
altogether. Member variables are pulverized when the parent object is
decimated in the switch request of creation. For example, if the parent is a
"programmed object" at that point, it is wrecked when it leaves scope, which
triggers the obliteration of every one of its individuals.
Brief variables are made as to the consequence of articulation assessment and
are obliterated when the statement containing the articulation has been wholly
assessed (as a rule at the; toward the finish of an announcement).
These objects have a unique life expectancy and are made with a call to
“new” and destroyed unequivocally with a call to “delete.” C++ likewise
supports “malloc” and “free,” from C, yet these are not perfect with “new”
and “delete.”
Formats or Templates
C++ formats or templates empower nonexclusive programming. C++
underpins work, class, nom de plume, and variable formats. Formats might be
parameterized by types, assemble time constants, and different layouts. A
launch actualizes formats at order time. To start up a layout, compilers
substitute specific contentions for a format's parameters to produce a solid
capacity or class occurrence. A few substitutions are impractical; these are
dispensed with by an over-burden goals arrangement portrayed by the
expression "Substitution failure isn't an error" (SFINAE). Formats are an
amazing asset that can be utilized for conventional programming, layout
metaprogramming, and code streamlining; however, this power infers an
expense. Format use may expand code size because every layout launch
delivers a duplicate of the format code. One for each arrangement of layout
contentions, in any case, this is the equivalent or littler measure of code that
would be created if the code was composed by hand. [56] This is rather than
run-time generics seen in different dialects (e.g., Java) where at assemble
time, the sort is deleted, and a solitary layout body is saved.
Templates are not quite the same as macros: while both of these incorporate
time language highlights empower contingent accumulation, formats are not
limited to lexical substitution. Layouts know about the semantics and type
arrangement of their partner language, just as all incorporate time type
definitions and can perform elevated level activities, including automatic
stream control dependent on an assessment of carefully type-checked
parameters. Macros are fit for contingent command over accumulation
dependent on foreordained criteria, yet can't start up new kinds, recurse, or
perform type assessment and, as a result, are constrained to pre-arrangement
content substitution and content consideration/rejection. Macros can control
gathering stream dependent on pre-characterized images yet can't, in contrast
to formats, freely start-up new images. Templates or layouts are a device for
static polymorphism and nonexclusive programming.
Moreover, layouts are an arrange time system in C++ that is Turing-finished.
This means that any calculation expressible by a PC program can be
registered, in some structure, by a format metaprogram preceding runtime.
Summarily, a template is an aggregate time parameterized capacity or class
composed without information on the particular contentions used to start it
up. After launch, the subsequent code is equal to code composed explicitly
for the passing contentions. As such, layouts give an approach to decouple
nonexclusive, extensively material parts of capacities and classes (encoded in
templates) from explicit viewpoints (encoded in template parameters) without
giving up execution because of deliberation.
Objects
C++ presents object-oriented programming (OOP) highlights to C. It offers
classes, which give the four highlights ordinarily present in OOP (and some
non-OOP) languages: polymorphism, inheritance, encapsulation, and
abstraction. One distinctive component of C++ classes contrasted with
classes in other programming languages is support for deterministic
destructors, which, thus, offer help for the Resource Acquisition is
Initialization (RAII) idea.
Encapsulation
This is the covering up of data to guarantee that data frameworks and
operators are utilized as proposed and to make the utilization model
increasingly evident to the engineer. C++ gives the capacity to characterize
classes and capacities as its essential epitome instruments. Inside a class,
individuals can be proclaimed as either open, secured, or private to
implement epitome unequivocally. An open individual from the class is
available to any capacity. A private part is open just to capacities that are
individuals from that class and to capacities and classes expressly allowed
access consent by the class ("companions"). A secured part is available to
individuals from classes that acquire from the class, notwithstanding the class
itself and any companions.
The item situated standard guarantees the exemplification of all and just the
capacities that entrance the interior portrayal of a kind. C++ supports this
guideline utilizing part capacities and companion capacities; however, it
doesn't uphold it. Developers can proclaim parts or the entirety of the
portrayal of a sort to be open, and they are permitted to make open elements
not part of the portrayal of a kind. In this way, C++ underpins object-situated
programming, yet other decay ideal models, for example, particular
programming.
It is commonly viewed as great practice to make all information private or
secured, and to make open just those capacities that are a piece of a negligible
interface for clients of the class. This can shroud the subtleties of information
usage, enabling the creator to later on a fundamental level, change the
execution without changing the interface in any way.
Inheritance
This permits one data type to gain properties of other data types. Inheritance
from a base class might be pronounced as open, secured, or private. This
entrance specifier decides if disconnected and determined classes can get to
the acquired open and secured individuals from the base class. Just open
inheritance relates to what is typically implied by "inheritance." The other
two structures are considerably less often utilized. If the entrance specifier is
overlooked, a "class" acquires secretly, while a "struct" acquires freely. Base
classes might be proclaimed as virtual; this is called virtual inheritance.
Virtual inheritance guarantees that just one occasion of a base class exists in
the inheritance chart, dodging a portion of the equivocalness issues of
numerous inheritances.
Different inheritance is a C++ highlight not found in most different
languages, enabling a class to be gotten from more than one base class; this
takes into account progressively expound legacy connections. For instance, a
"Flying Dog" class can acquire from both "Canine" and "Flying Mammal."
Some different languages, for example, C# or Java, achieve something
comparable (albeit increasingly constrained) by permitting inheritance of
numerous interfaces while limiting the number of base classes to one
(interfaces, in contrast to classes, give just presentations of part works, no
usage or part information). An interface like the ones in the programming
languages, C# and Java, can be characterized in C++ as a class containing
just unadulterated virtual capacities, regularly known as a theoretical base
class or "ABC." The part elements of such a dynamic base class are regularly
unequivocally characterized in the inferred class, not acquired verifiably.
C++ virtual legacy displays equivocalness goals include called
predominance.
Operators
C++ gives over 35 operators, covering essential number juggling, bit control,
indirection, correlations, intelligent activities, and others. Practically all
operators can be overloaded for client characterized types, with a couple of
striking special cases, for example, access to “(• and •*)” just as the
restrictive operator. The rich arrangement of overloadable operators is
integral to making client characterized types in C++ appear worked in types.
Overloadable operators are additionally a fundamental piece of many
progressed C++ programming systems, for example, keen pointers.
Overloading an administrator doesn't change the priority of computations,
including the operator, nor does it change the number of operands that the
operator utilizes (the operator may overlook any operand. However, it is
assessed before execution). Overload "&&” and "||” operators lose their short
out assessment property.
Polymorphism
This empowers one standard interface for some executions, and for objects to
act distinctively under various conditions.
C++ supports a few sorts of static (settled at an aggregate time) and dynamic
(settled at run-time) polymorphisms, upheld by the language highlights
portrayed previously. Accumulate time polymorphism doesn't take into
account certain run-time choices, while runtime polymorphism typically
causes an exhibition punishment.
Static polymorphism
Capacity overloading enables projects to announce various capacities having
a similar name yet with various contentions. The capacities are recognized by
the number or types of their conventional parameters. Along these lines, a
similar capacity name can allude to various capacities relying upon the
setting wherein it is utilized. The sort returned by the capacity isn't utilized to
recognize overload works and would bring about an aggregate time mistake
message.
While stating a function, a software engineer can determine for at least one
parameter default esteem. Doing so enables the parameters with defaults to
alternatively be excluded when the capacity is called, in which case the
default contentions are utilized. At the point when capacity is called with
fewer contentions than there are proclaimed parameters, unequivocal
contentions are coordinated to parameters in the left-to-correct request, with
any unparalleled parameters toward the finish of the parameter list being to
their default contentions. As a rule, determining default contentions in a
solitary capacity assertion is desirable over-furnishing over-burden work
definitions with various quantities of parameters.
Templates in C++ give a modern system to composing conventional,
polymorphic code (for example, parametric polymorphism). Specifically,
through the inquisitively repeating format design, it's conceivable to actualize
a type of static polymorphism that intently emulates the sentence structure for
superseding virtual capacities. Since C++ layouts are type-mindful and
Turing-complete, they can likewise be utilized to let the compiler settle
recursive conditionals and produce considerable projects through format
metaprogramming. In opposition to some feelings, the layout code won't
produce a mass code after accumulation with the correct compiler settings.
Dynamic polymorphism
Variable pointers and references to a parent class type in C++ can likewise
allude to objects of any inferred classes of that type. This permits clusters and
different sorts of compartments to hold pointers to objects of different kinds
(references can't be legitimately held in compartments). This empowers
dynamic (run-time) polymorphism, where the alluded articles can carry on
unexpectedly, contingent upon their (real, inferred) types.
C++ likewise gives the “dynamic_cast” operator, which enables code to
securely endeavor transformation of an item, utilizing a base
reference/pointer, to a progressively inferred sort: downcasting. The endeavor
is fundamental as regularly one doesn't realize which inferred type is
referenced. (Upcasting, change to a progressively broad sort, can generally be
checked/performed at the aggregate time utilizing “static_cast,” as familial
classes are indicated in the determined class' interface, evident to all guests.)
dynamic_cast depends on run-time type data (RTTI), metadata in the
program that empowers separating types and their connections. If a
“dynamic_cast” to a pointer fizzles, the outcome is the “nullptr” consistent,
though if the goal is a reference (which can't be invalid), the cast tosses a
particular case. Articles known to be of a specific determined sort can be cast
to that with “static_cast,” bypassing RTTI and the safe runtime type-checking
of “dynamic_cast,” so this ought to be utilized just if the software engineer is
specific the cast is, and will consistently be, legitimate.
What is C++
C++ is a superset of the C programing language, and that means that for all
intents and purposes, any legitimate C program is a lawful C++ program.
A programming language is considered to apply static composing when type
checking is performed during accumulate time rather than runtime.
Object-Oriented Programming
C++ ultimately underpins object-oriented programming, including the four
mainstays of object-oriented advancement, which are data hiding,
encapsulation, inheritance, and polymorphism.
Standard Libraries
Standard C++ comprises of three significant parts. These parts are:
- The primary language giving all the structure blocks, including factors, data
types, and literals, etcetera.
- The C++ Standard Library, which offers a rich arrangement of capacities
controlling records, strings, etcetera.
- The Standard Template Library (STL), which offers an extensive
arrangement of techniques controlling information structures, etcetera.
Learning C++
The most significant thing while at the same time, learning C++ is to
concentrate on ideas.
The motivation behind learning a programming language is to improve as a
software engineer; that is, to turn out to be progressively compelling at
structuring and actualizing new frameworks and at keeping up old ones.
C++ supports an assortment of programming styles. As such, users can write
in styles peculiar to FORTRAN, C, Smalltalk, etcetera, in any language. Each
style can accomplish its points viably while keeping up runtime and space
proficiency.
Utilization of C++
- C++ is utilized by a considerable number of software engineers in basically
every application space.
- C++ is, as a rule, profoundly used to compose gadget drivers and other
programming that depend on direct control of equipment under real-time
requirements.
- C++ is broadly utilized for instructing and research since it is spotless
enough for fruitful educating of fundamental ideas.
- Any individual who has utilized either an Apple Macintosh or a PC running
Windows has, in a roundabout way, utilized C++ because the essential UIs of
these frameworks are written in C++.
Exercise 1:
For instance:
int num1=20, num2=100;
We can likewise compose it like this:
int num1,num2;
num1=20;
num2=100;
Kinds of variables
Variables can be arranged dependent on their data type. For instance, in the
above model, we have seen whole number type variables. Below are the sorts
of variables accessible in C++.
int primary {
//Some code
}
Any variable proclaimed inside these brackets has scope restricted inside
these brackets, if you pronounce a variable in a main() function and attempt
to utilize that variable outside the main() function, then you get an
assemblage error.
Since we have comprehended scope is, let us proceed onward to the sorts of
factors dependent on the scope.
-Global variable
A variable announced outside of any function (counting main too) is called a
global variable. Global variables have their scope all through the program.
They can be gotten to anyplace in the program, in the main, in the user
characterized function, anyplace.
The example shown below can help you understand it better.
#include <iostream>
utilizing namespace std;
//This is a global variable
char myVar = 'A';
int main()
{
cout <<"Value of myVar: "<< myVar<<endi;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Yield:
Value of myVar: A
Value of myVar: Z
Local variable
These variables are proclaimed inside the supports of any user characterized
functions, principle capacity, circles, or any control statements(if, if-else,
etcetera) and have their scope restricted inside those brackets.
Below is an example.
Local variable model
#include <iostream>
utilizing namespace std;
char myFuncn() {
//This is a nearby factor
char myVar = 'A';
}
int primary()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Yield:
Incorporate time error, since we are attempting to get to the variable myVar
outside of its scope. The scope of myVar is restricted to the group of function
myFuncn(), inside those brackets.
Can Global And Local Factors Have The Same Name in C++?
Let’s see a model having the same name as a global and local factor.
#include <iostream>
utilizing namespace std;
// This is a worldwide variable
char myVar = 'A';
char myFuncn() {
// This is a neighborhood variable
char myVar = 'B';
return myVar;
}
int principle()
{
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
return 0;
}
Yield:
Funcn call: B
Value of myVar: A
Funcn call: B
Value of myVar: Z
Exercise 2:
An Overview
There are numerous simple approaches to get to a database in C/C++. Except
for ODBC, its APIs are not standard. Most database merchants give a local
customer library to get to a database. Customer libraries are seller explicit;
that implies that the API gave by one is not the same as another, although the
hidden standards are the equivalent. MySQL, for instance, has its custom
library, and the API provided is very not quite the same as the API provided
by the customer library of PostgreSQL. If you stick to one merchant explicit
database, state MySQL, the driver choices for database programming with
C++ are:
- > Click on the code::blocks IDE and proceed to settings - > then compiler
and debugger settings (You should notice a worldwide compiler setting)
- > Now click on “Linker settings” in the linker settings click on ADD catch
and include the accompanying
On Windows Systems:
Enter the following code:
C:\SQLAPI\lib\libsqlapiddll.a
C:\Program Files\CodeBlocks\MinGW\lib\libuser32.a
C:\Program Files\CodeBlocks\MinGW\lib\libversion.a
C:\Program Files\CodeBlocks\MinGW\lib\liboleaut32.a
C:\Program Files\CodeBlocks\MinGW\lib\libole32.a
These a found in your SQLAPI++ (If you have not extricated in C: drive at
that point, select the proper area and add the referenced records to linker
settings).
The above code is utilized to add library records to interface C/C++ program
with SQL API.
Code:
/C++ program for associating with database (and blunder taking care of)
#include<stdio.h>
#include<SQLAPI.h>/fundamental SQLAPI++ header
int main(int argc, char* argv[])
{
//make association item to interface with database
SAConnection con;
try
{
//interface with database
//in this model, it is Oracle,
//yet can likewise be Sybase, Informix, DB2
//SQLServer, InterBase, SQLBase and ODBC
con.Connect ("test",/database name
“tester",/client name
“tester",/secret phrase
SA_Oracle_Client);/Oracle Client
printf("We are connected!\n");
//Disconnect is discretionary
//autodisconnect will happen in destructor if necessary
con.Disconnect();
printf("We are disconnected!\n");
}
catch(SAException and x)
{
//SAConnection::Rollback()
//can likewise toss a special case
//(if a system mistake for instance),
//we will be prepared
attempt
{
//on mistake rollback changes
con.Rollback ();
}
catch(SAException and)
{
}
//print error message
printf("%s\n", (const char*)x.ErrText());
}
return 0;
}
Yield:
We are Connected!
We are Disconnected!
Full Code:
#include<stdio.h>
#include <SQLAPI.h> // main SQLAPI++ header
int main(int argc, char* argv[])
{
SAConnection con; // connection object will connect to the database
SACommandcmd; // create a command object
try
{
// connect to a database (Oracle in the sample)
con.Connect("test", "tester", "tester", SA_Oracle_Client);
// link a command to the connection
// connection can also be stated within the SACommand constructor
cmd.setConnection(&con);
// create a table
cmd.setCommandText("create a table tbl(id number, color
varchar(20));");
cmd.Execute();
// enter value
cmd.setCommandText("Input into tbl(id, color) values (1,”Orange”)");
cmd.setCommandText("Input into tbl(id, color) values (2,”Peach”)");
cmd.setCommandText("Insert into tbl(id, name) values (3,”Purple”)");
cmd.Execute();
// commit to changes on success
con.Commit();
printf("Table created, row inserted!\n");
}
catch(SAException &x)
{
// SAConnection::Rollback()
// can also throw an exception
// (if a network error for instance),
// we will be ready
try
{
// on error rollback changes
con.Rollback();
}
catch(SAException &)
{
}
// print error message
printf("%s\n", (const char*)x.ErrText());
}
return 0;
}
Objects− These have states and behaviors. Let me use the example of a cat to
explain this. A cat has states which include its color, name, breed as well as
its behaviors, which include feeding, jumping, meowing. In biological terms,
these are referred to as the characteristics of the dog. In programming speak,
the occurrences of these characteristics refer to an object. An object can be
seen as the occurrence of a class.
#include <iostream>
using namespace std;
The C++ language characterizes a few headers, which contain data that is
either vital or valuable to your program. For this program, the header
<iostream> is required.
The line utilizing namespace std; advises the compiler to utilize the std
namespace. Namespaces are a generally ongoing expansion to C++.
The following line ‘//main() is where program execution begins.’ is a single
line statement accessible in C++. The single-line statement starts with “//
“and stops toward the end of the line.
The line int main() is the primary function where program execution starts.
The following line cout << “Hi World”; causes the message “Hi World” to be
shown on the screen.
The following line returns 0; ends the main( )function and makes it return the
value 0 to the calling procedure.
You have the option to see ‘Hello World’ imprinted on the window.
g++ hello.cpp
./a.out
Hi World
Ensure that g++ is in your path and that you are running it in the directory
containing document hello.cpp.
You can accumulate C++ programs utilizing makefile.
Semicolons and Blocks in C++
In C++, the semicolon is a statement ended. That is, every individual
statement must be finished with a semicolon. It demonstrates the end of one
logical element.
C++ doesn't perceive the end of the line as the end of the code or piece of
code. Thus, it doesn't make a difference where you put a statement in a line.
For instance−
* x = y;
* y = y + 1;
* add(x, y);
* is equivalent to
* x = y; y = y + 1; add(x, y);
C++ Identifiers
A\The term C++ identifier is used in recognizing a variable, module, class,
function, or some other user characterized thing. An identifier begins with a
letter a to z or beginning to end or an underscore (_) trailed by at least zero
letters, underscores, and digits (0 to 9).
C++ doesn’t permit accentuation characters, for example, @, $, and % inside
identifiers. C++ is a case-touchy programming language. Therefore, Labor
and labor are two distinct identifiers in C++.
asm, else, new, this, auto, enum, operator, throw, bool, explicit, private, true,
break, export, protected, try, case, extern, public, typedef, catch, false,
register, typeid, char, float, reinterpret_cast, typename, class, for, return,
union, const, friend, short, unsigned, const_cast, goto, signed, using,
continue, if, sizeof, virtual, default, inline, static, void, delete, int, static_cast,
volatile, do, long, struct, wchar_t, double, mutable, switch, while,
dynamic_cast, namespace, template, Trigraphs.
Trigraph
Replacement
Trigraph Replacement
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~
Every one of the compilers doesn’t support trigraphs, and they are not
instructed to be utilized on the grounds of their befuddling nature.
Whitespace in C++
A line containing just whitespace, potentially with a statement, is known as a
clear line, and the C++ compiler disregards it.
Whitespace is the term utilized in C++ to portray spaces, tabs, newline
characters, and remarks. Whitespace isolates one piece of a statement from
another and empowers the compiler to recognize where one component in a
statement, for example, int, closes, and the following component starts.
Statement 1
int age;
Statement 2
natural product = apples + oranges;/Get the complete organic product
Exercise 4:
1. Distinguish between an object and a class.
2. What are characters, such as @, $, and % known as in C++?
3. What is the use of semicolons in C++?
Chapter Five
Data Types
All variables use data type during assertion to confine the sort of information
to be put away. This way, we can say that data types are utilized to tell the
variables the sort of data it can store. At whatever point a variable is
characterized in C++, the compiler designates some memory for that variable
dependent on the data type with which it is stated. Each datum type requires
an alternate measure of memory.
Datatype Modifiers
As the name suggests, datatype modifiers are utilized with the inherent data
types to adjust the length of data that a specific data type can hold.
Beneath table abridges the adjusted size and scope of inherent datatypes
when joined with the sort modifiers:
float 5
double 10
long double 15
Note: The above qualities may differ from compiler to compiler. In the above
model, we have considered a GCC 64 piece.
We can show the size of the considerable number of data types by utilizing
the size of () function and passing the keyword of the datatype as a
contention to this capacity as demonstrated as follows:
int main()
{
cout << "Size of int: " << sizeof(int)
<< ' byte' << endl;
cout << 'Size of char: ' << sizeof(char)
<< ' bytes' << endl;
cout << 'Size of wchar_t : ' << sizeof(wchar_t)
<< ' bytes" << endl;
cout << "Size of double : ' << sizeof(double)
<< ' bytes' << endl;
cout << 'Size of unsigned long int : ' << sizeof(unsigned long int)
<< ' bytes' << endl;
cout << 'Size of long int : ' << sizeof(signed long int)
<< ' bytes' << endl;
cout << 'Size of short integer: ' << sizeof(short integer)
<< ' bytes' <<endl;
cout << 'Size of signed long int : ' << sizeof(signed long int)
<< ' bytes' << endl;
cout << 'Size of float: ' << sizeof(float)
<< ' bytes' <<endl;
return 0;
}
Output:
Size of int : 4 bytes
Size of char : 1 byte
Size of wchar_t: 4 bytes
Size of double : 8 bytes
Size of unsigned long int : 8 bytes
Size of long int : 8 bytes
Size of short int: 2 bytes
Size of signed long int : 8 bytes
Size of float: 4 bytes
Exercise 5:
As the name suggests, the name constants are given to such variables or
values in C++ programming language, which can't be changed once they are
characterized. They are fixed values in a program. There can be many sorts of
constants like integer, float, octal, hexadecimal, character constants, and so
forth. Each constant has some range. The numbers that are too large to fit into
an int are taken as long. Presently different extents contrast from unsigned to
signed bits. Under the signed piece, the scope of an int differs from -128 to
+127 and under the unsigned piece, int changes from 0 to 255.
Characterizing Constants:
In C++ program, we can characterize constants in two different ways as
demonstrated as follows:
- Utilizing #define preprocessor directive
- Utilizing a const keyword
Literals
The values allocated to all constant variables are alluded to as the literals. For
the most part, the two terms, constants and literals, are utilized reciprocally.
For example, "const int = 5;" is a constant articulation and the value 5 is
referred to as constant integer literal.
Model:
#include <iostream>
using namespace std;
#define val 10
#define floatVal 4.5
#define charVal 'G'
int main() {
cout << "Integer Constant: " << val << "\n";
cout << "Floating point Constant: " << floatVal << "\n";
cout << "Character Constant: "<< charVal << "\n";
return 0;
}
Yield:
Integer Constant: 10
Floating-point Constant: 4.5
Character Constant: G
include <iostream>
using namespace std;
int main() {
// int constant
const int intVal = 10;
// Real constant
const float floatVal = 4.14;
// char constant
const char charVal = 'A';
// string constant
const string stringVal = "ABC";
Yield:
Integer constant: 10
Floating point constant: 4.14
Character constant: A
String constant: ABC
For instance:
0x10 = 16
For instance:
56, 78
For instance:
045, 076, 06210
For instance:
0b101, 0B111
Suffixes: The prefix of the integers strictly demonstrates the sort wherein it is
to be perused.
For instance:
12345678901234LL
shows a long integer value 12345678901234
in light of the suffix LL
These are spoken to from numerous points of view, as indicated by their data
types.
- unsigned long int: character ull or ULL toward the finish of an integer
constant.
Model:
C++
#include <iostream>
using namespace std;
int main()
{
// constant integer literal
const int intVal = 10;
cout << "Integer Literal: "
<< intVal << "\n";
return 0;
}
Yield:
Integer Literal:10
Floating Point Literals: These are utilized to speak to and store genuine
numbers. The genuine number has a whole number part, a genuine part, a
partial part, and an exponential part. The floating-point literals can be put
away either in decimal structure or exponential structure. While speaking to
the floating-point decimals, one must remember two things to deliver
substantial literals:
In the decimal structure, one must incorporate the decimal point, example
part, or both, else, it prompts a blunder.
In the exponential structure, one must incorporate the whole number part,
partial part, or both, else, it prompts a mistake.
Model:
#include <iostream>
using namespace std;
int main()
{
// Real literal
const float floatVal = 4.14;
cout << "Floating-point literal: "
<< floatVal << "\n";
return 0;
}
Yield:
Floating point literal: 4.14
Character Literal: This alludes to the literals that are utilized to store a single
character inside a separate statement. To store numerous characters, one
needs to utilize a character cluster. Putting away more than one character
inside a separate statement tosses an admonition and shows only the last
character of the strict. It offers to ascend to the accompanying two portrayals:
Char type: This used to store ordinary character exacting or the tight
character literals. C++ upholds this.
Model:
/For C++
singe chr = 'G';
wchar_t type: This exacting is supported just in C++ and not in C. If the
character is trailed by L, at that point, the strict should be put away in
wchar_t. This speaks to wide-character exacting.
Model:
#include <iostream>
using namespace std;
int main()
{
// constant char literal
const char charVal = 'A';
return 0;
}
Yield:
Character Literal: A
Escape Sequences: There are different exceptional characters that one can use
to perform different activities.
String Literals: String literals are like that of the character literals, then again,
actually it can store various characters and uses a double statement to store
the equivalent. It can likewise oblige the extraordinary characters and
getaway arrangements referenced in the table above.
Model:
string stringVal = "ThisOurBooks"
Model:
#include <iostream>
using namespace std;
int main()
{
const string str
= "Welcome\nTo\nThis\tOur\tBook";
cout << str;
return 0;
}
Yield:
Welcome
To
Boolean Literals: This literal is given uniquely in C++ and not in C. They are
utilized to speak to the Boolean datatypes. These can convey two qualities:
true: To speak to true value. This must not be viewed as equivalent to int 1.
false: To speak to false value. This must not be viewed as equivalent to int 0.
Model:
#include <iostream>
using namespace std;
int main()
{
const bool isTrue = true;
return 0;
}
Yield:
isTrue? 1
isFalse? 0
Exercise 6:
1. What are literals?
2. What are constants?
3. What are boolean literals?
Chapter Seven
Operators
Operators In C++
Operators make up the essential foundation of any programming language.
Without operators, we can't change or control the contents of programming
languages and, in this manner, can't deliver the ideal outcomes. C++ is
wealthy in worked in operators.
In C++, a large portion of the operators is double operators. What this means
is that these operators require two operands to play out an activity. Not many
operators like ++ (increase) operators are the unary operator, which implies
they work on one operand as it were.
There is likewise a ternary operator in C++ called Conditional Operator,
which takes three operands.
Arithmetic Operators
This type of operator is utilized for performing fundamental mathematical
tasks on operands.
C++ underpins the accompanying arithmetic tasks:
Operator Binary/unary Description
- + Binary Addition of two operands
- Binary Subtraction of two operands
The example beneath exhibits the initial five arithmetic operators in C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
int op1=3,op2=4;
float op3=10.1,op4=5.4;
cout<<"Operands are op1 = "<<op1<<" op2 = "<<op2;
cout<<" op3 = "<<op3<<" op4 = "<<op4;
cout<<endl;
cout<<"op1 + op2 = "<<op1+op2<<endl;
cout<<"op1 - op2 = "<<op1-op2<<endl;
cout<<"op3 * op4 = "<<op3*op4<<endl;
cout<<"op3 / op4 = "<<op3/op4<<endl;
cout<<"op2 % op1 = "<<op2%op1<<endl;
}
Yield:
The following arithmetic operators that we cover are ++ and –. These are
called increment and decrement operators individually. The increment
operator builds the value of the operand by 1, while the decrement
administrator diminishes the value of the operand by 1.
x+=1;
x = x+1;
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x=4,y;
y = ++x;
cout<<"PreIncrement:Value of x = "<<x;
cout<<endl;
cout<<"PreIncrement:Value of y = "<<y;
cout<<endl;
y = x--;
cout<<"PostDecrement:Value of x = "<<x;
cout<<endl;
cout<<"PostDecrement:Value of y = "<<y;
cout<<endl;
}
Yield:
PreIncrement:Value of x = 5
PreIncrement:Value of y = 5
PostDecrement:Value of x = 4
PostDecrement:Value of y = 5
This is the program to exhibit the increment and decrement operators. Note
that we have utilized pre-increment and post-decrement operators in this
program. For the first articulation, y=++x, as this is pre-increment, x is
augmented first, and afterward, the resultant value is doled out to y. This is
obvious from the yield that we have gotten.
Logical Operators
These kinds of operators are utilized for assessing a mix of
conditions/imperatives to get a resultant value. The aftereffect of the
assessment of a Boolean articulation is Boolean, which is either true or false.
Operator Description
- && Logical AND: returns true if the two true conditions generally
return false.
- || Logical OR: This operator returns true when one of the conditions is
valid. Returns false when the two conditions are false.
- ! Logical NOT: refutes the condition.
##include <iostream>
#include <string>
using namespace std;
int main()
{
int a=25, b=5,c=18,d=22;
if(!(a==0))
cout<<"a is not zero"<<endl;
else
cout<<"a is zero"<<endl; if((a>b)&&(c<d))
cout<<"Logical AND is true"<<endl;
else
cout<<"Logical AND is false"<<endl;
if((a<c)||(b<d))
cout<<"Logical OR is true"<<endl;
else
cout<<"Logical OR is false"<<endl;
}
Yield:
a isn't zero
Logical AND is true
Logical OR is true
In the above program, we have utilized all three logical operators to assess
articulations and print the outcomes.
Relational Operators
These kinds of operators are utilized to carry out a comparison between the
two operands. The consequence of the assessment is either true or false.
C++ supports the accompanying Relational Operators:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a=15, b=13,c=17,d=20;
if(a==b)
cout<<"a is equal to b"<<endl;
else
cout<<"a is not equal to b"<<endl;
if(c!=d)
cout<<"c is not equal to d"<<endl;
else
cout<<"c is equal to d"<<endl;
Yield:
an isn't equivalent to b
c isn't equivalent to d
(a+b) less than/equal to (c+d)
(a-b) greater than/equal to (d-c)
In the above program, we see the utilization of relational operators and how
they assess the articulations given.
Note that we can give values as well as variables and articulations in the
contingent proclamations.
Bitwise Operators
These types of operators in C++ work on bits of the operands gave. Bitwise
operators are applied distinctly to fundamental sorts like number, character,
and so on., and not on data types like float, double, and so on.
These bitwise operators work on operands in a tiny bit at a time. Truth tables
for AND, OR, and XOR tasks are given beneath.
Think about a and b as two bits on which AND, OR, and XOR activities are
to be completed.
Truth tables for the equivalent are as given underneath:
a=8 1000
a=4 0100
a&b 0000 = 0
a|b 1100 = 12
a^b 1100 = 12
In the above model, we see that the bitwise AND of 8 and 4 is 0. Bitwise OR
of 8 and 4 is 12, and bitwise XOR of 8 and 4 is also 12.
##include <iostream>
#include <string>
using namespace std;
int main()
{
int a=8,b=4,c;
c = a&b;
cout<<"Result of & : "<<c<<endl;
c = a|b;
cout<<"Result of | : "<<c<<endl;
c = a^b;
cout<<"Result of ^ : "<<c<<endl;
c = a<<2;
cout<<"Result of << by 2 bits : "<<c<<endl; c = b>>2;
cout<<"Result of >> by 2 bits : "<<c<<endl;
c = ~3;
cout<<"Result of ~ : "<<c<<endl;
}
Yield:
Result of & : 0
Result of | : 12
Result of ^ : 12
Result of << by 2 bits: 32
Result of >> by 2 bits: 1
Result of ~ : -4
In the above program, we exhibited the use of bitwise operators and printed
the yield.
Assignment Operators
Assignment operator "=" is accustomed to allotting an incentive to a variable.
The Left-Hand Side of the task administrator is a variable, and the Right-
Hand Side is the value that is designated to the variable. The value on the
right side must be the same as that of the variable on the left-hand side.
Note the contrast between '=' and '==' operators. The previous is the
assignment operator, and the latter is the equality operator.
Assignment activity happens from right to left. Aside from the assignment
operator '=,' there are different varieties of assignment operators, which are
known as 'compound assignment operators". These operators play out an
activity, notwithstanding the assignment.
The underneath breakdown gives us a depiction of these assignment
operators.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x,y;
cout<<"Enter input variable y: "; cin>>y;
x = y;
cout<<"\nValue of x = "<<x<<endl;
a *= b;
b /= c;
cout<<"\na *= b: "<<a;
cout<<"\nb /= c: "<<b;
return 0;
}
Yield:
Note: We can likewise join the other paired operators like %, <<, >>, and, |,
^, and so on into compound assignment articulations, notwithstanding the
ones that are now illustrated.
Other Operators
So far, we investigated all the significant operators in C++. Some
progressively extra C++ operators need our consideration.
These operators include:
Size of operator
The conditional operator in C++ can be utilized as a trade for the if-else
statement.
The general language structure for the conditional operator is:
Condition? expression1:expression2;
Comma Operator
This operator that is spoken to as a token ‘,’ can be utilized as an operator just
as a separator.
As an operator, a comma is utilized when there is more than one articulation
to be assessed. Just the furthest right articulation is relegated to LHS.
x = (y=4, y+1);
There are two operators in C++ that are utilized to get to the individual
members from classes, structures, or associations. These operators include
the arrow (- >) operator and dot operator (.). You gain proficiency with these
operators in detail when you learn object-arranged programming in C++.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x,y;
x = (y=3,y+4);
cout<<"Value of x = "<<x;
y = (x<5)?0:1;
if(y == 0)
cout<<"\nVariable x is less than 5"<<endl;
else
cout<<"\nVariable x is greater than 5"<<endl;
return 0;
Yield:
Value of x = 7
Variable x is greater than 5
sizeof(x): 4 sizeof(y): 4
As appeared in the above program, first, we have two factors announced and
isolated using a comma (comma as a separator). Furthermore, a comma
operator contains two articulations. As should be evident from the yield, the
furthest right articulation’s value is allocated to variable x. Next, we exhibit
the conditional administrator to assess if x is under 5.
At long last, we exhibit the use of the sizeof the administrator. Here we
utilize the sizeof the administrator to get the size of the factors x and y. As
both are whole number factors, the size returned is 4 bytes.
We have just observed practically all the C++ operators, and we realize that
they can be utilized in articulations to do explicit tasks. Be that as it may, the
articulations we have found in models are basic and clear. Be that as it may,
contingent upon our necessities, articulations will, in general, become
increasingly mind-boggling.
Such intricate articulations have more than one operator and various
operands. In such a circumstance, we have to assess which operator is to be
assessed first.
x = 4 + 5/3;
Notes:
Priority level 1 is the most noteworthy, and level 17 is the least. Operators
with a higher priority level get assessed first.
Exercise 7:
1. What are operators?
2. What are bitwise operators?
3. Name the two-member access operators.
Chapter Eight
Loop Constructs in C++
Loops In C++
For Loop
The construct that executes proclamations repetition is the “for” loop.
The general sentence structure for the loop shows that it comprises of three
sections. The initialization expression comprises the underlying qualities set
for the loop variable. The condition expression gives the condition that is
checked to leave the loop. The increment part is utilized to increase the loop
variable after each iteration.
At first, the “for” loop starts execution with the initialization of the loop
variable. At that point, it tests the condition. If the value of the loop variable
fulfills the condition, then it executes the statement block.
At the point when the statement block is executed, the loop variable is
augmented according to the increment determined, and the following iteration
is begun. Along these lines, the loop does the iteration until the condition is
satisfied. At that point, the “for” loop is left.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"Printing multiples of 3 less than 30"<<endl;
for(int i =3;i<=30;i +=3)
{cout<<"i = "<<i<<"\t";
}
}
Yield:
Printing multiples of 3 less than 30
i = 3 i = 6 i = 9 i = 12 i = 15 i = 18 i = 21 i = 24 i = 27 i = 30
Here you print the 2’s multiples up to 20 utilizing a “for” loop. Note that it is
advantageous to utilize when you know the number of iterations in advance.
While Loop
C++ gives one more loop develop that enables us to execute many statements
repetitively. This is ‘while’ loop.
while(condition)
{
Statement_block;
}
‘While’ loop rehashes a lot of the statement as long as the condition is valid.
So, before the beginning of each iteration, the condition is assessed. If it is
satisfied, statement_block is inside while loop. Else, the loop is left.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"Printing multiples of 3 less than 30"<<endl;
int i=2;
while(i<=20)
{
cout<<"i = "<<i<<"\t";
i += 2;
}
}
Yield:
Printing multiples of 3 less than 30
i = 3 i = 6 i = 9 i = 12 i = 15 i = 18 i = 21 i = 24 i = 27 i = 20
To streamline the idea, we have changed a similar program that was utilized
to show the “for” loop. Here not at all like for loop, we determine the
underlying value of the loop variable outside the while loop. At that point, we
start the while loop, where we indicate the condition.
Inside the loop, we increase the loop variable, and the code within the
“while” loop is processed, given the condition is satisfied.
At the point when you don’t know about the precise number of iterations that
the code is executed for, you go for a “while” loop.
Do While Loop
The following loop in C++ is the “do-while” loop. On account of the “while”
loop, we check the condition first and afterward execute the cycle. On
account of d“do-while” loop, we execute the cycle first, and afterward, we
assess the condition to proceed with the loop.
The "do-while" loop has the standard syntax shown below:
do{
…
…
}while(condition);
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"Printing 3's multiples less than 30"<<endl;
int i=3;
do
{
cout<<"i = "<<i<<"\t";
i += 3;
}while(i<=30);
}
Yield:
Printing 3's multiples less than 30
i = 3 i = 6 i = 9 i = 12 i = 15 i = 18 i = 21 i = 24 i = 27 i = 30
We have changed a similar model to the past loops. Note that the condition is
checked toward the end after the statement block is executed. This guarantees
the loop is executed at any rate once before exiting.
The flow diagram demonstrating Break and Continue statements are given
below:
Break
Continue
Let us see a case of utilizing the break and continue statements in the code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout<<"Printing 3's multiples less than 30"<<endl;
int i =0;
while(1)
{
if(i==0){
i += 3;
continue;}
cout<<"i = "<<i<<"\t"; i += 3; if(i > 30) break;
}
}
Yield:
Printing 3's multiples less than 30
i = 3 i = 6 i = 9 i = 12 i = 15 i = 18 i = 21 i = 24 i = 27 i = 30
By and by, we have taken a similar case of printing 2’s multiples up to 20.
For this situation, we have initiated the loop variable to zero. At that point,
we utilize an endless while loop, and inside the loop, we skirt the main
iteration utilizing the continue statement.
Next, we utilize the break statement to exit out of the loop the minute the
loop variable gets higher than 30.
At the point when the explanation matches any instance of the switch
statement, the code is executed. Afterward, the control goes to the cases
following the matched case. Along these lines, in the wake of matching the
case, every single ensuing case is likewise executed before leaving the switch
statement. This leads to a case of an erroneous output.
To keep the consequent cases from executing, we present the break statement
toward the finish of each case. This makes the controlled exit out of the
switch statement once the matching case is found and code is executed.
Infinite Loop
An infinite loop is additionally called an endless loop. An endless loop
happens when the loop condition consistently evaluates to true. Subsequently,
it executes inconclusively.
For example, for(;;) brings about an infinite “for” loop.
While(;) or while(1) results in while loop being executed inconclusively.
Infinite loops ought not to be empowered in programming, however, on the
off chance that at all the need emerges, we ought to have the option to break
out of the loop utilizing an ending condition inside the loop.
While loop ought to be utilized when we realize the ending state of the loop.
The do-while loop ought to be utilized when we need the loop to be executed
at any rate once.
Exercise 8:
1. What triggers an endless loop?
2. How is a break and continue statements used?
3. How does the while loop work?
Chapter Nine
Decision Making
If Statement
The general sentence structure of ‘If’ statement is given beneath:
if(condition)
{
statement _block;
}
This is the fundamental decision-making construct. The condition inside the
‘if’ develop is assessed. If it is true, the statement block within the brackets
following the ‘if’ explanation is executed.
If the condition is false, at that point, the statement block is skipped, and
control is passed to the statements following the ‘if’ square.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
cout<<"Enter number between 1 and 10:"; cin>>num;
if(num>=1 && num<=10)
{ cout<<"\nYou have entered correct number";
return 0;
}
cout<<"\nNumber not between 1 and 10";
}
Yield:
Enter number between 1 and 10:4
You have entered the correct number
In the above program, we utilize ‘if’ construct to decide whether the number
entered is somewhere in the range of 1 and 10.
If-else Statement
Now and then, a circumstance emerges where we need to execute one
statement block if the condition is true and another statement block if the
condition is false. In such a circumstance, we utilize the ‘If-else’ construct.
if(condition)
{
statement _block;
}
else
{
statement _block;
}
If the condition is true, at that point, the statement block after the ‘if’
condition is executed. If the condition is false, at that point, the statement
block after the ‘else’ statement is executed.
The flow diagram for the ‘if-else’ construct is demonstrated as follows.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char mychar = 'X';
if(mychar == 'X')
cout<<"\nCharacter is 'X'";
else
cout<<"\nCharacter is not 'X'";
}
Yield:
Character is ‘X'
In this sample program, we find out whether the character is ‘X’ and as print
the message as required.
Else if Statement
In this construct, we have different conditions just as alternatives. If the
condition is true, at that point, the statement block after ‘if’ statement is
executed. If the condition is false, at that point, another if the condition is
checked.
Contingent upon whether the condition is true or false, the statement block or
another condition is checked. This is shown in the general language structure
of this construct beneath.
General Syntax:
if(condition)
{ statement-block1;
}else if(condition)
{ statement-block2; }
else if(condition)
{ statement-block3; }
else
default-statement;
As shown above, there are numerous ‘if’ statements within the else block of
the initial ‘if’ statement. The final level in the code block is the ‘else’
statement, which initiates the execution of the default statement.
Flow Diagram of Else if Statement
Let us see a case of this construct.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
cout<<"To determine if the input number is negative or positive"<<endl;
cout<<"Enter the number: "; cin>>num;
if(num==0)
{ cout<<"The number entered is 0"<<endl;
}
else if(num < 0)
{cout<<"The number is negative"<<endl;}
else
{cout<<"The number is positive"<<endl;}
return 0;
}
Yield:
To determine if the input number is negative or positive
Enter the number: 7
The number is positive
In the code shown above, we utilize the ‘else-if’ statement. Here we verify if
the number inputted is zero, positive or negative. To do this, we make use of
the if-else develop.
Nested If Statement
By term ‘Nested If,’ we mean at least one ‘if’ statement inside another ‘if’
statement. We can have any type of ‘if’ statement like simple if, if-else, else-
if, or another settled if relying upon our necessities.
Given beneath is the general language structure of the nested if and the flow
diagram.
General Syntax:
if(condition)
{
if(condition)
{
Statement_block;
}
else{
Statement_block;}
}
else
{Statement_block;}
Flow Diagram of Nested If Statement:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num=10;
if(num>0)
{
if(num==10)
cout<<"Number = 10"<<endl; else if(num > 10)
cout<<"Number is greater than 10"<<endl;
else if(num < 10)
cout<<"Number is less than 10"<<endl;
}
else
cout<<"Number is negative"<<endl;
return 0;
}
Output:
Number = 10
Switch Statement
As our projects get increasingly conflict, we will, in general, have an ever-
increasing number of conditions to test, and if regardless, we use ‘if’
statements, there are various ‘if’ statements which are hard to deal with and
in this way make our program confused.
...
case n: {statement_block;
break;}
default: {statement_block;
break;}
}
In the syntax shown above, the switch contingent statement ought to be the
one that evaluates to a constant value. Expressions evaluating variable
qualities are considered invalid. There are ‘n’ cases for the switch statement,
as well as a default case. Keep in mind that the default case is executed when
the statement doesn’t match any of the cases given.
The default case is optional. On the off chance that the default case is
missing, the switch leaves when no case is matched.
The statement’ break;’ is likewise optional. The break statement is utilized to
exit out of the statement. If the break statement isn’t given, after a counterpart
for the case is discovered, at that point, other consequent cases are executed
likewise.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char mychar;
cout<<"Enter an uppercase vowel character:"; cin>>mychar;
switch(mychar)
{
In the sample program used here, we verify whether the character inputted is
an English vowel. For this, we indicated the vowel cases and a default case if
a character other than vowel is entered.
Goto Statement
We use ‘goto’ statement, at whatever point we have to branch to another
piece of the code from one point. Here we name a specific statement, and
afterward, utilizing ‘goto label,’ we branch to that specific statement.
The general language structure of the goto statement is shown below:
goto label;
…
…
label: statement_block;
…
…
int main()
{
int num = 5;
if(num>0)
{
cout<<"Number is greater than 0"<<endl;
if (num <= 5) goto labelfive; else if (num >5)
cout<<"Number is greater than 5 too"<<endl;
}
labelfive: if(num == 5)
cout<<"Number is equal to 5"<<endl;
else if(num < 5)
cout<<"Number is less than 5"<<endl;
return 0;
}
Yield:
Number is greater than 0
Number is equal to 5
In the above program, we utilize the ‘goto’ statement. We verify whether the
number is equal to or less than 5, and if it is, we jump to a name titled
‘labelfive.’
We have reached the end of this chapter on decision making constructs in
C++. As already talked about, these decision-making constructs enable us to
execute the code according to our choice.
Exercise 9:
1. In the if-else statement, what happens when a condition is true?
2. Why are the break and continue statements preferred to the go-to
statement?
Explain the switch statement.
Chapter Ten
Numbers
Typically, when we work with Numbers, we utilize crude data types, for
example, int, short, long, float and double, and so on. The number of data
types, their inherent qualities, and number extents has been clarified while
examining C++ Data Types.
#include <iostream>
using namespace std;
int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
At the point when the above code is incorporated and executed, it creates the
accompanying outcome −
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
To use these capacities, you have to incorporate the math header file
<cmath>.
1: double cos(double): This function takes an angle (as a double) and gives
you the cosine.
2: double sin(double): This function takes an angle (as a double) and gives
you the sine.
3: double tan(double): This function takes an angle (as a double) and gives
you the tangent.
4: double log(double): This function takes a number and returns the standard
log of that number.
5: double pow(double, double): The first is a number you wish to raise and
the second is the power you wish to raise it to
7: double sqrt(double): You give this function a number, and it gives you the
square root.
8: int abs(int): This function gives you the total value of a whole number that
is given to it.
9: double fabs(double): This function gives you the total value of any decimal
number given to it.
10: double floor(double): Finds the whole number, which is not exactly or
equivalent to the argument given to it.
#include <iostream>
#include <cmath>
using namespace std;
int main () {
// number definition:
short s = 10;
int i = -1000;
/* cin is used in collecting user input
* and assigning it to a variable.
*/
cin>>num1;
cout<<"Enter a second integer value: ";
cin>>num2;
cout<<"S\The sum of in[utted values is: "<<(num1+num2);
return 0;
}
Yield:
Enter first integer value: 15
Enter second integer number: 25
Sum of entered numbers is: 40
C++ Program To Add Two Numbers Utilizing Function Overloading
In this model, you see how to add two numbers utilizing function
overloading. Function overloading is an element that enables you to have
more than one function having the same name; however unique number, sort
of succession of arguments. Here you are characterizing three functions for a
similar reason addition; in view of the data type of arguments, the diverse
function is called.
Yield:
Enter two integer numbers: 34 99
Yield: 133
Enter two float numbers: 15.4 43.7
Yield: 59.1
Enter an int and a float number: 28 34.8
Yield: 62.8
#include <iostream>
using namespace std;
class Add{
public:
/* Two variables that will be
* added. To find the sum of a double variable or float
* instead, try changing the data
* type. For instance: the float numX, numY;
*/
int numX, numY;
Yield:
Enter first number: 35
Enter second number: 25
60
You might be asking why the sum function is called from the main()
function; this is because the sum function is called from the show() function.
#include <iostream>
return 0;
}
Yield:
Real part: 13
Imaginary part: 5
abs() – It gives the absolute of the complex number.
arg() – It gives the argument of the complex number.
#include <iostream>
int main ()
{
cout << "The absolute value of " << complexval<< " is: ";
cout << "The argument of " << complexval<< " is: ";
Output:
The argument of (4,3) is: 0.927295
The absolute value of (4,3) is: 5
#include <iostream>
// std::complexval, std::polar
#include <complexval>
// driver function
int main ()
{
cout << 'The complexval with a magnitude of ' << 2.0;
// use of polar()
cout << ' is ' << polar (2.0, 0.5) << endl;
return 0;
}
Yield:
The complex with a magnitude of 2 and phase angle is 0.5 is
(0.999961,0.008727)
complex-2
#include <iostream>
// driver function
int main ()
{
// use of norm()
cout << "The norm of " << complexval << " is "
return 0;
}
Yield:
The norm of (4,3) is 25.
#include <iostream>
using namespace std;
// std::complex, std::conj
#include <complex>
// driver program
int main ()
{
// use of conj()
cout << conj(complexval) << endl;
return 0;
}
Yield:
The conjugate of the operands (10,2) is (10,-2)
#include <iostream>
// driver program
int main()
{
std::complex<double> c1(1, 2);
cout << "proj" << c1 << " = " << proj(c1) << endl;
cout << "proj" << c2 << " = " << proj(c2) << endl;
cout << "proj" << c3 << " = " << proj(c3) << endl;
}
Yield:
proj(1,2) = (1,2)
proj(inf,-1) = (inf,-0)
proj(0,-inf) = (inf,-0)
sqrt() – Gives the square root of x utilizing the main branch, whose
cuts are along the negative real axis.
#include <iostream>
<< "The square root of (-25,-0), the other side of the operation, is "
Yield:
The square root of -25 is (0,5)
The square root of (-25,-0), the other side of the operation, is (0,-5)
#include <iostream>
// driver program
int main ()
{
// use of log()
cout << "The log of the" << complexval << " is "
return 0;
}
Yield:
The log of (-1,2) is (0,0.3010)
#include <iostream>
// driver program
int main ()
{
// use of cos()
cout << "Cos of " << mycomplex << " is given as "
// use of tan()
cout << "Tan of " << mycomplex << " is given as "
return 0;
}
Yield:
Cos of (0,1) is given as (1, 0.99985)
Tan of (0,1) is given as (0, 0.01746)
Sin of (0,1) is given as (0, 0.01745)
cosh(z)=(e^z+e^(- z))/2
sinh(z)=(e^z-e^(- z))/2.
tanh(z)=(e^(2z)- 1)/(e^(2z)+1)
/utilization of tanh(),cosh(),sinh()
#include <iostream>
#include <cmath>
// For the std::complex
#include <complex>
int main()
{
// x = i + 0j
Exercise 10:
1. What data types are used in numbers operations?
2. How does the complex library work?
3. How does the double cos(double) work?
Chapter Eleven
Arrays in C++
There are different ways which we can declare an array. It can be declared by
determining its type and size, by initializing it or both.
int arr1[5];
Model:
#include <iostream>
int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3] = arr[0];
<< " " << arr[2] << " " << arr[3];
return 0;
}
Yield:
5 2 -10 5
No Index Out of bound Checking:
There is no file outside the field of play checking in C++. For instance, the
accompanying system gathers fine; however, it may deliver unforeseen
output when run.
// This C++ program compiles fine
// as index out of bound
// is not checked in C.
#include <iostream>
int main()
{
int arr[2];
return 0;
}
Output:
2008101287 4195777
#include <stdio.h>
int main()
{
return 0;
}
Warning:
Note: The program won't compile in C++. On the off chance that we spare
the above program as a .cpp, the program creates compiler error "error: too
many initializers for 'int [2]'".
Model:
// A C++ sample program to show that the elements in an array
// can be stored in contiguous locations
#include <iostream>
int main()
{
int main()
{
vector<int> x1;
for (int i = 1; i <= 5; i++)
x1.push_back(i);
cout << "The yield of begin and end is: ";
for (auto i = x1.begin(); i != x1.end(); ++i)
cout << *i << " ";
cout << "\nThe yield of cbegin and cend is: ";
return 0;
}
Output:
The yield of begin and end is: 1 2 3 4 5
The yield of cbegin and cend is: 1 2 3 4 5
The yield of rbegin and rend is: 5 4 3 2 1
The yield of crbegin and crend is: 5 4 3 2 1
Capacity
#include <iostream>
#include <vector>
int main()
{
vector<int> x1;
g1.push_back(i);
if (x1.empty() == false)
else
x1.shrink_to_fit();
return 0;
}
Output:
Size : 5
Capacity : 8
Max_Size : 4611686018427387903
Size : 4
Vector is not empty
Component access:
#include <bits/stdc++.h>
int main()
{
vector<int> g1;
for (int i = 1; i <= 10; i++)
g1.push_back(i * 10);
cout << "\nReference operator [g] : g1[2] = " << g1[2];
return 0;
}
Output:
Reference operator [g] : g1[2] = 30
at : g1.at(4) = 50
front() : g1.front() = 10
back() : g1.back() = 100
The first element is 10
Modifiers:
int main()
{
// Assign vector
vector<int> v;
v.push_back(15);
int n = v.size();
cout << "\nThe last element is: " << v[n - 1];
// removes last element
v.pop_back();
// prints the vector
v.insert(v.begin(), 5);
v.erase(v.begin());
v.emplace_back(20);
n = v.size();
cout << "\nThe last element is: " << v[n - 1];
v.clear();
v1.push_back(1);
v1.push_back(2);
v2.push_back(3);
v2.push_back(4);
// Swaps v1 and v2
v1.swap(v2);
Vector 1: 1 2
Vector 2: 3 4
After Swap
Vector 1: 3 4
Vector 2: 1 2
All Vector Functions :
Exercise 11:
1. How does array differ from pointers?
2. What is the function of the insert() modifier?
3. How are arrays declared?
Chapter Twelve
Strings
C++ has, in its definition, an approach to speak to a succession of characters
as an object or class. This class is called std:: string. String class stores the
characters as a grouping of bytes with usefulness in enabling access to a
single-byte character.
Input Functions/Capacities
1. getline():- This capacity is utilized to store a stream of characters as
entered by the user in the object memory.
2. push_back():- This capacity is utilized to enter a character toward the
finish of a string.
3. pop_back():- This function came as anew addition in C++11(for strings);
this capacity is utilized to erase the last character from the string.
Here is an example of how these three work:
// Displaying string
cout << "The string after push_back operation is : ";
cout << str << endl;
// Using pop_back() to delete a character
// from end
// pops 's' in this case
str.pop_back();
// Displaying string
cout << "The string after pop_back operation is : ";
cout << str << endl;
return 0;
Input:
ThisBook
Yield:
The underlying string is : thisbook
The string after push_back activity is: thisbook
The string after pop_back activity is: thisbook
Capacity Functions
// Displaying string
cout << "The initial string is : ";
cout << str << endl;
// Displaying string
cout << "The string after resize operation is : ";
cout << str << endl;
// Displaying string
cout << "The new capacity after shrinking is : ";
cout << str.capacity() << endl;
return 0;
Yield:
Iterator Functions/Capacity
// Declaring iterator
std::string::iterator it;
// Displaying string
cout << "The string using forward iterators is : ";
for (it=str.begin(); it!=str.end(); it++)
cout << *it;
cout << endl;
Yield:
The string using forward iterators is: thisbook
The reverse string using reverse iterators is: koobsiht
Manipulating Functions/Capacity
return 0;
Yield:
The new copied character array is: thisband
The 1st string before swapping is: thisband is for all
The 2nd string before swapping is: thisband rocks
The 1st string after swapping is: thisband rocks
The 2nd string after swapping is: thisband is for all
In this segment, the subsequent strategy is talked about. String class is a piece
of C++ library that supports a whole lot more functionality than C style
strings.
C++ string class inside uses char array to store character, yet all memory
management, portioning, and null end is taken care of by string class itself.
That is the reason it is anything but difficult to utilize. The length of a string
in C++ can be altered during runtime, given the dynamic assignment of
memory, such as vectors. Since a string class is a container class, we can
repeat over the entirety of its characters utilizing an iterator like different
compartments such as vector, set, and maps. Yet, for the most part, we utilize
a basic loop for emphasizing the characters and index them utilizing []
operator.
C++ string class has plenty of capacities to deal with string effectively. The
most valuable of them are exhibited in the code below.
int main()
{
// the different constructors of a string class
// initializing through raw strings
string str5("first string");
// would clear the function and delete all characters from the string
str4.clear();
// both the size() and length() functions return the lengths of the strings and
// they work in conjunction
int len = str10.length(); // Similar to "len = str10.size();"
cout << "Length of the string is given as: " << len << endl;
cout << 'the third character of string is given as: ' << ch << endl;
// the front returns the first character while the back returns the last
character
// of the string
cout << "The first char is given as : " << ch_f << ", the last char is given as:
"
<< ch_b << endl;
// the c_str returns as a null and terminated char array version of the string
const char* charstr = str10.c_str();
printf('%s\n', charstr);
if (str10.find(str8) != string::npos)
cout << "str8 found in str10 at " << str10.find(str8)
<< ' pos' << endl;
else
cout << "str8 not found in str10" << endl;
return 0;
}
The output is as follows:
first string
first string
#####
string
first
Length of string is given as : 6
the third character of the string is given as : r
First char is given as: Last char is given as : g
string
string extension
string
str4 found in str6 at 0 pos
ext
extension
string nsion
strinion
Applications
On premise of above string capacity some applications are composed
underneath :
return 0;
}
Yield :
Floating part is : 342
string contains only digit
google%20com%20in
return 0;
}
• find(“string”): This function is used to search a string for the first event of
the substring determined in arguments. It restores the situation of the main
event of a substring.
• find_first_of(“string”): This function is used to search a string for the
primary character that matches any of the characters indicated in its
arguments. It restores the situation of the primary character that matches.
• find_last_of(“string”): Searches the string for the last character that matches
any of the characters indicated in its arguments. It restores the situation of the
last character that matches.
• rfind(“string”): Searches the string for the last event of the substring
indicated in arguments. It restores the situation of the last event of a
substring.
// C++ program to demonstrate working of find(),
// rfind(),find_first_of() and find_last_of()
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str("This Book");
return 0;
Yield:
return 0;
}
Yield:
Bookfor
ThisBook
clear(): This capacity clears every character from the string. The
string gets vacant (length gets 0) after this activity.
void(): It tests whether the string is vacant, and returns a Boolean worth.
return 0;
}
Yield:
String is empty
Language structure:
Model:
int main()
{
// Initialize 2D array
char color[4][10] = { "Blue", "Red", "Orange",
"Yellow" };
return 0;
}
Yield:
Blue
Red
Orange
Yellow
Downside:
• Both the number of Strings and Size of String are fixed.
• A 2D exhibit is designated, whose subsequent measurement is equivalent to
the highest estimated string, which causes wastage of room.
2. Utilizing string Keyword (Only in C++): In this strategy, the size of the
string isn’t fixed; thus, space is spared.
Language structure:
Model:
String book[50]
// C++ program to demonstrate array of strings using
// array of strings.
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Initialize String Array
string color[4] = { "Blue", "Red",
"Orange", "Yellow" };
// Print Strings
for (int i = 0; i < 4; i++)
cout << color[i] << "\n";
}
Yield:
Blue
Red
Orange
Yellow
Downside: The array is of fixed size.
Language structure:
Vector “Name”
Model:
Vector Color
// C++ program to demonstrate vector of strings using
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Declaring Vector of String type
vector<string> color;
Out of all the three strategies, a vector is by all accounts an ideal path for
making an array of Strings in C++.
Exercise 12:
1. What is the purpose of the find_last_of(“string”) function?
2. Distinguish between a vahravyer and
3. How is string concatenation performed in C++?
Answers
Answers (Exercise 1):
1. Crude data types, such as int, short, long, float and double, are used
for Numbers operations.
2. It actualizes the complex class to contain complex numbers in
cartesian structure and several functions and overloads to work with
them.
This function takes an angle (as a double) and gives you the cosine.
Answers (Exercise 11):
1. The confusion happens because the array name shows the address of
the first element, and arrays are passed continuously as pointers
(regardless of whether we utilize square brackets).
2. insert() – It embeds new components before the component at the
predefined position
3. They can be declared by determining their types and sizes, by
initializing, or both.
Answers (Exercise 12):
1. It searches the string for the last character that matches any of the
characters indicated in its arguments.
2. The fundamental contrast between character array and a string is if
there should be an occurrence of a character array, the size must be
allocated at the hour of assertion, i.e., all memory once allotted is
fixed and can’t be changed at run time. Though, for string, there is
no compelling reason to determine the size and to assign fixed
memory at the hour of affirmation.
3. A string can be concatenated to another string by += or by attach().
Conclusion
I hope that this book has been beneficial to you.
Remember that coding is a continuous process. You need to keep at it to
become better at it. Don’t feel discouraged if you run into ruts. Keep at it, and
you would become better. You can always refer to this book for the help that
you need.