0% found this document useful (0 votes)
700 views

Computer Programming - 4 Books in 1 - The Ultimate Crash Course To Learn Python, SQL, PHP and C++

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.

Uploaded by

Shafi Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
700 views

Computer Programming - 4 Books in 1 - The Ultimate Crash Course To Learn Python, SQL, PHP and C++

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.

Uploaded by

Shafi Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 529

COMPUTER PROGRAMMING:

This Book Includes: 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:

Python : The Ultimate Crash Course for Data Analysis, Machine


Learning and Data Science, with Practical Computer Coding
Exercises.

SQL: The Ultimate Crash Course for Data Base Management,


Queries Server with Practical Computer Coding Exercises

PHP: The Ultimate Crash Course to Learn PHP with Practical


Computer Coding Exercises

C++: The Ultimate Crash Course to Learn C ++ with Practical


Computer Coding Exercises
PYTHON:
The Ultimate Crash Course for Data Analysis,
Machine Learning and Data Science, with Practical
Computer Coding Exercises.

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.

How Python Started


Python programming began at the fingertips of a Dutch programmer, name of
Guido Van Rossum. He wrote the program sometime in the latter period of
the ’80s as a hobby project. Since its release to the public, Python has grown
and evolved over time to be one of the most acclaimed, polished, and
consistent languages in the world of computer programming.
According to Van Rossum, the conception of Python can be traced to a
Christmas weekend in December 1989. He had begun working on his hobby
project in his free time to develop an interpreter language—a successor to the
ABC programming language to which Van Rossum helped develop.
However, when the entire process of development came to an end, Python
emerged as nothing short of a complete programming language in itself.
Given its somewhat already weird history, the name “Python” draws even
more questions to the identity of the programming language. Van Rossum
had the Unix and C hackers as the target audience of his program, but more
importantly, he was especially keen on the then famous TV sitcom—The
Monty Python’s Flying Circus. Van Rossum explained that he found the
name “Python” not only suitable to his taste but appealing to his target
audience, so he ran with it.
Properties of Python Programming Language
Python is a dynamically and implicitly typed language in itself, so you are
not required to declare variables while coding. The datatypes in Python are
enforced, and its variables are sensitive to case. As a result, VALUE and
value are processed as two distinct variable types. Furthermore, there are no
set out characters used in terminating statements or commands. Every block
of code is specified with an indentation. As such, at the beginning of a block
of code, an indent is introduced, and a de-dent is used at the end. Statements
that require a level of indentation are terminated using a colon (:). To add
comments, the hash (#) is used in each line. For multiple line strings, they are
used in multi-line comments. To assign values to variables, the equal to (=) is
used, while the double equal to (==) signs are used in testing for equality.
Increment and decrement can be performed on values using the operators
(+=) and (-=), respectively, with the amount placed on the right-hand side of
the operator. Such operations can be performed on strings and several other
data types. Other properties of Python are discussed below:

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.

The productivity of developers:


The coding style in Python is both elegant and clean. Its syntax is also very
similar to regular English, and it is dynamically typed. With this, a variable
declaration isn’t required as one simple assignment can assign a name to an
object of any datatype. Python also features significantly fewer codes than
other contemporary languages, such as Java and C++, meaning it can be
easily written, debugged, and maintained. Python programs, contrary to other
compiled languages, don’t require to be linked and compiled, further
increasing the productivity of developers.
Portability of code:
Since the nature of Python puts it as an interpreted language, its interpreter is
charged with the responsibility of portability. Also, the interpreter in Python
is capable of producing a single output across many different platforms. As a
result, it isn’t necessary to modify codes when switching across platforms.

Extensive libraries (built-in and external):


Python features an extensive collection of both built-in and portable set
libraries. These libraries can be loaded anytime for the use of any constituent
functionality.

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.

Freedom of use, modification, and redistribution:


Python is an open-source software (OSS), meaning it is free to use by the
public, makes amendments in its source codes, and can be redistributed even
for commercial use. This level of openness is what has attracted a large and
ever-growing community user base to Python.

Object-oriented programming at its core:


Python’s structure is flawlessly in tune with the designs of OOP (object-
oriented programming). OOP enables developers to use an intuitive method
to structure their codes, and a good understanding of the basic underlying
concepts allows users to make the most of their codes. With object-oriented
programming, it is relatively easier to picture a complex problem as much
smaller flows with defining objects and their method of correlation. At this
point, the correct logic to make the code work is actualized.
The Benefits Of Learning Python Programming
Coding in Python is straightforward and promises a fun experience that beats
basic routine programming. Below are some benefits of learning to code with
Python:

Easier and better debugging:


Debugging refers to a process of searching for bugs and defects and resolving
them. These bugs and errors tend to inhibit a program or system from
working correctly. In this vein, debugging aims to resolve problems in
programs. In terms of debugging, Python is one of the highest-ranking
programming languages owing to the tools it provides, such as PyDebug,
pudb, and pdb, which help make the debugging experience smooth and
manageable.
Take, for instance, the tool—pudb can help programmers analyze the core of
codes and track down a problem. When compared, while other languages
keep working to improve their debugging experiences and tools, Python only
gets better with time.

There are no restrictions to its programming syntax:


Unlike other programming languages, Python can be easily understood by
anyone, even up to a non-programmer. The reason is primarily attributed to
its high readability and problem-oriented design, which lets one pay attention
to coding logically rather than expressly delving into the nitty-gritty of the
syntax.
As proof of this unique benefit, consider the sample program shown below to
calculate a simple interest.

print('Simple Interest Calculator:')


amount = float(input('Value of Principal ?'))
roi = float(input('Rate of Interest ?'))
time = int(input('Duration (no. of years) ?'))
total = (amount * pow(1 + (roi/100), time)
interest = total - amount
print('\nInterest = %0.2f' %interest)

Taking a look at the program, you can note how relatively easy it is to decode
and write the code in Python.

An explicit declaration is not required:


When coding in Python, type specifiers should not be used in the declaration
of variables because it can be done without declaring any of the data types in
Python. Additionally, it is unnecessary to make use of separators, such as
semicolons (;) in marking the end of a statement or command. Indentation in
Python takes the place of parenthesis in grouping a block of code. And to
make indentations in codes, you can make use of either spaces or tabs. Albeit,
some rules are enforced in Python, like the use of four spaces for each level
of indentation. Many other facets of Python, such as this contribute to making
learning easier for beginners.

Great Object-oriented programming support:


OOP (Object-oriented programming) comes as a built-in element in Python.
It creates a model that produces solutions by devising objects, binding data,
and defining connections. Albeit, the procedural programming methodology
takes a different approach from top to bottom, solving one problem at once
and splitting it into bit sizes. Object-oriented programming, on the one hand,
is a different ball game altogether. It adopts a bottom to top problem-solving
approach that looks for blueprints to the solution from the onset, thereby
leaving implementation to a much later time.
To develop yourself as a professional Python programmer, constructing
objects, building inheritance, and using classes are fundamental approaches
to take. What’s more, is that these concepts can be easily mastered in Python
for the production of quality programs with quicker implementations than
other programming languages. Python encourages minimalism in code sizes,
allowing for faster and better applications.
How To Set-Up Python On Your PC:
Python codes are independent of platforms, meaning they can be written on
just about any platform and executed on any other supported platform. In this
section, we concentrate on setting up Python on three popular PC platforms,
namely Windows, Linux, and Mac OS.

How to set up Python on Mac OS X:


As at the time of this writing, High Sierra (10.13) is the latest version of Mac
OS X known, and it comes pre-installed with Python. For beginners, Python
2 could suffice to learn the basics of the program. Professionals, however,
should use the latest version 3.6 of Python.
To set up Python on a Mac system, begin by installing the program. Visit the
Python page slated for downloading Mac OS X-related software. Click on
your preferred package to download. Once completed, initiate the launch
sequence on the downloaded file. Follow the succeeding steps to complete
the installation process.
If you would rather use the command-line or prefer to use consoles in
performing routine system tasks, you can execute the commands shown
below to install Python:
Start by opening the terminal environment and installing a HomeBrew
package manager for your Mac OS X.
$ ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install)"
Type in the command shown below to find out the status of the Brew
installation:
$ brew –version
Having successfully ascertained the availability of the Brew installation, use
the Brew package manager initiate the installation process Python 3.x:
$ brew install python3
When you install Python using Brew on Mac OS X, you indirectly install the
PIP tool, in this case, pip3. PIP serves as an update manager for checking the
availability of modules in your Python repository.

How to execute the Python program:


Having already concluded the installation of the Python package, it is time to
set up a Python environment for coding. For a more professional code
development, you might want to use an IDE (Integrated Development
Environment) for better efficiency and productivity. Eclipse with PyDev and
the community version of PyCharm are the most advisable IDEs, as they are
both free and come with useful features.
If you’d rather not trifle with IDEs, you can stick to the default, built-in IDE
that comes with the Python package—IDLE. Also, the Python console can be
used to execute your first few codes. And since it’s Python, there is a lot that
can be done with just a single block of code. Take, for instance; you could
create a function that searches for odd numbers, call it using an input, and
print out the outcome, all with one single line of code. See the sample code
below:
print((lambda isOdd: isOdd(3))(lambda x: x % 2 != 0))
When the code above is entered into a Python CLI, it would require an enter
key to run. Albeit, when you make use of IDLE, you can easily run it using
the key F5. Either way, it is done; the code outputs the value “True.”

How to set up Python on a Linux (Ubuntu) PC:


In version 16.04 of Ubuntu, both Python 2 and 3 are pre-installed packages.
Albeit for better performance, it is recommended of you to verify how up-to-
date they are. To do this, you need to use the apt-get commands shown
below:
$ sudo apt-get update
$ sudo apt-get -y upgrade

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

If you wish to create Python projects in a different space or want to allow


room for creativity in a different set-up, you can create an isolated space on
your PC. To do this, you need the venv (virtual environment) module. You
can find it as a component of the standard library in Python 3. To install
venv, use the command shown below:
$ sudo apt-get install -y python3-venv

How to execute Python on Linux systems:


To run Python on Linux systems, you have to begin by creating a Python
environment. To do this, enter the following lines of code:
$ mkdir environments
$ cd environments
$ python3 -m venvtest_env
To make use of the <test_env> environment, you first have to activate it
using the command shown below:
$ source test_env/bin/activate

At this point, your prompt may differ a little from a standard prompt.
(test_env) pythonforbeginners@pythonforbeginners:~/environments$

The prefix here is an indication of the activation of the environment test_env.


You can now set-up programs to make use of the packages and settings in the
environment.

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

The output should be as follows:


Hello, World!

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.

How to run Python packages on Windows systems:


Having concluded the installation process, it’s time to begin setting up an
environment for coding. As was mentioned in earlier parts of this discussion,
for better development, a professional IDE is required. Albeit, since it’s the
beginning stages, you can use the default text editor on Python—IDLE.

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.

How To Create A Simple Python Program?


Once the set-up is complete, the next step is to begin creating Python scripts.
For beginners, the first program is usually the traditional Hello World script.
This program is used across almost every programming language known and
has become cliché with time. Plus, the program just prints “Hello, World!” as
standard output. There is hardly anything challenging about it. And for a
language with vast potentials like Python, it seems rather trivial. So, to offer
beginners a better challenge and help them learn faster, we focus on creating
an interest calculator program.
This is how it will look:
The program is used to calculate accrued interest on a specific principal value
over a given number of years, with one year given as the fixed value of the
compound interval.
The source code of the program is shown below:
print('Interest Calculator Program:')
amount = float(input('Principal value ?'))
roi = float(input('Rate of Interest ?'))
time = int(input(Timeframe (no. of years) ?'))
total = (value * pow(1 + (roi/100), time))
interest = total - value
print('\nInterest = %0.2f' %interest)

Here is a step by step explanation of the source code below:


Step one:
The function print() is used in the opening line to output an informative
message. The first line prints as an “Interest Calculator Program” in the same
way as the Hello World program discussed earlier.

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;

P is the Principal value (Original investment)


R represents the annual nominal interest rate (as a decimal)
N is the number of times the interest gets compounded every year
T is the number of years
Also, the assignment process involves using the following functions and
operators peculiar to Python:

Addition operator (+): It is an operator used to find the sum of


operands.
Multiplication operator (*): It is an operator used in multiplying two
or more operands.
Division operator (/): It is used in dividing the operand on the left
hand by the operand on the right.
pow(A, B, C): This operator is used to find [A to the power of B].
And should Z be available, it proceeds to return A to the power B,
modulo C].
Step Four:
Moving to the sixth line, notice the subtraction operator (-) is introduced into
the fray to calculate the difference and obtain the Interest value.
Step Five:
In conclusion, a print statement showing the interest amount is introduced.
Since the value is not a float number, the function print() outputs the entire
length of the number by default. As such, we must define or limit output. To
do this, we introduce the floating-point format specifier to the print()
function. Here, we used (%0.2f), meaning two decimal points.
Exercise 1:

1. What was Guido van Rossum’s initial plan for Python?


2. What does Python being an open-source software mean?
3. What is used to add comments in Python?
Chapter Two
Types of Variables
In Python, variables refer to the reserved memory locations used in storing
values. That is, whenever you attempt to create a variable, you automatically
reserve a certain amount of space in the program’s memory. Variables could
be of any data type indeed, so, the Python interpreter performs memory
allocations based on the data type assigned to a variable, and determines what
would be stored in the allotted memory. As a result, by assigning variables
several data types, you are able to store characters, decimals, integers, and so
on in them.
How Values Are Assigned To Variables
Recall from earlier parts of this text that Python’s characteristic simplicity
can be traced to its negligence towards declaring variables. Well, here’s why.
The variables in Python don’t have to be explicitly declared to reserve a
space in the memory. The declaration process is simple and automatic. A
variable is assigned a value using the sign of equality (=), and that is just
about that. The operand occupying the left-hand side of the equal to (=)
operator serves as the name given to the variable, while the operand on the
right-hand side is the value being stored in or assigned to the variable.
Take the sample below, for instance:
#!/pythonforbeginners/bin/python

mark = 500 # An integer assignment


distance = 3000.0 # A floating point
name = "Jane" # A string

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

Multiple Variable Assignments:


In Python, it is possible to assign multiple variables to one single value
simultaneously. Check out the sample below for better understanding:
i = j = k = 50
In the sample above, an integer object is created using the value “50.” Given
how there are three variables assigned to the same value, all would be stored
in the same location in the program’s memory. Asides values, it is possible to
assign more than one object to more than one variable. Check the sample
below:
x,y,z = 5,10,"happy"
In this case, each object is assigned to a corresponding variable on the left.
That is, variables x and y are assigned the values 5 and 10, respectively,
while the variable z is assigned the string object containing the value
“happy.”

Data Types in Python


The data that is stored in the memory of the program can come in many
different forms. Take, for instance; we decide to register and store the details
of a customer. The age of the customer would be saved as a numeric value
while their purchases would be stored as alphanumeric characters. There are
five standard data types used in Python to define the possible operations they
could be used in, as well as the perfect storage method that fits each one of
them. The five standard data types include the following:

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

When this sample code is executed, it produces the following results:


Welcome to Python!
W
com
ome to Python!
Welcome to Python!Welcome to Python!Welcome to Python!
Welcome to Python!YAY!
Lists in Python
In Python, lists serve as the most versatile of all the compound data types.
Lists are made up of items enclosed within square braces ([]) and separated
using commas. To a degree, lists in Python are quite similar to the arrays in
the C programming language. The only distinguishing factor between both is
that all the items that make up a list can be of several different data types. To
access the values that make up a list, the slice operator ([:]) and ([]) is used
with indexes beginning at 0 from the starting of the string and working their
way from -1 at the terminal point. Like with strings, the sign of addition (+) is
an operator used in list concatenation, and the asterisk (*) is known as the
repetition operator. Check out the sample below:
#!/pythonforbeginners/bin/python
list = [ “ijkl”, 419 , 3.14, 'xena', 22.7 ]
smalllist = [789, ‘data’]

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from second till third
print list[2:] # Prints elements starting from the third element
print smalllist * 2 # Prints list two times
print list + smalllist # Prints concatenated lists

When this sample code is executed, the result is as follows:


[ “ijkl”, 419 , 3.14, 'xena', 22.7 ]
ijkl
[419, 3.14]
[3.14, 'xena', 22.7]
[789, ‘data’, 789, ‘data’]
[“ijkl”, 419 , 3.14, 'xena', 22.7, 789, ‘data’]

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

When this sample code is executed, the result is as follows:


(“ijkl”, 419 , 3.14, 'xena', 22.7)
ijkl
(419, 3.14)
(3.14, 'xena', 22.7)
(789, ‘data’, 789, ‘data’)
(“ijkl”, 419 , 3.14, 'xena', 22.7, 789, ‘data’)
The second sample shown below is of an invalid code because an attempt
was made to update the tuple. Recall that tuples cannot be updated or
modified. However, a similar case can be performed on lists:
#!/pythonforbeginners/bin/python
tuple = ( “ijkl”, 419 , 3.14, 'xena', 22.7 )
list = [ “ijkl”, 419 , 3.14, 'xena', 22.7 ]
tuple[3] = 4000 # Invalid syntax with tuple
list[3] = 4000 # Valid syntax with list

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"

smalldict = {‘customer’: ‘drery’, 'amount':5000, ‘item’: 'shoes'}

print dict['one'] # Prints value for 'one' key


print dict[2] # Prints value for 2 key
print smalldict # Prints complete dictionary
print smalldict.keys() # Prints all the keys
print smalldict.values() # Prints all the values

When the sample code is executed, it produces the following:

This is one
This is two
{‘item’: 'shoes', 'amount':5000, ‘customer’: ‘drery’}
['item', 'amount', 'customer']
[‘shoes’, 5000, 'drery']

For dictionaries, the concept of order between elements is negligible. As


such, it is incorrect to declare the elements of a dictionary as “out of order,”
as they simply exist in an unordered state.

Python Data Type Conversion


In Python, you would sometimes be required to carry out conversions
between the built-in standard data types. To do this, the name of the data type
is used as a function. Many different built-in functions can be used in
performing data type conversion. These functions return a new object that
represents the converted value.

int(a [, base]): This function is used to convert x into an integer,


while “base” depicts the base of x if it is a string.
long(a [, base]): This function is used to convert x into a long
integer, while “base” represents the base of x if it is a string.
float(a): This function is used in converting x into a floating-point
number.
complex(real [,imag]): This function is used in the creation of
complex numbers.
str(a): This function is used in converting the object a into a string
representation.
repr(a): This function is used in converting the object a into an
expression string.
eval(str): This function is used in performing evaluations in strings
to return objects.
tuple(j): This function is used in converting j into a tuple.
list(j): This function is used to convert j into a list.
set(j): This function turns j into a set.
dict(z): This function is used in creating a dictionary. “z” must
represent a series of (key, value) tuples.
frozenset(j): This function is used in converting j into a frozen set.
chr(a): This function is used in converting integers into characters.
unichr(a): This function is used in covering integers into Unicode
characters.
ord(a): This function is used in converting single characters to their
corresponding integer values.
hex(a): This function is used in converting integers into hexadecimal
strings.
oct(a); This function is used in converting integers into octal strings.

Exercise 2:

1. What is the relationship between variables and the memory of a


Python program?
2. Can the element of a dictionary be “out of order”? Give the reason
for your answer.
3. How are values assigned to variables in Python?
Chapter Three
Methods/Functions in Python
Functions refer to reusable or independent blocks of codes that can be called
from any point in a program multiple times. They are a core took in
programming required for breaking down large programs into smaller and
simpler modules. Functions serve as one of the foundational pieces of all
programming languages, and a tool every programmer must learn to utilize.
In Python, there are many different built-in methods or functions users can
work with, although it is also possible to define custom functions.
The functions in Python serve as logical units of codes made up of a series of
commands indented under specific names. These names are assigned to the
functions using the keyword “def.” functions enable users to devise logical
divisions of extensive data into simpler forms, making coding more
extensible, manageable, and straightforward. During programming, functions
inhibit users from introducing duplicate codes into a program by error and
allows for better reusability of code.

Creating Functions in Python

Syntax:
Functions in Python usually follow after this syntax:

For single line functions, the syntax is as follows:


defsingle_line(): statement
For functions containing document strings (do strings):
deffn(arg1, arg2,...):
"""docstring"""
statementa
statement
Nested Python function:
deffn(arga, argb,...):
"""docstring"""
statementa
statementb
deffn_new(arga, argb,...):
statementa
statementb
...
...
Before proceeding to create your first custom function in Python, it is
recommended for you to understand the basic concepts of functions. They
include:

The def keyword:


In Python, the “def” statement or keyword is used in defining functions.
Hence, every function ought to begin using the def keyword, after which a
specified name and a colon (:) is added. The function of the “def” keyword is
to create a function object and assign the specified name to it. In further
operations, it is possible to assign other names to the same function object.
When naming your function, use a distinct name, and only add definitive do
strings which describe the purpose of the function. However, this step is
optional.
Begin creating the body of the function by introducing valid commands in
Python into the fray. Remember to use a proper indentation of four spaces. At
this point, it is possible to introduce a statement for returning values at the
terminal point of the function. This step, however, is optional, too. Click on
the enter key and clear the indentation to terminate the function. As the “def”
keyword is a statement, it can be introduced at any point within a program,
from within other functions to being nested within an if clause.
Consider the sample shown below:
if test:
def test(): # First definition
...
else:
def test(): # Alternate definition
...
...

Calling Python Functions


When the def statement is used, it creates the blueprint for a function with
elements such as a body with valid Python commands, a name, and
parameters to pass. The ensuing step after the creation of a function is the
execution. This step can be carried out by calling the function from within a
Python program, or a function, or even directly from the Python shell itself.
To call a function, its name, as well as other valid parameters, have to be
specified.
Polymorphism of Python functions
Polymorphism in functions is a possible operation in Python because no
argument types were specified during the creation process of the functions.
How a function behaves tends to vary based on the arguments it receives. A
single function can receive several arguments of varying object types. And
when the objects locate a matching interface, they are processed by the
function. Consider the example shown below:
def product(a, b) : return a * b
print(product(5, 8)) # function returns 40
print(product('Hello!', 2)) # function returns
# Hello!Hello!
print(product('Hello 2 or 3?', '3')) # TypeError occurs

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:

An argument only gets assigned to a local variable name after it’s


been passed to a function.
Modifying the value of arguments within a function does not affect
the caller.
Should the argument contain a mutable object, then altering it within
a function would affect the caller.
Pass by Value is a term used to describe the process of passing
immutable arguments since Python doesn’t support them changing in
place.
In Python, Pass by Pointer refers to the process of passing mutable
arguments since they are susceptible to being affected by any
changes made within a function.

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

fn(answer=xyz) # output => xyz


fn(answer="Python!") # output => Python!
When making use of keyword arguments, keep in mind that the name used in
the assignment process ought to match the one used in the function definition.
Otherwise, a TypeError would be thrown upon execution if the code as in the
sample below:
fn(answer5="Python!") # wrong name used in the keyword argument
The function call shown above triggers the error shown below:
TypeError: fn() got an unexpected keyword argument 'answer5'

Default Values in Arguments:


Functions in Python allow default values to be assigned to parameters within
the function definition. These values are known as default arguments.
The callee in a function makes use of these default values anytime the caller
fails to pass them within the function call. The sample analyzed below lends
clarity to the idea behind default arguments:
defdaysInYear(is_leap_year=False):
if not is_leap_year:
print("365 days")
else:
print("366 days")
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

inventory('Kitchenware', 'kettle', 'cooker', 'pot', 'refrigerator', ‘pans’)


inventory(‘Texts’, 'heat', 'physics', ‘wave’, 'history')
When this code is executed, the output is as follows:
Kitchenware [items=5]: ('kettle', 'cooker', 'pot', 'refrigerator', ‘pans’)
- kettle
- cooker
- pot
- refrigerator
- pans
Books [items=4]: ('heat', 'physics', ‘wave’, 'history')
- heat
- physics
- wave
- history
Keep in mind that the choice of having or excluding a formal argument
within a function definition, as well as other variable arguments is totally up
to you. You could choose to skip a variable argument and call the function. In
that case, the tuple stays empty.

Local Variables within A Function:


The visibility of a local variable exists within a block of code, like the
function def keyword. Local variables are only available during the execution
process of a function. Consider the sample below on how local variables are
used:
deffn(x, y) :
temp = 1
for iter in range(y) :
temp = temp*x
return temp

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.

Global Variables within A Function:


In Python, the global keyword refers to a statement that allows variables
(names) to maintain modifications made outside of a def statement and at the
top level of a module file. With one global statement, it is possible to specify
one or multiple names separated using commas. Every listed name is attached
to the scope of the enclosing module when referenced or assigned within the
body of a function.
Consider the sample below:
i=2
j = 22
deffn() :
global x
i = [5, 9]
j = [2, 44, 66]
# a local ‘j’ is assigned and created here
# whereas, ‘i’ refers to the global name
fn()
print(i, j)
In the code sample above, the global variable is 'i' and retains every change
made to its value within the function. The second variable, 'j,' has a local
slope, and is thus unable to retain the changes made.
Let’s take a look at another sample analyzing how a globally declared name
performs in different functions:
foo = 66

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)

Return Values in Python Functions:


The “return” statement is used in Python for returning a value. In a typical
case, the function only returns a sole value. However, on the requirement,
Python supports the returning of multiple values through the use of collection
types like using a list or tuple. This feature works similarly to the
“call_by_reference” command, meaning it returns tuples and proceeds to
assign the results again to the initial argument names within the caller.
defreturnDemo(valx,valy) :
valx = 'Ubuntu'
valy = ‘Linux’
return valx, valy # return multiple values in a tuple

varx = 5
vary = [1, 3, 5, 7]

print("before return =>", varx, vary)


varx, vary = returnDemo(varx, vary)
print("after return =>", varx, vary)
The above code gives the following output.
before return => 5 [1, 3, 5, 7]
after return => Ubuntu Linux

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

Also, it is possible to pass a function object to another function:


def fn1(i, j) : print('fn1 called')
def fn2(fun, i, j) : fun(i, j)
fn2(fn1, 11, ‘aa’)
The output will be:
fn1 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)

listOfFuncs = [(fn1, "First function"), (fn2, "Second function")]


for (f, arg) in listOfFuncs : f(arg)
The output will be:
fn1 First function
fn2 Second function

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:

Addition (+): It is used in determining the sum of two operands. E.g.


i + j.
Subtraction (-): It is used in finding the difference between two
operands. E.g., x – y.
Multiplication (*): It is used in determining the product of two
operands. E.g., k * l.
Float Division (/): It is used in determining the quotient of two
operands. E.g. y / z.
Floor Division (//): It is also used in finding the quotient of two
operands, but without fractions. E.g. y // z.
Modulus (%): It is used in determining the integer remainder after
division of the left-hand operand by the right-hand operand. E.g.,
x%y.
Exponent (**): It is used to determine the product of the left-hand
operand raised to the power of the right-hand operand. E.g., i**j.
Let’s consider a sample code containing arithmetic operators:
Example-
x=8
y=3

print('Sum : ', x+y)


print('Subtraction : ', x-y)
print('Multiplication : ', x*y)
print('Division (float) : ', x/y)
print('Division (floor) : ', x//y)
print('Modulus : ', x%y)
print('Exponent : ', x**y)
Output-
Sum : 11
Subtraction : 5
Multiplication : 24
Division (float) : 2.67
Division (floor) : 2
Modulus : 5
Exponent : 512
Comparison Operators:
Comparison operators are used in Python for determining the rate of equality
between two values and decide according to the result of the equation
process. Below is an outline of the comparison operators that are found built-
in on Python.

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)

print('x != y is',x!=y)

print('x >= y is',x>=y)

print(‘x <= y is',x<=y)


When the code is executed, the result will be as follows:
x > y is True
x < y is False
x == y is False
x != b is True
x >= y is True
x <= y is False

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)

# Result: not x is False


print('not x is',noty)
Output-
x and y is 4
x or y is 7
not x is False
Bitwise Operators:
In Python, bitwise operators are used in processing certain bits of integer
values, in which they are treated as sequences of binary bits. Bitwise
operators are used in checking whether a certain bit is set. Take, for instance,
IoT applications analyze the data obtained from sensors based on a specific
bit being set or not. In a case like this, bitwise operations come to the rescue.
Below is an outline of the built-in bitwise operators in Python:

Bitwise AND (&): It is used in the comparison of two operands on a


bit level and would return 1 when both corresponding bits are 1. E.g.
x & y.
Bitwise OR (|): It is used in comparing two operands on a bit level,
returning 1 should any of the corresponding bits be 1. E.g., x | y.
Bitwise NOT (~): It is used in inverting every bit within a single
operand. E.g., ~x
Bitwise XOR (^): It is used in comparing two operands on a bit
level, returning 1 when either, but not both of the corresponding bits
are 1. E.g., x ^ y.
Right shift (>>): It is used in shifting the bits of the operand x to the
right by operand “y” number of times. E.g. x >> y.
Left shift (<<): It is used to shift the bits od operand “x” towards the
left by “y” number of times. E.g. x << y.
Let’s proceed to see a sample code using one of these operators. For the
example we’ll use the numbers 9 and 5 which are “0000001001” and
“000000101” in binary form. We will use these values in performing an
operation with the AND operator.
i=9
j=5
#Bitwise AND: The result of ‘a & b’ is 1
print(‘i& j is',i& j)
The output is as follows:
i& j is 1
The result shown above is the outcome of the AND operation outlined below:
0000001001 &
000000101
------------------
0 0 0 0 0 001 (the binary form of the number 1)

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.

(**=): 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.

(>>=): E.g. x >>= 7.


Evaluation: x = x>>7.

(<<=): E.g. x <<= 7.


Evaluation: x = x<<7.
Special Operators in Python:
In Python, asides the usual operators, there are other special operators used
for specific reasons. These operators are classified as advanced operators in
Python. They include:

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")

# Using the 'is not' identity operator


k = 3.2
if (type(k) is not int):
print("true")
else:
print("false")
The result will be as follows:
true
true

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)

The result is as follows:


True
True
True
True
False

Exercise 4:

1. What type of operators allows users to make decisions according to


several defined conditions?
2. What are operands?
3. What type of operator does the expression x | y contain? What
operator is it?
Chapter Five
Flow Control in Python
In some of the code samples we have used until now, you may notice that the
codes follow a pattern of execution that is religiously adhered to. One
prominent pattern is the top to bottom order of execution each of these codes
uses. Bringing that to light now, did you know it is possible to alter this order
of execution? Say, for instance, you want the program to make decisions on
its own, performing different actions depending on the situation that comes
up. Like printing, “Good Morning” or “Good Night” depending on the time
of day.
This is a possible feat in Python and can be achieved with the use of control
flow statements. These statements are three in number in Python, namely
while, if, and for statements. Let’s discuss each one of them briefly:

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.

When the code is executed, the result is as follows:


$ python if.py
Enter an integer : 24
No, it is a lot less low than that
The End

$ 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.

The while Statement:


Unlike the if statement, the while statement has to do with repetitions rather
than conditions. The while statement enables a user to execute a specific
block of code repeatedly for as long as a specified condition holds. While
statements are examples of looping statements because they are used to create
cycles—loops. While statements often tend to have optional else clauses.
Let’s consider the same code sample used for the if statement. This time,
though, save the file by the name “while.py”:
number = 15
running = True

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’)

When the code is executed, the result is as follows:

$ 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

How the while statement works:


In the sample code above, we attempt to create a number guessing game, with
an advantage of multiple guesses accorded to a user until the correct guess is
made. As such, it is unnecessary to run the program repeatedly for each entry
made, as was done in the if statement.
This goes to show how the while statement is used in code blocks. So, the if
statements and the input are moved into the while loop, and the variable is
passed to True before the while loop is triggered. To start, we find out
whether or not variable running is True before going ahead to process the
connected while block. After the block of code has been executed, the
condition is rechecked, which, at this point, has been assumed by the running
variable. Should it output as true, the while block is executed all over again,
else execution is started on the alternative else-block and continues to the
accompanying code block. The else block is processed when the condition of
the while loop becomes False—it could be the first time the condition would
be checked even. When a while loop comes with an else clause, it will almost
always be executed, unless a break statement is introduced to break off the
loop. As was mentioned in earlier discussions, False and True are Boolean
values, so it is safe to consider their equivalent values to be 0 and 1,
respectively.

The for Loop:


In Python, the for…in statement is a looping statement that allows users to
iterate over a sequence of objects. That is, it is used to go through every item
that makes up a sequence. Take note that a sequence refers to an ordered set
of items. Let’s consider the same code sample used for the if statement. This
time, though, save the file by the name “for.py”:

for x in range(1, 7):


print(x)
else:
print(‘The for loop is complete)
Output:
$ python for.py
1
2
3
4
5
6
The for loop is completed
How the for statement Works:
In the code sample used above, we attempt to print out a sequence of
numbers. This sequence of numbers is generated with the help of a built-in
“range” function. What we do at this point is to enter two numbers into the
program, and the “range” function returns a sequence of numbers beginning
from the initial number up to the second one. For instance, range (1,7)
produces the sequence (1, 2, 3, 4, 5, 6). In a default state, range assumes a
step count of 1. If we add a third number into the range, then it automatically
takes the place of the default step count. Take, for instance, range (1,7,2)
produces the sequence [1,3,5]. Take note that the range reaches up to the
second number, but does not include the second number itself. So, the second
number serves as a boundary the range never reaches or exceeds. Keep in
mind that the range() function only generates one number per time. So, if you
need a full set of numbers at any point, use the list() on the range() function.
For instance:
list(range(7)) will result in the sequence [0, 1, 2, 3, 4, 5, 6].
Moving on, the for loop steps in and begins iteration over the range— for x in
range(1,7) is the same as for x in [1, 2, 3, 4, 5, 6]. This case is also similar to
assigning each object or number in the sequence to x, one per time, and then
running the clock of code for every value of x. At this point, we go straight to
printing the values within the block of code. Recall that the else section of the
code remains optional. So, when it is introduced, it is only ever executed after
the for loop has been entirely executed, or until a break statement is used.
Also, recall that for..in loops work on all sequences. At this point, there is a
sequence of numbers produced from executing the range function, but it is
possible to still use any other sequence containing any type of object.

The break Statement:


The break statement in Python is applied as a breakout strategy from a loop
statement. That is, it is used to stop the running of a loop statement, even
when the condition for looping remains True, and the sequence of objects has
not undergone complete iteration. A point worth noting is that when you
apply the break statement to a while or for loop, any other alternative loop,
such as the else or elif block, remains unexecuted.
Let’s consider the same code sample used for the if statement. Save the file
by the name “break.py”:
while True:
m = input('Enter something : ')
if m == 'quit':
break
print('Length of the string is', len(m))
print('Completed')

When the code is executed, the result is as follows:


$ python break.py
Enter something: Python is easy to learn
Length of the string is 23
Enter something: When my work is over
Length of the string is 20
Enter something: You could make your work fun:
Length of the string is 29
Enter something: Hello, World!
Length of the string is 13
Enter something: quit
Completed

How the break statement Works:


In the sample code shown above, you may notice that the input of the user is
repeatedly taken, and their respective lengths are printed one at a time. Here,
a special condition is introduced to check if the input of the user is ‘quit’ and
stop the execution of the program. The program is terminated by breaking off
the loop and arriving at the end of the program.
To find out the length of the string entered by the user, the built-in function
len() is used.
The continue Statement:
In Python, the continue statement is used to inform the program to skip the
remainder of the statements yet unexecuted in the present loop block and
continue to the next loop iteration. Let’s consider a sample code of the
continue statement in use. Save the file as continue.py.

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

How the continue statement works:


In the sample code above, the input is obtained from the user, and the input is
only processed as a string of it meets the condition of having up to 5
characters in length, at least. Here, the built-in function “len” is used to obtain
the length, and should the length be less than five, the remaining commands
in the code block are skipped with the continue statement. Otherwise, the
remaining commands in the loop de processed, performing any kind of
execution programmed into the loop. Take note that the continue statement
can also be used with the for statement, too.

Exercise 5:

1. What are the three basic flow control statements in Python?


2. What system can be used to stop the running of a loop statement,
even when the condition for looping remains True, and the sequence
of objects has not undergone complete iteration?
3. What is the alternative clause added to an if statement?
Chapter Six
Class and Objects in Python
In Python, classes refer to arrangements of functions and variables within
single logical entities. They function as a template from which objects are
created. For objects, they can use the functions and variables of classes as
their members. There is a reserved keyword called “class” in Python, which
can be used in defining newer classes. Objects are working instances of
classes that are created during execution.
How Classes are Created in Python
To work with classes and objects in Python, there are specific terms you
ought to be familiar with as a result of their relative importance to this
subject. Some of those terms include the following:

The “__init__” method


The class attributes
The “class” keyword
The “self” keyword
The instance attributes
For a better understanding of these terms and how they fit into the concept of
objects and classes in Python, we discuss them briefly:

The “Class” keyword:


The class keyword makes possible the creation of Python classes within a
program. Check the code sample below for a syntax of how it works:
class BookShop:
pass

The “self” keyword:


The” self” keyword is provided in Python to play the role of the instance of a
class. It serves as a handle for gaining access to the members of a class, like
attributes from the class methods. Also, it is worth noting that in all Python
classes, the “self” keyword is implicitly the beginning argument to _ method.
The __init__ (Constructor) method:
The “__init__() method is one with a distinct association with every class in
Python. It is automatically called in Python for every object that is created
from a class. It functions to initialize the attributes of a class with values
provided by a user. Another widely known name for the __init__ method in
object-oriented programming is Constructor. Consider the code sample
below:
class BookShop:
def __init__(self):
print("__init__() constructor is called...")

B1 = BookShop()
Output
__init__() constructor is called...

The Instance Attributes:


The instance attributes refer to the parameters of the __init__ method defined
by attributes specific to objects. All objects are allowed to have distinct
values for themselves. In the sample shown below, the “attribX” and
“attribY” serve the instance attributes:
class BookShop:
def __init__(self, attribX, attribY):
self.attribX = attribX
self.attribY = attribY

The Class Attributes:


Contrary to instance, attributes that remain visible even at an object level,
class attributes maintain consistency across all objects. Consider the sample
code below, which shows how class-level attributes are used:
class BookShop:
instances = 0
def __init__(self, attribX, attribY):
self.attribX = attribX
self.attribY = attribY
BookShop.instances += 1

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

Python Class Demonstration:


At this point, we are considering an example in which we attempt to build a
<BookShop> class and instantiate its objects using varying values.
How to create the BookShop Class:
class BookShop:
noOfBooks = 0

def __init__(self, title, writer):


self.title = title
self.writer = writer
BookShop.noOfBooks += 1

defbookInfo(self):
print("Book title:", self.title)
print("Book writer:", self.writer,"\n")

# Create a virtual book shop


b1 = BookShop("Animal Farm", "George Orwell")
b2 = BookShop("Arms and the Man", "Bernard Shaw")
b3 = BookStore("Birthright", "Nora Roberts")

# call the member functions for every object


b1.bookInfo()
b2.bookInfo()
b3.bookInfo()

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

Book title: Birthright


Book author: Nora Roberts
BookShop.noOfBooks: 3
Take note that in the sample code used, we applied some of the key terms in
Python class and objects, like the “__init__” method and the “self” keyword.

Exercise 6:

1. What method is automatically called in Python for every object that


is created from a class.
2. What is the function of the class keyword?
3. What is the difference between an object and a class?

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:

timedelta: This class revolves around the intervals of time, and is


used in calculating future and past time and date objects.
Date: This class is responsible for date objects.
Info: This class is responsible for time zone information regarding
local time.
datetime: This class is responsible for the combinations of date and
time objects.
Time: This class is responsible for all-time objects.

How the Datetime Module is Implemented in Python


In creating and altering the new date and time objects, the first step revolves
around the importation of the module. The module is loaded using the
following lines of code:
import datetime
However, if you choose to have only one of the modules, use:
from datetime import date
Or
from datetime import time
Or
from datetime import datetime

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

datetime.datetime(year_number, month_number, date_number,


hours_number, minutes_number, seconds_number)
To change the format of the dates into strings that can be read by users, the
function strftime() is used within the datetime module. The timedelta()
function makes it possible to carry out calculations on date and time objects.
It can also be used in time management and planning. The syntax used in
calling the timedelta() function is shown below:
from datetime import timedelta

timedelta(days, hours, minutes, seconds, year,...)

Examples of Python datetime manipulation:


The commands shown in the sample can be used from within the Python
interpreter environment or by creating a script with the codes and executing it
in the Python environment.
To print the present date (today’s), the code shown below is used:
import datetime

print (datetime.date.today())
Or
from datetime import date

print (date.today())

To view each component that makes up the date, we use:


from datetime import date

print (datetime.date.today().day)

print (datetime.date.today().month)

print (datetime.date.today().year)

#If you would instead write a single sentence, write it as

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

#print (now.day, now.month, now.year)


This second sample code is a more readable and concise version of the first.
Writing your codes in the briefest and most precise way without altering the
readability is critical in Python programming. The snapshot below is an
insight into the result of executing the sample code:

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()

print (Today.strftime(“%d, %M, %d8, %y”))

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()

print (“Today’s date is “ ,Today.strftime(“%c”))

To print the local date alone and local time separately, we could swap out
“%c” using “%x” and “%X” respectively.

Programs that use Timedelta


from datetime import date,time,datetime,timedelta

Time_gap = timedelta(hours = 23, minutes = 34) #Time_gap is the timedelta


object that allows us perform different calculations on it.

print (“Future time is ”, str(datetime.now() + Time_gap))


When executed, the result is:
How the Datetime Module is used
The datetime module is one powerful feature introduced by Python. It
enables users to be able to manipulate the date and time of the system without
causing any changes to the system. It is possible to define a new date object
and alter how it is represented. Date and time objects allow for arithmetic
calculations to be performed on them for a variety of reasons, like
determining a future date, the current year, creating solutions for time
management, formatting dates into strings, among others.
Exercise 7:

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

from sklearn import preprocessing

#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

Click to return. Output should be as follows:


Mean = [ 5.55111512e-17 -3.70074342e-17 0.00000000e+00 -1.85037171e-
17]
Std deviation = [1. 1. 1. 1.]
Take note that the output of the mean is very near zero (0), while the standard
deviation rests on 1.

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. The result outputted is as follows:


L1 normalized data = [ [ 0.21582734 -0.10791367 0.21582734 -0.46043165]
[ 0. 0.35714286 -0.1547619 0.48809524]
[ 0.0952381 0.21904762 -0.27619048 -0.40952381]
]
The normalization technique is used in ensuring that data points are not
boosted owing to the characteristic of their features.

The Binarization Technique:


The binarization technique is one used in converting a numerical feature
vector into a Boolean vector form. The code shown below is used in effecting
the binarization technique:
data_binarized =
preprocessing.Binarizer(threshold=1.4).transform(input_data)
print "\nBinarized data =", data_binarized

Proceed to execute the line of code. The result it outputs is:


Binarized data = [[ 1. 0. 1. 0.]
[ 0. 1. 0. 1.]
[ 0. 1. 0. 0.]
]
The binarization technique comes in handy when users already have prior
knowledge about the data.

The One Hot Encoding Technique:


The one-hot encoding technique is often required in cases dealing with
numerical values, which are few and scattered in nature. Also, these values
may not need to be stored when being processed. If the amount of distinct
values is x, this technique modifies the feature into an x-dimensional vector
in which only one value appears as 1 while the others appear as 0.
To perform the one hot encoding technique, use the code shown below:
encoder = preprocessing.OneHotEncoder()
encoder.fit([ [0, 2, 1, 12],
[1, 3, 5, 3],
[2, 3, 2, 12],
[1, 2, 4, 3]
])
encoded_vector = encoder.transform([[2, 3, 5, 3]]).toarray()
print "\nEncoded vector =", encoded_vector

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.

The Label Encoding Technique


Under supervised learning, a type of machine learning, there tends to be a
common variety of labels that take on the form of words or numbers. When
they take the form of numbers, they are directly implemented by the
algorithm. Albeit, most often than not, labels have to take on readable forms.
As a result, words are usually used in labeling the training data. The label
encoding technique revolves around converting the word labels to numbers to
help the algorithm better understand how to implement them. Take a look at
the ensuing sample code below. It should lend clarity to how label encoding
is done in Python:
from sklearn import preprocessing
label_encoder = preprocessing.LabelEncoder()
input_classes = ['mack', 'kia', 'mack', 'cat', 'kia', 'bmw']
label_encoder.fit(input_classes)
print "\nClass mapping:"
for a, item in enumerate(label_encoder.classes_):
print item, '-->', a

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:

Encoded labels = [3, 2, 0, 2, 1]


Decoded labels = ['kia', 'mack, 'bmw', 'mack', 'cat']
As can be deducted from the result, take note that the mapping has been well
preserved.

Data Analysis in Python

How datasets are loaded:


Data can be directly loaded from a repository, say, the UCI Machine
Learning. Take note that pandas are being used to lay the data in this case. It
is also possible to explore data with the help of pandas, both using data
visualization and descriptive statistics. Take note of the code shown below
and keep in mind that we are attempting to specify the names of every
column when data is being loaded.
import pandas
data = ‘pima_indians.csv’
names = ['Pregnancies', 'Galactose', 'BloodPressure', 'SkinThickness',
'Dopamine', ‘Outcome’]
dataset = pandas.read_csv(data, names = names)
When the code sample is executed, you can notice the loading of the dataset,
implying its readiness to be analyzed. At this point, the file pima_indians.csv
has already been downloaded and saved to the path of the working directory.
Also, it has been loaded by the local file name.
Summarizing the Dataset:
Data summarization can be performed in many different ways, such as the
following:

Breaking down the data by class variables.


Listing the whole data
Checking dimensions of the dataset
Viewing the statistical summary of every attribute

Dimensions of the Dataset:


The command shown below can be used in checking the number of columns
(attributes) and rows (instances) a data holds with the shape property.
print(dataset.shape)
For the sample code being used here, you would note about 6 attributes and
769 attributes:
(769, 6)

Listing the whole Data:


It is possible to get a view of the whole data for better understanding of its
summary:
print(dataset.head(20))
Running the line of code above outputs the first 20 instances (rows) in the
data, as shown in the outline below:
S/NPregnancies Galactose BloodPressure SkinThickness Dopamine Outcome
1 6 148 72 35 0 1
2 1 85 66 29 0 0
3 8 183 64 0 0 1
4 1 89 66 23 94 0
5 0 137 40 35 168 1
6 5 116 74 0 0 0
7 3 78 50 32 88 1
8 10 115 0 0 0 0
9 2 197 70 45 543 1
10 8 125 96 0 0 1
11 4 110 92 0 0 0
12 10 168 74 0 0 1
13 10 139 80 0 0 0
14 1 189 60 23 846 1
15 5 166 72 19 175 1
16 7 100 0 0 0 1
17 0 118 84 47 230 1
18 7 107 74 0 0 1
19 1 103 30 38 83 0

Viewing the Statistical Summary:


To view the statistical summary of each column or attribute, including the
frequency and top, count, and unique, execute the line of code showed below:
print(dataset.describe())
When the command shown above is executed, the result that is printed gives
a depiction of the statistical summary of all the attributes:
PregnanciesGalactoseBloodPressureSkinThicknessDopamineOutcome
count 769 769 769 769 769 769
unique18 137 48 52 187 3
top 1 100 70 0 0 0
freq 135 17 57 227 374 500

Breaking down the Data by Class Variable:


You could also observe the number of rows or instances that are connected to
all the outcomes as the absolute count. To do this, use the code shown below:
print(dataset.groupby('Outcome').size())
When the code is executed, the number of outcomes of instances is printed as
follows:
Outcome
0 500
1 268
Outcome 1
dtype: int64
Data Visualization:
Data can be visualized with two types of plots, namely univariate and
multivariate plots. Univariate plots helps with the understanding of all
attributes, while multivariate plots help in understanding the relationship
attributes exhibit.

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()

Box and Whisker Plots:


It is possible to create histograms for every entry variable to gain an insight
into the distribution. To do this, use the block of code shown below:
#histograms
dataset.hist()
plt().show()
The snapshot of the output goes to show that two of the entry variables
contain a Gaussian distribution. As such, these plots lend clarity and
understanding of the underlying algorithms that are used in the program.

Multivariate Plots:
Multivariate plots help in providing clarity about the interrelationship
existing between the variables.

Scatter Plot Matrix:


To begin, we take a look at the scatter plots of every pair of attributes. This
can be especially useful in spotting a structured relationship existing between
the entry variables.
from pandas.plotting import scatter_matrix
scatter_matrix(dataset)
plt.show()
When executed, the code above gives the following:
Observe from the snapshot that there is a form of diagonal grouping between
some pairs of attributes. This quality is indicative of a high level of
correlation and predicts a possible relationship.

Exercise 8:

1. Why is the mean removal technique used?


2. Distinguish between univariate and multivariate plots?
3. What are the conventions for using the one-hot encoding technique?
Chapter Nine
Applications of Machine Learning in Python
Everywhere you look, Machine Learning (ML) and Artificial Intelligence
(AI) abounds. From medicine to engineering to technology to learning to
finance and trade, everything seems to have an embedment of ML or AI.
Surprised? Well, there’s a chance you use them in your day-to-day life
without your knowledge.
In Machine Learning, devices, software, and computers are thought to
perform through cognition similarly to the human brain. Some typical
successful applications of machine learning can be found in programs
capable of face recognition, spam detection, stock market predictions and
analysis, voice recognition, handwritten text decoding, weather forecasting,
among other things. In this segment, we would be taking an in-depth look at
how machine learning is applied in Python. Before that, though, let’s discuss
why Python is chiefly preferred for machine learning. The reason is not
farfetched—simplicity. This characteristic property of the language makes it
a better pick for machine learning because it promises better readability and
reusability of code. Also, Python has an extensive library to support machine
learning. Some of these libraries include:

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:

1. What library of machine learning contains a predefined environment


used to test and compare algorithms?
2. What is the relationship between machine learning and chatbots?
3. How are E-commerce platforms able to identify the preferences of a
user?
Chapter Ten
Inheritance in Python
In the general sense of things, inheritance is a tool that allows users to define
a class, which derives all its functionality from a parent class while providing
insight to add more.
Inheritance forms a core part of object programming because of how it can
extend the functionality of an already existing class by introducing new
features. It can be compared to a real-world situation of a birthright in which
children inherit the properties of their parents in addition to the ones they
already possess. The children may also derive a surname (the last name) from
their parents. The inheritance serves as one of the four core concepts object-
oriented programming (OOP), including polymorphism, abstraction, and
encapsulation. Inheritance is a robust tool in the hands of programmers,
allowing them to create and enable new classes to inherit or receive every one
of the methods and properties of an already existing class or classes. As we
have come to know, class refers to a template or blueprint of an object. As
such, every object was created using a class, while the concept of inheritance
comes in to devise a form of relationship between the blueprints. This
property is a feature of object-oriented programming that is applied in
defining a new class containing little to no modification to an already existing
class. While the class from which the other class is obtained is known as the
parent class or base class, the created class is regarded as the child class or
derived class. The formation of the derived class involves the use of the base
class, as well as some other added features. The general purpose of the
concept of inheritance is to help improve code reusability.
The function of inheritance in object-oriented programming:
By making use of the inheritance feature, users can find it possible to have a
blueprint that has the same attributes as the initial one.

How an Inheritance is Implemented in Python


To introduce inheritance into a code sample, you could use the following
syntax:
class ParentClass:
Parent class attributes
Parent class methods
class ChildClass(ParentClass):
Child class attributes
Child class methods
Automatically, inheritance introduces reusability to a block of code because
the child class comprises of everything found in the base class.
Methods of interaction between a parent and child class
When programmers make use of a concept in object-oriented programming
like inheritance, they create interactions between parent and child classes in
three main ways. They include:

Anything performed on the child class modifies a corresponding


action performed on the parent class.
Actions carried out on the child class override the subsequent actions
carried out on the parent class.
Actions performed on the child class are simple actions performed
on the parent class.
Sample code for Python inheritance
To improve your understanding of the concept of inheritance and its
application, let us consider some samples below:
We start by creating a base or parent class, with a child or derived class
vehicle.
class Taxi:

def __init__(self, model, capacity, variant):


self.__model = model # __model is private to Taxi class
self.__capacity = capacity
self.__variant = variant

defgetModel(self): # getmodel() is accessible outside the class


return self.__model
defgetCapacity(self): # getCapacity() function is accessible to class
Vehicle
return self.__capacity

defsetCapacity(self, capacity): # setCapacity() is accessible outside the class


self.__capacity = capacity

defgetVariant(self): # getVariant() function is accessible to class Vehicle


return self.__variant

defsetVariant(self, variant): # setVariant() is accessible outside the class


self.__variant = variant

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"

# In method getInfo we can call getmodel(), getCapacity() as they are


# accessible in the child class through inheritance

v1 = Vehicle("i20 Active", "4", "SX", "Bronze")


print(v1.vehicleInfo())
print(v1.getModel()) # Vehicle has no method getModel() but it is accessible
via Vehicle class
v2 = Vehicle("Fortuner", "7", "MT2755", "White")
print(v2.vehicleInfo())
print(v2.getModel()) # Vehicle has no method getModel() but it is accessible
via Vehicle class

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

The UML Diagram of Python Inheritance


To provide more clarity on this subject, take a look at the UML diagram
outlined below. The diagram is connected to the sample code used in this
section.
The Super() Method:
What is the function of the super() method in Python?
The super() method enables users to gain access to the inherited methods
which cascade into a class object. In the samples shown earlier, the super()
method was used within the constructor of the derived class <Vehicle>. At
this point, the super() method invokes the function of the parent class <Taxi>.

How the super() method is implemented


Assume that you are required to involve a method in the parent class, for
example, vehicleinfo(), that is defined in the derived class. To do this, you
can make use of the line of code showed below:
super().vehicleInfo()

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__()

Implicit inheritance in Python:


Implicit actions happen in Python inheritance whenever a programmer
defines a function within the base class alone. This type of inheritance is
depicted in syntax using the simple sample shown below:
class super (object) :

def implicit(self) :
print (“Super-Class with Implicit function”)

class sub(super) :
pass

su = super()
sb = sub()
su.implicit()
sb.implicit()

The output produced is as follows::


Super-Class with Implicit function
Super-Class with Implicit function

From a general overview, it can be seen that Python inheritance contributes


immensely to object-oriented programming. As a result, it is of utter
importance that you understand how inheritance works in Python owing to
the object-oriented design of the language.

Exercise 10:

1. What real-world situation can be compared to the concept of


inheritance?
2. How does inheritance work with classes?
3. What is the function of a super() method?
Chapter Eleven
Special Methods in Python
Throughout this book, you have been introduced to many different examples
of “special methods” — the “magic” functions or methods that are invoked in
Python to call some specific syntax. With special methods, classes tend to
take on different forms. They could behave in a way similar to iterators,
numbers, dictionaries, sets, and even functions. In this section, we take an in-
depth look at some of these special methods, as well as a brief overview of
some pretty esoteric ones.

Basic Special Methods


From our discussion about classes and objects in Python, you would agree
that the __init__ method is the most common example of a special method.
Here, we are delving into a couple of basic special methods which are
particularly used in the debugging process for user-defined classes. The basic
special methods are including but not limited to, the following:

x = My class(): For when you want to initialize an instance (row).


When executed, Python calls the x.__init__() method.
repr(x): For when you want to create a standard representation in
string format. When executed, Python calls the x.__repr__() method.
str(x): For when you want to represent the “informal” value in string
format. When executed, Python calls the x.__str__() method.
bytes(x): For when you want to represent the “informal” value in the
form of a byte array. When executed, Python calls the x.__bytes__()
method.
format(x.format_spec): For when you want the value in the form of a
formatted string. When executed, Python calls the
x.__format__(format spec) method.

Rationale:

The __init__() method is called after the creation of the instance. To


take control of the primary creation process, the __new__() method
is used.
Based on convention, the __repr__() method ought to output a string,
which is an expression in Python that is valid.
The __str__() method can also be called any time print(x) is used.
The bytes() method is a new addition to Python 3, that was
introduced with the addition of the bytes data type.
Based on convention, format_spec ought to obey the Format
Specification Mini-Language. decimal.py in the standard library of
Python offers a __format__() method of its own.

Classes Behaving Like Iterators:


Two fundamental methods are prominent in iterator operations in Python.
These two methods are the __next__() and __iter__ methods, which are used
in the creation of methods from scratch.

Iter(seq): For performing iteration through a sequence. When


executed, Python calls the seq.__iter__() method.
Next(seq): For obtaining the succeeding value from an iterator.
When executed, Python calls the seq.__next__() method.
Reversed(seq): It is used in the creation of a reverse order iterator.
When executed, Python calls the seq __reversed__() method.
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:

x.my_property: It is used in obtaining a computer attribute


(unconditionally). When executed, Python calls
x.__getattribute__('my_property’).
x.my_property: This method is used for obtaining a computer
attribute (fallback). When executed, Python calls
x.__getattr__(‘my_property’).
x.my_property = value: It is used in setting up an attribute. When
executed, Python calls x.__setattr__('my_property’, value).
delxmy_property: It is used in deleting an attribute. When executed,
Python calls x.__delattr__('my property').
Did(x): It is used in listing every method and attribute. When
executed, Python calls x.__dur__().

Rationale:

When a class defines the __getattribute__(), method Python calls it


in all references to every method or attribute name, with the only
exception being special method names. The reason is that it would
result in an unpleasant unending loop.
If a class defines the __gefattr__() method, the program calls it only
after searching for the attribute in all the usual places. For example,
should an instance j define the attribute design, j.design won’t call
j.getattr__(‘design’). Rather, it returns the value of j.design that has
been already defined.
The method __setattr__ is typically called when an attribute is being
assigned a value.
The method __delattr__() is called when an attribute is being
deleted.
The method __dir__() comes in handy whenever the methods
__getattribute__() or __getattr__ are defined. In a normal setting,
calling the dir(x) method would only result in the conventional
methods and attributes being listed. Should the __getattr__() method
handle the design attribute dynamically, the due(x) method can only
list design as one of the available attributes. When the __dir__()
method is overridden, it lets you list design as an available attribute,
making it all the easier for other users who want to make use of your
class without going deep into its source code.
The difference between the methods __getattribute__ and
__getattr__() is thin, however, significant. Consider the samples
below for clarity on this subject:
class Dynamo:
def __getattr__(self, key):
if key == 'design': 1
return ‘CrazyJean’
else:
raise AttributeError 2

>>>dyn = Dynamo()
>>>dyn.design 3
‘CrazyJean’
>>>dyn.design = 'FlareBottoms'
>>>dyn.design 4
‘FlareBottoms’

Rationale:

In this code sample, the attribute name is passed to the method


__getattr__() in a string format. When the name is “design,” the
method would return a value. Since this is a case of a hard-coded
string, you would otherwise be able to perform some types of
computation and arrive at a result. [1]
When the attribute name is unknown, the __getattr__() method ought
to raise the exception “AttributeError,” otherwise, the code fails to
execute when attempting to access undefined attributes. From a
technical viewpoint, should the method fail to return a value
explicitly or raise an exception, it returns the value ‘None,’ the null
value in Python. This implies that every value that isn’t explicitly
defined returns as None. And since this isn’t what we want, it’s best
to avoid it. [2]
The instance ‘dyn’ is without an attribute named ‘design,’ explaining
why the __getattr__() method is introduced to produce a computed
value. [3]
Once the dyn.design has been explicitly set, the method __getattr__()
will no longer be necessary for providing dyn.design with a value as
the instance already has dyn.design defined on it. [4]
On the other hand, the method __getattr__ is unconditional and
absolute.
class SuperDynamo:
def __getattribute__(self, key):
if key == 'design':
return ‘CrazyJean’
else:
raise AttributeError

>>>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

>>> warrior = Jodie()


>>>warrior.run() 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __getattribute__
AttributeError

In the sample above, the class is used to define a __getattribute__ method


that raises an AttributeError exception always. As such, there is no successful
method or attribute lookup. [1]
Whenever warrior.run() is called, Python searches for a run() method within
the Jodie class. This lookup iterated over the __getattribute__() method,
because every method and attribute lookup always go through the
__getattribute__ method. As such, here, the __getattribute__() method
triggers the AttributeError exception; this way, the method lookup fails, and
the method call fails conversely. [2]

Classes Behaving like functions:


It is possible to create an instance from a class callable, in a similar way to
how functions are callable. It can be done by defining the __call__() method.
my_instance(): This method is used in calling an instance similar to a
function. When executed, Python calls the my_instance.__call__() method.

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.

Classes Behaving like Sets:


If a class serves as a container for a set of values, that is, if it doesn’t sound
nonsensical to ask if a class contains values, then there is a chance that the
class defines the special methods shown below, making it behave similarly to
sets.

len(s): It is used in determining the number of items. When executed,


Python calls the s.__len__() method.
x in s: It is used in determining whether a class contains a particular
value. When executed, Python calls s.__contains__(x).
Let’s consider a sample code below:
The cgi module makes use of these methods in the FieldStorage class, which
is a representation of the query parameters or form fields submitted into a
dynamic webpage.
# A script which responds to http://mysamplecode.com/search?q=cgi
import cgi
fs = cgi.FieldStorage()
if ‘q’ in fs: 1
do_search()

# An excerpt from cgi.py that explains how that works


class FieldStorage:
.
.
.
def __contains__(self, key): 2
if self.list is None:
raise TypeError('not indexable')
return any(item.name == key for item in self.list) 3
def __len__(self): 4
return len(self.keys()) 5

Once the instance of the cgi.FieldStorage class has been finally


created, proceed to use the “in” operator to determine if a specific
parameter was added to the query string. [1]

The method __contains__() is the special method that makes the


code work. When you attempt to find ‘q’ in fs, Python searches for
the __contains__() method on the fs object that is defined in the file
cgi.py. The __contains__() method is then passed the value ‘q’ is in
the form of a key argument. [2]
A generator expression is obtained by the function any() and
returned as True whenever the generator outputs any items. The
any() function works smartly, knowing to stop when a first match is
identified. [3]
Returning the length of the class is supported in the same
FieldStorage; hence, the function len(fs) can be used to call the
method __len__ on the FieldStorage class, returning the number of
query parameters that it found. [4]
The self.keys() method responsible for finding out if self.list is
returned as None so that the __len__ method would not have to
duplicate the error checking.

Classes Behaving like Dictionaries:


Slightly extending the discussion of classes behaving like sets, it is possible
to define classes, which not only interact with the len() function and “in”
operator, but also behave in a way similar to standard Python dictionaries,
returning values in the form of keys.

X[key]: This is used to obtain a value by its corresponding key.


When executed, it calls the method x.__getitem__(key).
X[key] = value: This is used in setting value by its corresponding
key. When executed, it calls the method x.__setitem__(key, value).
Del x[key]: This is used in deleting a value by its corresponding key.
When executed, it calls the method x.__delitem__(key).
X[nonexistent_key]: This is used in producing a default value for
missing keys. When executed, it calls the method
x.__missing__(nonexistent_key).
Using the cgi.py file still. The FieldStorage class obtained from the cgi
module defines the special methods in this category as well. This means you
can perform operations such as the one covered below:
# A script that responds to http://mysamplecode.com/search?q=cgi
import cgi
fs = cgi.FieldStorage()
if 'q' in fs:
do_search(fs['q']) 1

# An excerpt from cgi.py that shows how it works


class FieldStorage:
.
.
.
def __getitem__(self, key): 2
if self.list is None:
raise TypeError('not indexable')
found = []
for item in self.list:
if item.name == key: found.append(item)
if not found:
raise KeyError(key)
if len(found) == 1:
return found[0]
else:
return found
Although the instance of the cgi.FieldStorage is the fs object, it is still
possible to evaluate expressions, such as fs['q']. The expression fs['q'] is used
to invoke the __getitem__() method using the key parameter set as 'q.’ It then
proceeds to look up an item with a name that matches the specified key in the
internal list of query parameters (self.list) which it maintains.

Classes Behaving like Numbers:


With the correct special methods, defining a set of classes that behave
similarly to numbers is possible. That is, you can easily perform basic
mathematical operations on these classes, including but not limited to
addition, subtraction, multiplication, and division. This concept captures the
implementation process for fractions. The fraction class is used in
implementing these special methods. Once implemented, you can perform
operations, as seen below:
>>> from fractions import Fraction
>>> j = Fraction(1, 3)
>>> j / 3
Fraction(1, 9)
Below is a comprehensive outline of the special methods needed for the
implementation of classes that act like numbers.

You write a + b when you want to perform addition operations, and


Python calls the a.__add__(b) method.
You write a - b when you want to perform subtraction operations,
and Python calls the a.__sub__(b) method.
You write a * b when you want to perform multiplication operations,
and Python calls the a.__mul__(b) method.
You write a / b when you want to perform division operations, and
Python calls the a.__truediv__(b) method.
You write a // b when you want to perform floor division operations,
and Python calls the a.__floordiv__(b) method.
You write a % b when you want to perform modulo or remainder
operations, and Python calls the a.__mod__(b) method.
You write divmod(a, b) when you want to perform floor division and
modulo operations, and Python calls the a.__divmod__(b) method.
You write a ** b when you want to perform operations involving
powers, and Python calls the a.__pow__(b) method.
You write a << b when you want to perform left bit-shift operations,
and Python calls the a.__lshift__(b) method.
You write a >> b when you want to perform right bit-shift
operations, and Python calls the a.__rshift__(b) method.
You write a & b when you want to perform bitwise and operations,
and Python calls the a.__and__(b) method.
You write a | b when you want to perform bitwise or operations, and
Python calls the a.__or__(b) method.
You write a ^ b when you want to perform bitwise xor operations,
and Python calls the a.__xor__(b) method.

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:

1. Mention the two main methods used in iterator operations.


2. What special method does Python call when carrying out operations
involving multiplication?
3. When classes behave like dictionaries, how do they return values?
Chapter Twelve
Exception Handling in Python
Before we delve into the concept of exception handling, let’s distinguish
between errors and exceptions, because they are often confused.
An error refers to anything that goes wrong in a program. That is, anything
responsible for a program not executing is an error. An example of errors is
the syntactical error. Another characteristic pf error is that it happens during
runtime or compile time. See the sample code below for clarity:
if x<10
File "<interactive input>", line 1
if x<10
^
SyntaxError: invalid syntax
Exceptions, on the other hand, also happen during compile time, and as such,
are errors in themselves. However, the key distinguishing factor is that
exceptions are events that happen when a block of code is being executed,
disrupting the normal flow of the instructions of the code block. From a
general viewpoint, an exception is usually raised when a Python script runs
into an error situation that it can’t deal with. An exception object is created at
the point when a Python script raises an exception. The script would typically
look to manage the exception at once. If it fails in doing so, then the program
ends, printing a traceback to the error, as well as its location within the block
of code.
Consider the sample code below:
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in run code
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero

How Exceptions Are Handled Using The Try-Except Statement


Before we discuss how try-except is used in handling exceptions, let’s define
the statement. The try-except statement is used to allow for exception
handling within Python codes.
The try-except statement works by entering the code that can raise an
exception within the try block, while the code which catches or handles the
exception is placed within the except clause.
The syntax for Python exception handling:
Shown below is a syntax for the try-except-else block in Python.
try:
Perform your operations here;
......................
except ExceptionI:
If there is any ExceptionI, then execute this block.
except ExceptionII:
If there is any ExceptionII, then run this block.
......................
else:
If there are no exceptions, then run this block.

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.

Using the Except clause to handle multiple Exceptions


Multiple exceptions can be defined using a single except clause. It implies
that when the Python interpreter locates a similar exception, it proceeds to
run the code attached to the except clause. That is, whenever an except clause
is defined in this manner, it is expected of the same block of code to throw
several exceptions. Besides, the goal is to perform the same action repeatedly
in every case.
Take a look at the code sample shown below:
try:
Perform all your operations here;
....................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there are any exceptions from the given exception list,
then run this block.
....................
else:
If there are no exceptions, then execute this block

Using the Try-Finally statement to handle Exceptions


The try-finally statement, like the try-except statement, can be used in
enabling exception handling in the Python program. However, in the case of
the try-finally statement, the try block features the option of defining the
“finally” block. Such a clause implies the use of defining statements that a
programmer wishes to execute, regardless of whether or not the try block has
already raised an exception. This property tends to enter into the fray when
external resources are being released. Below is a coding snippet for clarity:
try:
Perform all your operations here;
......................
Due to an exception, this may be skipped.
finally:
This would always be executed.
......................

Let’s consider an example below:


One principal point to keep in mind is that either a “finally” or an “except”
clause can be defined using a try block. Both clauses cannot be used together
in the same code. Also, the “finally” clause cannot be used in the same code
as an “else” clause.
try:
fob = open('test', 'y')
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'

If an exception isn’t raised, then the following output is printed.


>>try block executed
>>finally block executed

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

When a code raises an exception within a try block, the execution is


immediately passed into the “finally” block. Once every command within the
“finally” block has been executed, the exception is resumed in the “except”
block to be executed. However, the next higher try-except statement ought to
be present.

Raising Exceptions using Python Arguments


Raising an exception can be forcefully done with the raise keyword.
Alternatively, we can choose to pass values to an exception, specifying the
underlying reason behind its occurrence.
The Raise Syntax:
The syntax for calling the raise method is shown below:
raise [Exception [, args [, traceback]]]

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.

Let's consider a sample code for more clarity:


>>> raise MemoryError
Traceback (most recent call last):
...
MemoryError

>>> raise MemoryError("This is an argument")


Traceback (most recent call last):
...
MemoryError: This is an argument

>>> 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)

When a negative number is entered, the output displayed is as follows:


Enter a positive integer: –9
This is not a positive number!!

Creating Custom Python Exceptions


A custom exception refers to a type of exception that is created by a
programmer intentionally. The programmer creates an exception by
introducing a new class. One trick applies here; deriving the custom
exception class from the parent exception class. Also, recall that the majority
of the built-in exceptions in Python also have respective classes of their own.
How to createan Exception Class In Python:
>>> class UserDefinedError(Exception):
... pass

>>> raise UserDefinedError


Traceback (most recent call last):
...
__main__.UserDefinedError
>>> raise UserDefinedError("An error occurred")
Traceback (most recent call last):
...
__main__.UserDefinedError: An error occurred
In the code sample used here, it can be seen that a user-defined exception
class has been created in the “UserDefinedError.” This is done from making
use of the base exception class as the parent. As a result, the new user-
defined exception class raises exceptions in the same way as any other
exception class. That is, through calling the “raise” statement using an
optional error message.
Consider the sample code below:
In this code sample, we describe how a user-defined exception can be raised,
as well as how to identify errors within a program.
The program asks the user to make an entry of an alphabet repeatedly until
the alphabet stored in the program is entered.
As an aid, the program offers a given hint to the user to enable them to find
out the right alphabet. Also, the user can check if the guess entered is lesser
or higher than the store alphabet value.
#define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass

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

#user needs to guess the alphabet


alphabet = 'q'

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('')

print("Congrats! Your guess was correct.")

We attempt to try out this program by entering several inputs.


Enter an alphabet: w
This value is too large, try again!

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.

Built-in exceptions in Python


An outline of some of the standard or built-in exceptions in Python
programming is shown below:

Exception: It serves as the parent class for every other exception in


Python programming.
StopIteration: This exception is raised anytime a next() function in
an iterator doesn’t point to an object within a program.
SystemExit: This exception is raised when the function sys.exit() is
called.
StandardError: This exception is a base class for every other built-in
exception aside SystemExit and StopIteration.
ArithmeticError: This exception is a base class for every error that
happened during a numeric calculation.
OverflowError: Whenever the maximum allowed limit for the
calculation of a numeric type is exceeded, this exception is raised.
FloatingPointError: Anytime a floating-point calculation is
unsuccessful, this exception is raised.
AssertionError: In the eventual failure of an Assert statement, this
exception is raised.
AttributeError: In the case that an attribute assignment or reference
fails, this exception is raised.
EOFError: When the end of a file is reached, and there is no input
from either the input() function or the raw_input() function, this
exception is raised.
ImportError: Whenever an import statement is unsuccessful, it raises
this exception.
KeyboardInterrupt: This exception is raised whenever the execution
of a program is interrupted, usually by a user entering the command
Ctrl + c.
LookupError: This exception serves as the base class for every
lookup error.
IndexError: When an index cannot be located within a sequence, the
program raises this exception.
KeyError: When a specific key cannot be located within a dictionary,
the program raises this exception.
NameError: Whenever an identifier cannot be located within a global
or local namespace, the program raises this exception.
UnboundLocalError: When attempting to access a local variable
within a method or function when it has not been assigned any value,
the program raises this exception.
EnvironmentError: This exception serves as the base class for every
exception which occurs outside of the Python environment.
IOError: Whenever an output or input operation fails, for example,
say the open() function or the print statement becomes non-existent
when attempting to open the file, the program raises this exception.
IOError: This exception is raised for errors related to the operating
system in use.
SyntaxError: Whenever an error exists in a Python syntax, the
program raises this exception.
IndentationError: When the indentation is not adequately specified in
a program, this exception is raised.
SystemError: This exception is raised whenever the Python
interpreter locates an internal problem; however, when this error is
encountered, the interpreter fails to quit.
SystemExit: Whenever the Python interpreter is exited with the
function sys.exit(), this exception is raised. If it goes without being
handled in the code block, it makes the interpreter exit.
TypeError: When a function or operation considered invalid for a
given data type is attempted, this exception is raised.
ValueError: When the built-in function for a data type has the type of
arguments considered valid, while the values specified for the
arguments are invalid, this exception is raised.
RuntimeError: When a generated error cannot be classified into any
category, this exception is raised.
NotImplementedError: Any time an abstract method that ought to be
implemented within an inherited class isn’t implemented, this
exception is raised.
Generator exit: This exception is raised whenever the <close()>
method of a generator is called.
MemoryError: When an operation runs out of memory during
execution, this error is raised.
OSError: This exception is raised any time a system operation is
unsuccessful.
ReferenceError: This exception is raised any time a garbage
collected reference is attempted to be accessed by a weak reference
proxy.
TabError: This exception is raised as a result of inconsistencies in
the use of spaces and tabs.
UnicodeError: This exception is raised for Unicode decoding or
encoding of errors.

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)

The execution of this sample code produces the results as follows:


32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
Exercise 12:
Distinguish between an error and an exception.
How do assertions work in Python?
Describe the EnvironmentError exception.
Answers to exercises:
Answers (Exercise 1):

1. He designed Python as an interpreter language to succeed ABC


programming language.
2. It means Python is free to use by the public who can amend its
source codes, and redistributed even for commercial use.
3. The hash (#) is used in each line.

Answers (Exercise 2):

1. Attempting to create a variable automatically reserves a certain


amount of space in the program’s memory.
2. No. It is because they exist in an unordered state.
3. A variable is assigned a value using the sign of equality (=).

Answers (Exercise 3):

1. It is used to assign names to functions.


2. It is because Python is an object-oriented language (OOL).
3. 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.

Answers (Exercise 4):


Logical operators.
Operands are the values in the form of variables used in passing inputs into
the operator.
Bitwise operator. Bitwise OR.

Answers (Exercise 5):


The while, if, and for statements.
The break statement.
The else statement.
Answers (Exercise 6):

1. The __init__() method.


2. The class keyword is used in the creation of Python classes within a
program.
3. Objects are working instances of classes that are created during
execution while classes are the arrangements of functions and
variables within single logical entities.

Answers (Exercise 7):

1. They are timedelta, date, info, datetime, and time.


2. The function strftime() function is used within the datetime module
to change the format of the dates into strings that can be read by
users.
3. It is responsible for time zone information about local time.

Answers (Exercise 8):

1. It is used in taking out every form of bias from the features.


2. Univariate plots helps with the understanding of all attributes, while
multivariate plots help in understanding the relationship attributes
exhibit.
3. The case should be about numerical values, which are few and
scattered in nature.

Answers (Exercise 9):

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

Answers (Exercise 10):


1. Inheritance is comparable to a real-world situation of birthrights in
which children inherit the properties of their parents in addition to
the ones they already possess.
2. It enables new classes to inherit or receive every one of the methods
and properties of an already existing class or classes.
3. It allows users to gain access to the inherited methods which cascade
into a class object.

Answers (Exercise 11):

1. __next__() method and __iter__ method.


2. The .__mul__() method.
3. They return values in the form of keys.

Answers (Exercise 12):

1. An error refers to anything that goes wrong in a program, while an


exception is any event that happens during runtime, disrupting the
normal flow of the instructions of the code block.
2. It tests a code block and raises an exception if the result returns as
false.
3. It serves as the base class for every exception which occurs outside
of the Python environment.
Conclusion
I wish to thank everyone who bought this book and supported it in one way
or the other. Your efforts did not go unnoticed and are deeply appreciated.
This book is the success it is because of you all. I hope the book proved
enlightening to you, opening your mind to the vast potentials of Python
programming. I expect it has helped you grow as a beginner programmer in
Python. It only gets better from here on. Happy coding!
Warmest regards,
SQL:
The Ultimate Crash Course for Data Base
Management, Queries Server with Practical
Computer Coding Exercises

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.

A computer is an electronic device that does systematic and logical, scientific


and arithmetic activities; however, all of these activities can only be achieved
with the aid of a computer programming. Computers are developed to stored
data, manage and transmit information easily, and among other benefits of
the computer.
Howbeit, the computers will be ineffective without computer programs.
Computer programs are collective instructions that allow tasks to be executed
efficiently.
The process of writing and editing any collection of code is referred to as
computer programming. When a programmer is editing a code, which is also
known as source code, it involves the testing, analyzing, coordinating, and
refining code alongside with other developers.
Computer programs can be divided into two main paradigms which are the
imperative and declarative programs. These two programming languages
allow the expressions, declaration, and computation of data.
Based on historical facts, programs have been in existence for centuries, and
though these programs were created to occupy large spaces, unlike today that
programs invented can be manipulated conveniently. The first known
program invention was recorded as far back as the 9th century. A music
sequencer; a device designed to record, edit and play back music was
invented by the Banu Musa. Few centuries after that, an Arab Engineer, Al-
Jazari, who invented a drum machine. Each century, programs were designed
to make life better and easier for humans, and as they were gross increase in
the creation of programs, likewise, they were an increase in computer
programming language.
As humans, we enjoy the company of others because we can communicate
effectively with one another. Think of this, how you will live if you can’t
understand the language of your colleague at work, even worse, when you
have no idea what a single phrase means. I don’t know how you felt while
you imagined the above scenario, but it would definitely be a frustrating
experience. We certainly don’t have an idea what the computer feels when
you command it to do something it does not understand, but we do know that
the computer will fail to execute your order. So, this explains why you need
to learn computer programming language.
Computer programming language can be described as the collection of
languages that the computer can understand to carry out an action. There are
several programming languages, like we have several languages I our
country, and each language has its own uniqueness, just as some languages
share some similarities. Programming languages however have unique
keywords and these words are the words that the computer understands to
carry out an action.
There are several programming languages designed for each program or
multipurpose programs. However, there are also some specific languages like
the structured query language. Structured query language is one of the first
commercialized languages that was designed and has been in existence, all
you need to know about SQL is written in the first chapter of this book.
One of the uniqueness of a programming language is the command of each
language, there are different commands in a programming language, and each
command has a rule to it. Following the rule attached to each command helps
you achieve your aim, without losing any of your data. In understanding
programming languages, you need to know about database and how they
work. The relational database management system is used to stored data in
tabular forms, but these data will not be stored effectively if they do not
understand the language of the programmer. This is why syntax is very
important to computer programming; remember how important grammar is to
English language. Yes! Syntax is also very important to programming
language.
Computer programming languages are very vast, and it is an important
subject for programmers. Nonetheless, there are more to programming than
just the grammar or command, knowing the type of data that you need to
design a program for is likewise essential. Albeit, knowing the benefit of
operators, and functions of the data objects in a SQL is important.
I believe this book will take you on a journey to understanding programming
language, more importantly, all you need to know about the Structured Query
Language.
Chapter 1

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

Basic Commands That Work Well in SQL


A command in computer programming serves as directives to computer
programs to perform tasks. A command can be issued through the command
line interface. A Command Line Interface, abbreviated as (CLI) is a line that
allows an interaction between a computer program and its user. The term
command is significantly used in computer languages, because the computer
does not understand natural languages, hence it has to be written in
imperative computer languages.
Many computer programs permit formatted arguments such as flags
which can literally be represented as adverbs, while options can be compared
as objects. These arguments modify the default nature of this program.
Having known the basics of SQL as explained in chapter one, SQL
commands are simply instructions that coded into SQL statements; they are
used to communicate efficiently with databases to perform specific works,
queries, and functions with data. SQL commands are structured to be useful
not only when you are searching for database, but also effective to perform
several functions that includes creating of tables, adding of tables, modifying
and dropping tables. Above all of these functions, commands give
permissions to users.
SQL commands are categorized in four ways based on how they function.

Data Definition Language (DDL)


Data Definition Language (DDL) is used to modify, create and alter
data. It is used to define data structures, like database schemas. DDL is also
known as a data description language, because it describes the records ad
fields in a database table.
DDL is often considered a subset of SQL; however, here are DDL that are
commonly used in SQL queries.

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

An example of how the create statement is used is seen below

CREATE TABLE STUDENTS (


id no INTEGER PRIMARY KEY,
first_name VARCHAR(50) not null,
surname VARCHAR(75) not null,
course VARCHAR(50) not null,
dateofbirth DATE not null
);

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

DROP objecttype objectname.


Here is how to apply the drop statements.
DROP TABLE students;

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.

ALTER objecttype objectname parameters.

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.

TRUNCATE TABLE table_name;

Data Manipulation Language (DML)


This command is used to store, modify, form and delete data in a database. It
is simply to manipulate data, and the commands used are: SELECT,
DELETE, UPDATE and INSERT. In SQL, the data manipulation language
consists of data change statements, which can modify data at anytime,
without causing a change in the schema, or database objects. DML have a
functioning competence structured by the initial word in a statement. Data
manipulation languages are likely to have many versions, capabilities
between database vendors.
DML are sub-divided into two categories namely, the procedural
programming and the declarative programming.
- Procedural Programming is a program that was created on the
concept of routines, subroutines, or functions that contain few series of
computational steps that should be carried out. While procedural
programming language is the only language that can be understood by the
procedural program. The first procedural program was made public and
appeared I the market first between the years 1957 – 1964.
Examples of procedural programming language include BASIC, C,
FORTRAN, Java and Pascal. To use the procedural language successfully,
you need to use an effective programming editor, like Microsoft Visual
Studio, Eclipse, or Adobe Dreamweaver. The functions of these
programming editors are to help developers who use procedural languages
to test and fix bugs in the code.
- Declarative programming language is a language that specifies what
should be done in a program, rather than how to do it. Declarative language
also has two subdivisions, namely the logic programming language and the
functional programming language.
The logic programming language consists of a set of logical relations and
PROLOG is the most commonly used type, while the functional language
uses sets of mathematical styles. Examples of this language include
examples of database query languages like SQL, XQuery, regular
expressions, logic programming and configuration management systems.

1. Transaction Control Language (TCL)

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;

Data Control Language (DCL)


Commands under the data control language are used to provide authentic
security measures to prevent unauthorized personnel from accessing the data
in the database. The command includes ALTER, DELETE, and INDEX,
INSERT, and SELECT, UPDATE and GRANT, which is used to grant
access to a database. Used for granting user access privileges to a user to
access any database of their choice.
GRANT object privileges ON table name TO user_name1, user_name2…
,user_name
Examples:

1. An update command on a student data


GRANT SELECT, UPDATE ON Student TO Nora Robert

2. A grant command to authorize some users


GRANT object privileges ON course_name TO Aba Mike, Jack Finn

3. DCL can also be used to grant access to a user on all data


GRANT ALL ON students_name to Nora Roberts
DCL allows users to either perform any of the above commands on their
desired data.

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.

UPDATE is used for the updating and adding of new information to a


database. When writing the update command, you can use the WHERE
clause to update rows that have been selected, if you fail to use the where
clause, other rows will be affected and you may lose your data.
Here is general syntax with the UPDATE query, with a WHERE clause
present
UPDATE table_name
SET column1= value1, column = value
WHERE [condition];
Example in tabular form
ID NAME AGE COURSE
O1 Rush 23 Nursing
Informatics
O2 Janet 20 Accounting
03 Jack 25 Strategy
Management
04 Karen 19 Human Resources
Management

Update the course for ID number 02 in the table


SQL> UPDATE STUDENT
SET COURSE = Artificial Intelligence
WHERE ID = 02;
Now the table will look like this;
ID NAME AGE COURSE
O1 Rush 23 Nursing
Informatics
O2 Janet 20 Artificial
Intelligence
03 Jack 25 Strategy
Management
04 Karen 19 Human Resources
Management

DELETE command is useful in deleting data from a database table. The


WHERE clause can be used to delete rows. If you delete without the WHERE
clause, that means you will have all your data deleted.
Example of a general syntax of the DELETE query that contains the WHERE
clause
DELETE FROM table_name
WHERE [condition];
ID NAME AGE COURSE
O1 Rush 23 Nursing
Informatics
O2 Janet 20 Accounting
03 Jack 25 Strategy
Management
04 Karen 19 Human Resources
Management

Consider this table; DELETE a customer whose ID is 04


SQL> DELETE FROM STUDENTS
WHERE ID = 04;
Immediately this command takes place, your table will look like this.
ID NAME AGE COURSE
O1 Rush 23 Nursing
Informatics
O2 Janet 20 Accounting
03 Jack 25 Strategy
Management

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

ID NAME AGE COURSE


O1 Rush 23 Nursing
Informatics
O2 Janet 20 Accounting
03 Jack 25 Strategy
Management
04 Karen 19 Human Resources
Management

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

CREATE DATABASE is used to create new database and tables


The general syntax
CREATE DATABASE databasename;
ALTER TABLE is used for the modification of a table or tables
To add a column to your table, do the following
ALTER TABLE table_name
ADD column_name datatype;
DROP TABLE is used to delete a table or tables. When you drop a table, it
results to delete and loss of the information stored in that table
Example
DROP TABLE Students;
CREATE INDEX is used to create an index
DROP INDEX is used to delete an index from a database

Rules for SQL Commands


1. All SQL commands can be written on multiple lines, it is not
compulsory to write on one line.
2. The need for a clause is separate lines so that accuracy can be
built
3. Index can be used when writing a SQL command
4. Commands cannot be divided over lines
5. SQL commands are different from other commands because they
are not case sensitive
6. When giving a command, SQL prompts can be enrolled with a
SQL command. As the command line buffers, the prompt
performs.
7. The execution of a command occurs when the command
statements are specified by a semi-colon;
8. You must also understand that only one command statement can
e present on a line at a time, within the buffer, and this command
statement can run in many ways as the following.

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

Introduction to Relational Database Management


Systems
You have seen the abbreviation RDBMS a couple of times in the previous
chapters, and you may wonder what it means. However, you can’t
understand the concept of RDBMS without knowing what a database is. A
database consists of sets of data that are stored in a computer. A database is is
usually structured in tables and columns, to contain information on different,
because a database can contain various information. The structure of a
database makes the data easily accessible by enabled users.
Now that you know what a database is, RDBMS means Relational Database
Management System and it is a database system that was created and based
on the relational model that was introduced by E. F. Code. RDBMS, and in
computer programming of today, it is the basis on which SQL and other
database systems exist and work.
A relational database is a type of database that allows users to access and
identify stored data that is related to another data file in the database.
Relational database often represents and organize their data in tables. Each
table in a RDBMS consists of database table rows, and each database row
contains one of more database table fields. Data stored in a RDBMS are
stored in collection of tables that can related to each other as a result of
common fields.
RDBMS is also used to manipulate data that are stored in database tables.
However, most of the RDBMS available in the market today use SQL as their
database query language. There are different types of RDBMS, but the MS
SQL server, DB2, Oracle and MySQL are the most common ones.
The relational model which was the first model was designed by a research
scientist at the IBM, Dr. E. F. Codd. For few facts, several modern DBMS do
not accept Codd's definition of RDBMS, even though it is the relational
model. While the relational model was been developed, Codd had a focal
point, which was to reduce data redundancy and improve data integrity that
existed within database systems.
A paper was written in 1970 by the originator of the relational model, Dr.
Code, which was titled "A Relational Model of Data for Large Shared Data
Banks” to describe the concepts of RDBMS and how they apply to database
management systems. It was then discovered that the relation is the only data
structure that was used in the relational data model to represent entities and
relationships that existed between them.
A row of a relation is referred to as tuples of relation, and the attributes are
columns. Each attributes of columns are gotten from sets of values which is
known as domain.
While the domain of an attribute, consists of sets of values that the attribute
may assume.
Based on history, we can actually say from a historical perspective that the
relational model is relatively new. The first database systems that was
developed was based on either hierarchical or network models. The
relational data model has overtime establish itself as the foundational data
model for commercial data processing applications. The success of the
relational model in this domain had led to a successful usage and application
of it outside data processing for computer.
Difference between Database Management Systems and Relational
Database Management Systems
Database management systems abbreviated as DBMS are different from
relational database management systems. A database management system is
deigned to a few works in a database, like define, manipulate, retrieve and
manage the data in a database. It can manipulate the database format, file
structure and field names. A DBMS is accessible even when the program
created has ceased to exist, or the data created restart, that is why DBMS is
persistent.
DBMS also provides uniformity methods that are independent of specific
applications to access information stored. While RDBMS on the other hand is
known to support tabular structure to store data, that are in relationship
between tables.
However, some databases do not support tabular structure of enforce
relationships between tables. It has been said over time that DBMS does not
impose any form of constraints or security to keep or protect any information
stored. However, it is the responsibility of the user or programmer to ensure
maximum prevention from an unauthorized user. In this regard, RDBMS is of
more regard to keep the integrity of a data and also prevent it from
unauthorized user.
Now, you know the difference between Database Management Systems and
Relational Database System. We will like to analyze each component of the
relational database management system.
What is a table?
A table is referred to as a collection of related data in a database, and it
consists of numerous columns and rows. A table can have hundreds, or
thousands or rows of data. It can also contain many columns of data. A table
is described as the simplest and most common form of data storage
component in a relational database. A table is also called data sheets,
because it contains different data but related subject.
Below is an example of a table in a relational database.
ID NAME AGE MARITAL DIAGNOSE
STATUS
1 Rasheed Karen 23 Single Chronic
Insomnia
2 Margaret Green 65 Widow Heart Failure
3 Paul Yul 35 Married Substance
Abuse
4 Mitchell Brown 40 Divorced Pneumonia
5 Zhi Rich 15 Single Juvenile
Diabetes

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

1 Rasheed Karen 23 Single Chronic


Insomnia

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

What is a NULL value?


A table may contain a blank field; it is referred to as NULL value because it
contains no item. You must understand that a null value is different from zero
value. A null value has been blank since the record was created.
5 Zhi Rich 15 NULL Juvenile
Diabetes
The Advantages of a Relational Database Management System
RDBMS is useful because it prevents data redundancy, and provides easy
access and control for users. Among all of these, there are 4 advantages of
RDBMS.
Data Structure: RDBMS provides data structure, in a simple and easy way
which is through the tabular format. A table makes it easy for database
enabled users to access the structure and organization of the stored data.
Another striking benefit is that database queries can search for related topics
or items in a database, this feature will make information easily accessible by
users.
Multi-User Access: Multiple users can be allowed in a RDBMS, because it
was designed to have a built-in locking and transactions features, which will
allow users to access the updated data without having any trouble. It also
prevents collision between two users who may be updating data.
Privileges: With RDBMS, you can have a privilege control. This means you
have the authority either allow any database user or restrict a user from
accessing the database. Authorization and privilege control features in an
RDBMS allow the database administrator to restrict access to enabled users,
and grant privileges to individual users based on the types of database tasks
they need to perform.
Network Access: RDBMS provides access to a database through a network
server that allows clients to make requests to connect and access network.
This simply means that a user does not have to log in to a physical computer
to access the database.
Maintenance: RDBMS has a maintenance feature that provides administrators
with instruments that can allow them to repair and manage database easily.
These maintenance features are usually automated.
Language: RDBMS supports SQL, and this structured query language uses
English language as its keywords. Several other RDBMS add some non-SQL,
and database-specific keywords to the SQL language.
Keys in Relational Database System
Keys are to help a user identify any row in a table. Also keys allow you
create a relationship between two or more relation tables.
1. Candidate key
A candidate key is a key that consists of one or more attributes that can
identify a row in a table individually. Consider the first table in this chapter; I
want you to assume that the Id and Age are unique. The patient’s ID can
identify a row in a table uniquely, so the patient’s ID is the candidate key and
the key too.
2. Super key
Super key is any superset of a candidate key. The super keys include
{Patients ID, name}, {Patients ID, firstname, lastname}
3. Primary key
The primary key is usually chosen by the database developer, and the primary
key is just one key among the candidate keys that can identify a row in a
table uniquely.
4. Foreign key
The value of a foreign key is required to match the value of a candidate key
in a table, either the same or different. The foreign key is set of different
attributes that matches with the value of a candidate key. When your
candidate key is referring to its own foreign key, it is called a self-referencing
table.
5. Non-Key Attributes
Non-key attributes are attributes that are different from the candidate keys in
a table.
Relational database management system stores data in tables and data stored
can grow larger and become bigger. However as they grow larger, the
structured query language is used to manage the data stored.
Chapter 4

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.

What is a Syntax Error?


A syntax error may occur when the sequence of characters are not written
correctly, or the compiler or interpreter cannot understand the source code, so
as to generate a machine code. It may also occur if there is a presence of
invalid equation.
Levels of Syntax
Lexical Syntax
Lexical syntax contains all the basic symbols of the programming language in
use. In computer, a sequence of characters is known as a lexeme. A lexical
syntax is however a rational language, which consists of grammar rules that
defines a set of lexems.
Concrete Syntax
Concrete syntax is a set of rules for writing expressions, programs and
statements and how they should be interpreted. It describes how the elements
of language are been displayed and edited. The concrete syntax describes
how the program looks to the programmer.
Abstract Syntax
Abstract syntax is defined as the internal representation of specific programs
by the simplicity of their grammar. The implementation of a language is
known as abstract syntax. The abstract syntax describes the way the program
looks to the evaluator or compiler.
Types of Syntax Programming
There are various syntax programming languages, and they are all distinct
from each other.
- Prolog syntax and semantics are set of rules that describe how the
prolog program should be written and interpreted. A prolog is a logic
and declarative language; hence the programmer has to think about
the programs in a different way. Prolog syntax is one of the first
language to be created, and it is still popular among languages today.
It has been proven useful for things like theorem proving, expert
systems, term rewriting, automated planning and natural language
planning.
- Perl syntax borrows syntax language from other languages like
Bourbe Shell, Lisp, Smalltalk. The Perl syntax is a flexible form
language, which can be edited, or manipulated in whatever form the
programmer wants. The Perl syntax contains both sequence of
declarations and statements, and in Perl language, every statement
must end with a semicolon. It is also a case sensitive programming
language, and does not allow characters and punctuations like @, $ or
%.
- PHP syntax and semantics form set of rules that describe how the
PHP program can be written and interpreted. The PHP syntax was
developed to follow the C syntax format, so it can be used in web
development.
- C syntax is basically a set of rules that a programmer must bear in
mind when writing the C program. The C program consists of
elements like header files, main function, and program code. C syntax
is a case sensitive language, so a programmer must follow the rules
for the C program to prevent syntax error.
All C statement must end with a semicolon, and every C instruction
should be written be written in lower case letters. The C language is
represented by numbers in three forms, the integral, real and complex
form.
- C++ syntax is a programming language developed by a Danish
computer scientist, Bjarne Stroustrup, to be an extension of the C
programming language. C++ syntax is used in varieties of application
domains, which makes it a general-purpose language and a standard
by the International Organization for Standardization. Although the
C++ inherits most of C’s syntax features, however it offers efficient
hardware access and abstractions compared to other language.
- Java syntax is the set of rules that describes how the java program
should be written and interpreted. Although, Java was derived from
both C and C++ syntax. Despite these derivations, here are few
differences between these languages. In Java there are no available
variables, or global functions, but there are data members which are
considered as global variables.
- JavaScript syntax is the set of rules that a programmer must bear in
mind before writing a JavaScript program or interpreting it. The
JavaScript defines two types of values, namely: fixed values and
which are called literals, and variable values that are called variables.
JavaScript literals are important rules that defines how fixed values
should be written, and the rules guiding the values are as follow:
- Numbers are to be written with or without decimals
- Strings are text, or words writen between a single quote or a double
quote
While JavaScript variables are used to store data values. The var
keyword is used by JavaScript to declare variables. The var keyword
simply means a variable, and a variable can be changed at any time.
Java derives some of its features from Java syntax, and also inherits
some features from Awk and Perl. Despite having a bit of similarities
with Java syntax, it is a totally different language from JavaScript
syntax. JavaScript is case sensitive and a programmer must always
bear that in mind when constructing a statement.
- Python syntax and semantics is a set of rules that governs how the
python program will be written and interpreted. The python program
was developed with a high level of readability, and it uses English
keywords more and even frequently, than other languages. Moreover,
the python language has a few similarities to Perl, C and Java syntax,
and also some distinct differences between these languages. A python
program is however divided into logical a line which is created from
one or two physical lines. When this logical line is terminated, it is
usually done by the token newline.
A line in computer programming contains just tabs, spaces, and
possibly a comment called a black line which is usually ignored by
the python’s interpreter.
While a physical line on the other hand, are sets of sequence of
characters that are terminated at the end-of-life sequence. The python
syntax uses words known as reserved words and these words are as
follow: false, class, finally, none, continue, for, from, global, as,
assert, break et cetera.
- Lua syntax is a high-level multi-paradigm that contains a lot of
instructions that was created for a specific use and execution of task.
The Lua program allows programmers to implement namespaces,
classes and other features. Lua is simple and flexible
- Haskell syntax is a multi-dimensional language, and here the few
reasons why it is so. Haskell syntax is a language that is suitable for
any kind of program, which is why Haskell syntax is addressed as a
general-purpose language.
Aside from its ability to fit into any program, it is also a statically
typed language. The Haskell program is divided into two phases, the
compile time and the run time. When each of your variables has a
type that indicates the kind of data that variable is allowed to hold, it
is a compiled time phase. Java and C syntax are examples of a
statically typed language.
In addition, Haskell can allow you create anonymous functions, get
them stored in variables and pass them to other functions as
argument. The functions of the Haskell language will always produce
the same result and value.
Syntax in SQL
I believe by now you already have an overview of what syntax is all about.
Syntax is simply sticking to grammar and rules guiding the programming
languages. Every language has its own syntax, likewise SQL. Every
punctuation, symbols, characters has a meaning when used in SQL. Every
command in SQL must end with a semi colon. When writing a command,
whether while using SQL or another programming language, it is effective
that you learn and do things according to the rules. Leaving too much space,
using a capital letter can cause syntax error if it is the punctuations or letters
used wrongly.
Preventing syntax error is possible if you always create a clean and concise
programming command.
Chapter 6

SQL Data Types


In this chapter, I will describe all the SQL data types that PointBase supports.
In SQL, data types define the type of data each column can contain. In other
words, it describes the value the column can hold. Each of the column in any
data base table is expected a specific name and also a data type. It also
identifies the interaction between SQL with the stored data
Therefore, an SQL developer must decide when creating tables, the type of
data that will be stored in each of the columns.
It is important to note that the data base may likely have different names in
each data base. But even if the names are the same, the size or even details
may be different.
Each PointBase data types will be described in details, and the converting
data types will also be discussed.
The PointBase supports the following listed data types for its column and
also for its parameter declarations
1. CHARACTER [(length)] or CHAR [(length)]
2. VARCHAR (length)
3. BOOLEAN
4. SMALLINT
5. INTEGER or INT
6. DECIMAL [(p[,s])] or DEC [(p[,s])]
7. NUMERIC [(p[,s])]
8. REAL
9. FLOAT(p)
10. DOUBLE PRECISION
11. DATE
12. TIME
13. TIMESTAMP
14. CLOB [(length)] or CHARACTER LARGE OBJECT [(length)] or
CHAR LARGE OBJECT [(length)]
15. BLOB [(length)] or BINARY LARGE OBJECT [(length)]

CHARACTER [(length)] or CHAR [(length)]


The CHARACTER is one of the data types in SQL programming language.
This data type accepts character strings, which includes Unicode, of an
already fixed length. It is important to specify the length of the character
string in the data type declaration.
Take for instance, CHARACTER (n) in which represents the desired length
of the particular character string. In this case, if no length is indicated during
the declaration, then the developer should take the default length as 1.
CHARACTER data type is designed to have a maximum of that can be up to
the table page size while the minimum length is always 1. But in any case,
where a Character strings is larger than the default page size, it can be stored
as a Character Large Object (CLOB).
It is also important to note that CHARACTER(0) is always not allowed and
such raises an exception.
Furthermore, if for instance you assign specific value to a CHARACTER
column which contains fewer characters than the already defined length, then
the remaining space is filled with blank characters. At this point, any
comparisons made to a CHARACTER column must of necessity take these
trailing spaces into cognizance.
However, in order not to truncate the character string to a defined length, you
should avoid assigning a value which contains more characters than the
already defined length. And if at all any of the truncated characters are not
blank, then an error must be raised.
VARCHAR (length)
This is also another data type. It accepts character strings, including Unicode,
with a variable length that is up to the maximum length which is already
specified in the data type declaration.
In a VARCHAR declaration, the maximum character string length allowed is
defined by a positive integer which is always in parentheses. Take for
instance, VARCHAR (n) implies that any length of character string can be
accepted up to “n” characters in length.
However, the length parameter may take any value ranging from 1 to the
current table page size. Character string can be truncated to the defined length
if you attempt to assign a specific value that contains more characters than
the already defined maximum length. Also, if any of the truncated characters
is not blank, an error must be raised.
It is important to also take note that VARCHAR (0) is not allowed; And if
this occurs, an exception must be raised .
If for any reason, your character strings that are longer than the current table
page size needs to be stored, then the Character Large Object (CLOB) data
type should be used instead.
BOOLEAN
For the BOOLEAN data type, storage of two values is allowed. For this data
type, parameters are not required when declaring a BOOLEAN data type.
The case insensitive keywords that is “TRUE” or “FALSE” are used to
assign a value to the data type as well as for Comparisons. An error is raised
if you try to assign any other value to a BOOLEAN data type,
Examples of BOOLEAN data type:
Valid Invalid
TRUE 1
true 0
True Yes
False No
SMALLINT
Another Data type that is the SMALLINT which accepts numeric values
alongside an implied scale of zero. In this data type, integer values are stored
between the range 2^ -15 and 2^15 -1. An error will occur in an attempt to
assign values outside of this already defined range.
However, if for any reason you assign a numeric value with a precision as
well as a scale to a SMALLINT data type, the scale portion will eventually
truncate without even rounding.
It is necessary to always use the INTEGER data type whenever there is a
reason to store values which are beyond the already defined range (2^-15) to
(2^15)-1,
INTEGER or INT
This data type also accepts numeric values which has an implied scale of
zero. The INTEGER or INT data type always stores any integer value
between the range of 2^ -31 and 2^31 -1. An error will automatically occur if
any attempt is made to assign values outside of this range.
In addition, the scale portion will truncate even without rounding if a numeric
value is assigned with a precision and scale to an INTEGER data type.
It is noteworthy to use a DECIMAL data type which has a scale of zero if
you need to store integer values beyond the set range (2^-31) to (2^31)-1.
DECIMAL [(p[,s])] or DEC [(p[,s])]
This data type accepts numeric values. A precision and a scale are defined in
the data type declaration. The precision in this data type is always a positive
integer that indicates the number of digits that the actual number will contain.
While the scale is also a positive integer that indicates the number of these
digits that will stand for decimal places to the right side of the decimal point.
Also, the scale of the precision is always larger than the DECIMAL.
There are three major ways to declare the DECIMAL data types. These
declarations only control how the number is presented to a typical SQL
query, but not necessarily how it is stored. These include;
DECIMAL - Precision defaults to 38 while Scale defaults to 0
DECIMAL(p) - Scale defaults to 0
DECIMAL(p, s) – the Precision and Scale are usually defined by
the user

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

OPERATORS IN SQL (STRUCTURED QUERY


LANGUAGE)
There are different kinds of operations which are performed to either
manipulate or even retrieve data while we are handling different data in our
database. The Structured Query Language (SQL) which is the baseline of the
database management systems, provides various operators which are
instrumental to perform such diverse operations. Some of these Structured
Query Language (SQL) operators shall be discussed in this chapter.
What is an Operator in Structured Query Language (SQL)?
An operator in Structured Query Language (SQL) refers to a word or a
character set aside primarily in a Structured Query Language SQL
statement's WHERE clause to perform certain operation(s), such as
arithmetic and comparisons. These Operators are used to specify some
conditions in a Structured Query Language SQL statement and also to serve
as a link or element of combination for multiple conditions in a single
statement.
There are six common operators in Structured Query Language (SQL).
Which are;

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:

Operator Description Example

This Adds values on both sides of


+ (Addition) the operator a + b will give 30

This Subtracts the right hand


- (Subtraction)
operand from the left hand operand. a - b will give -10

* This Multiplies values on both sides a * b will give


(Multiplication) of the operator. 200

This Divides left hand operand by


/ (Division) right hand operand. b / a will give 2

This Divides left hand operand by


% (Modulus) right hand operand and returns b % a will give 0
remainder.

Structured Query Language SQL Comparison Operators


This Structured Query Language SQL assumes 'variable a' hold 10 and
'variable b' hold 20.
Examples:

Operator Description Example

This operator checks if the value of two


= operands are equal or not, and if equal then (a = b) is not
this condition becomes true. true.
This operator checks if the values of two
!= operands are equal or not, and if the values (a != b) is true.
are not equal then this condition becomes
true.

This operator checks if the values of two


operands are equal or not, and if the values
<> are not equal then this condition becomes (a <> b) is true.
true.

This checks if the value of the left operand


is in any way greater than the value of the (a > b) is not
> right operand. And if the value is greater, true.
then this condition becomes true.

This checks if the value of the left operand


is in any way less than the value of right the
< operand. And if it is less, then this (a < b) is true.
condition becomes true.

This checks if the value of the left operand


is greater than or equal to the value of the (a >= b) is not
>= right operand. And if it is then the condition true.
becomes true.

This will check whether the value of the left


operand is less than or even in any way
<= equal to the value of the right operand, and (a <= b) is true.
if it is then this condition becomes true.

This checks if the value of the left operand


is not less than the value of the right
!< operand. If it is then this condition becomes (a !< b) is false.
true.
This will check if the value of the left
operand is less than or not greater than the
!> recognized value of the right operand. If the (a !> b) is true.
answer is yes, then this condition becomes
true.

Structured Query Language (SQL) Logical Operators


This operator compiles the list of all the logical operators that are available
in Structured Query Language (SQL)
For example,
Serial Operator Description
Number
1 ALL The ALL operator is basically used to compare
a value to all the other values that are contained
in another value set.
2 AND The AND operator is another operator in SQL
which allows the existence of more than one
condition or multiple conditions in a Structured
Query Language SQL statement's WHERE
clause.
3 ANY The ANY operator is also another operator in
Structured Query Language SQL which is used
for comparison of a value to any other
applicable value in the list which is in line with
the condition.
4 BETWEEN The BETWEEN operator is an operator in the
Structured Query Language which is used for
searching for values which are within a set of
values in which the minimum value and the
maximum value are given.
5 EXISTS There is also another operator in Structured
Query Language SQL which is known as The
EXISTS operator. This operator is used to
search mainly for the presence of a row in an
already specified table which meets a certain
standard or condition.
6 IN The IN operator is a type of operator in
Structured Query Language SQL, which is used
to compare a value to a compiled list of other
literal values which have already been specified.
7 LIKE The LIKE operator is another type of operator in
the Structured Query Language SQL which is
used to compare a particular value to other
similar values and this is done by using the
wildcard operators.
8 NOT The NOT operator is a type of operator in
Structured Query Language SQL, which is used
to reverse the meaning of the logical operator
with which it is being used. Take for instance:
NOT BETWEEN, NOT EXISTS, NOT IN, etc.
This is also referred to as a negate operator.
9 OR The OR operator is another type of operator in
Structured Query Language SQL which is used
to combine different conditions in a Structured
Query Language, SQL statement's WHERE
clause.
10 IS NULL The NULL operator is a unique operator in the
Structured Query Language SQL which is used
to compare a particular value with a NULL
value.
11 UNIQUE The UNIQUE operator is a different type of
operator in Structured Query Language SQL
which searches every single row of an already
specified table for exclusiveness. Which are not
duplicates.
Structured Query Language SQL Compound
Operators
Serial
Operator Description
number
1
+= Add equals

2 -= Subtract equals

3
*= Multiply equals

4 /= Divide equals

5 %= Modulo equals

6 &= Bitwise AND equals

7 ^-= Bitwise exclusive equals

8
|*= Bitwise OR equals

Structured Query Language (SQL) Character Operators


This is a type of operator in the Structured Query Language SQL which is
primarily used in various expressions simply to manipulate different
character strings.
For instance,
Operator Description Example
II Concatenates character SELECT 'The Name of the
strings employee is… ' || ENAME FROM
EMP
Structured Query Language SQL Concatenating Character
Strings
It is very possible to concatenate character strings. This can easily be
achieved using the Oracle Database Lite. When this is done, the following are
the results that will be obtained;

1. Whenever you concatenate or link up two-character strings in a


chain or series, there is always a result obtained which is another
character string entirely.
2. Through concatenation, the Oracle Database Lite is able to preserve
trailing blanks which are in character strings. And this is achieved in
spite of the strings' datatypes.
3. The concatenate character function is provided by the Oracle
Database Lite as a clear alternative to the already known vertical bar
operator.
Take for instance;
SELECT CONCAT (CONCAT (ENAME, ' is a '),job) FROM EMP WHERE
SAL > 2000;
It’s important to take note that, the Oracle Database Lite usually treats as null
or any zero-length character strings.
Furthermore, whenever a zero-length character string is concatenated with
another operand, the result obtained at the end of this concatenation is always
the other operand.
However, the only situation or circumstance that a null value can be obtained
is through the concatenation of two-null strings.
Structured Query Language SQL Wildcard operators
Wildcard operators are another set of operators in Structured Query Language
SQL which are used alongside LIKE operator. Under this type of operator,
there are four basic other operators classified as wildcard. These are;
Serial Operator Description
number
1 % This is a type of wildcard
operator which is used in
substitute of zero or even more
characters.
2 _ This type of wildcard operator is
used in substitute of just one
character.
3 [range_of_characters] This is another type of wildcard
operator in Structured Query
Language SQL which is used
simply to fetch various matching
sets or even range of characters
which are already specified inside
the brackets.
4 [^range_of_characters] or This is a type of operator that is
[!range of characters] used to fetch basically non-
matching set or even a range of
characters which are already
specified inside the brackets.
Chapter 8

MANAGING OBJECTS IN SQL


SQL Server Management Objects (SMO) refers to objects which are
designed for programmatic management of Microsoft SQL Server. SMO can
be used to build a customized SQL Server management application.
As powerful and extensive the managing SQL Server may be, there will
definitely be times when you, the user, would be better served by an SMO
application.
For instance, in cases where we have new users on the platform or you desire
to cut down cost on training new users, it is advisable to use the user
applications which controls the SQL Server management tasks. At this point,
there may be necessary for you to create a customized SQL Server database,
or you may create another application which helps to create and monitor the
efficiency of the indexes.
Also, an SMO application could be used to include a third-party hardware or
even software effortlessly into the database management application.
It becomes very easy to manage a multi-version environment simply because
the SMO is quite compatible with the SQL server 2005.
The SMO has some features which are unique to it, some of these include:

1. The batched execution of Transact- SQL statements: For SQL, the


Statements are always batched so as to improve network for
optimum performance.
2. Optimized object instance creation and cached object model: For
this feature, only objects that are specifically referenced are
loaded. This implies that after objects are created, the properties
are only partially loaded. Hence, the remaining objects and
properties are later loaded after they are referenced directly.
3. Management of the SQL Server services alongside WMI Provider:
Just like most servers, the SQL Server services can equally be
started, paused or even stopped programmatically.
4. Capture Transact-SQL statements: This feature means that the
SMO allows the possibility of operations to be captured into
scripts. Most times, Management Studio uses this particular
capability of SMO to script an operation rather than executing it
immediately.
5. The use of Unique Resource Names (URNs): One of the
advantages of this particular feature is that it allows you to create
some instances and also references of SMO objects
6. Advanced Scripting: It’s possible to generate Transact-SQL
scripts which helps to re-create SQL Server objects. This
describes relationships to other objects on the instance of the SQL
Server.
Aside the above features, there are yet some other new features and
components which the SMO also represents as new properties or objects.
Many of these features are also introduced in the SQL Server 2005 (9.x).
These features include the following:

1. The index and Table partitioning which is basically for storage of


data on a partition scheme.
2. Row level versioning as well as Snapshot Isolation which is
useful for increasing concurrency.
3. HTTP endpoints which helps in managing SOAP requests.
4. Snapshot databases which is useful for the creation of read-only
copies of the databases.
5. XML indexes, XML schema collection, as well as XML
datatype. These provide validation and storage space for XML
data.
6. It also features the Service Broker support which helps
essentially in message-based communication.
7. The Synonym support which is for multiple names of SQL
Server database objects.
8. There is also a feature known as the Registered Servers support.
This is for registering basically connection information.
9. The management of Database Mail. This is a vital and widely
useful feature. It allows you to create e-mail profiles, e-mail
servers, and e-mail accounts right on the SQL Server.
10. In instances where you need to trace and replay events on SQL
Server.
11. There is also a feature that supports security keys for encrypted
files.
12. There is also a feature known as the DDL triggers which is
basically for adding functionality whenever DDL events occur.
The SMO namespace is termed as Microsoft.SqlServer.Management.Smo.
SMO is usually executed as a Microsoft.NET Framework assembly. This
implies that the common language runtime from the Microsoft.NET
Framework version 2.0 needs to be installed even before you use the SMO
objects.
The SQL Server SDK option is used to install the SMO assemblies by default
with the Global Assembly Cache (GAC).
SMO Classes
There are basically two categories of SMO classes. These are:
1 Instance classes
2 Utility classes
Instance Classes
The instance classes in the SMO category represent the SQL Server objects
such as tables, databases, stored procedures servers, and triggers. The server
connection class is useful for establishing a good connection to the instance
of SQL Server. It is also useful as a control system for capturing of the
commands sent to it.
In addition, the SMO instance objects form a specific hierarchy which stands
for the hierarchy of a database server. The SQL Servers are located at the top
of the instances, under which are the databases, and also following on with
columns, tables, triggers and so on.
In a logical instance where there is a relationship between one parent to many
children, such as a table having one or more columns, in such a case, then the
child is represented by a collection of objects. Otherwise the child is just
represented by an object.
Utility Classes
The Utilities classes are a group of objects which have been created
exclusively to carry out specific tasks. They have been divided into different
object and are ranked based on function:
These classifications includes;

Transfer class. This becomes useful when you need to transfer


schema and data to a different database.
Backup and Restore classes. They are useful for backing up and
restoring databases.
Scripter Class: This is used whenever there is a need to create
script files for the regeneration of objects as well as their
dependencies.

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:

1. Simple 1-phase scripting (this creates the script in one step)


2. Advanced 3-phase scripting (this creates the script in three steps;
dependency discovery, list generation, script generation)
3. Two-way dependency discovery (this allows for discovery of
dependencies, or dependents)
4. Response to progress events
5. Response to error events

Unique Resource Names


The Unique Resource Name (URN) is a key concept in using the SMO object
library. The URN uses a syntax which is similar to XPath. The XPath is a
hierarchy path which is used to specify an object in which each level has
qualifiers as well as functions. In SMO, the URN is made up of two main
elements, one is the path and while the other is the attribute naming which
has restricted functions. The path is usually used to specify the location of the
object while on the other hand, the attribute naming allows for a reasonable
level of filtering.
An example of an URN for a database is
/Server/Database[@Name='Adventureworks2012']
The object of the URN can be retrieved by referring to its URN property. The
Scripter object also uses URNs as parameters passing object references to the
method of the Scripter object.

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

RELATIONAL DATABASE CONCEPTS


You have reached yet another enlightening chapter. It is great that you
invested in learning. First, we will define some common basic terms to
explain further this chapter.
What is Data?
Data can be defined as facts and statistics which are related to any object
under consideration. For example, your name, height, weight age, etc. these
are some specific data related to you. Also, an image, or a document or even
a picture can also be considered data.
What is a Database?
Database can be said to be a place reserved to store and also process
structured information. Database can also be said to be a systematic
compilation/ collection of data. It is not a rigid platform, information stored
in a Database can also be manipulated, modified or adjusted when the need
arises. Database also supports the retrieval of stored information or data for
further use. Database has many forms that store and organize information
with the use of different structures. In a nutshell, data management becomes
easy with databases.
For instance,
An online telephone directory would certainly use database for storage of
data pertaining to phone numbers, people, as well as other contact details.
Also, an electricity service provider will need a database to manage billing
and other client related concerns. Database also helps to handle some
discrepancies in data among other issues.
Furthermore, the global and far-flung social media platform known as
Facebook. Which has a lot of members and users connected across the world.
Database is needed to store all the information of users, manipulate and also
present data related to users of this platform and their online friends. Also,
database helps to handle various of activities of users’ birthday, anniversary
among others, as well as advertisements, messages, and lots more.
In addition, most businesses depend absolutely on database for their daily
operation. For complex multinationals database is needed to take inventory,
prepare payroll for staff, process orders from clients, transportation, logistics,
and shipping which often requires tracking of goods. All these operations are
made easy because of a well-structured data base.
It can go on and on providing innumerable examples of database usage.
What is a Database Management System (DBMS)?
But how can you access the data in your database? This is the function of
Database Management System (DBMS). DBMS can then be said to be a
collection of programs which enables its users to gain access to the
information on the database, manipulate data, as well as reporting or
representation of data. Database Management System also helps to control
and restrict access to the database.
Database Management Systems was first implemented in 1960s and it cannot
be said to be a new concept. From history, Charles Bachmen's Integrated
Data Store (IDS) is the first ever Database Management Systems. After some
time, technologies evolved speedily and before long wide usage and diverse
functionalities of databases have been increased immeasurably.

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;

1. Data is organized and then stored in tables.


2. Databases are responsible for holding a collection of data stored in
tables.

Normalization and Denormalization


Normalization is a concept used by relational databases. Normalization is a
kind of design technique which helps to minimize the replication of
information. It helps to reduce the possible risk of errors in data which may
arise by coping with the same information that are not kept in synchronized
manner. Relationship helps to lessened or eliminated completely the likely
duplication required.
For instance, from the example given above, the fleet database could as well
be created with just a single table which contains all employees and as well as
the details of the vehicle that they drive. But if for instance two employees
drive the same vehicle, then it’s likely the vehicle's detail is entered twice
against their names and this ends up being maintained in two places. But by
creating a relationship between the table for recording the employee and the
vehicle’s table, that makes the vehicle’s data appear only once and it only
requires updating in just one place.
Furthermore, denormalization is the exact opposite of normalization. For a
denormalized database, there is always a duplication of information. With
this feature, the denormalized database performs better than a normalized
database at the cost of increased database size and also the risk of data
integrity problems. In addition, denormalized databases are also useful where
the speed of data retrieval is of utmost importance, such as in a database
which is useful for reporting purposes only.
Elements of a Relational Database Schema
There are different elements to a relational database which are created using
Microsoft SQL Server. Each of which forms a part of the database's schema .
The schema is that logical data model which determines the type of
information that may be stored in the database and how the information needs
to be arranged.
Some of these keys shall be discussed below:
1. Tables
This is the most essential element of a relational database. Information within
the database is held in Tables. A table contains both row and column. The
elements in the column grid contains elements of data required while the row
contains individual record. Therefore, the terms "columns" and "rows" are
those used to describe the schema of the table and its data respectively.
Employees Table
Payroll ID Name Cell Phone
1003 John Cain Samsung
1004 Adams Smith Nokia
1005 Lisa Gold Techno
1006 Abraham Mike I phone

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

HOW TO DEFINE DATA IN SQL


Defining data in SQL can be achieved with a data description language which
is also known as DDL. Data description language can be a syntax which is
similar to a computer programming language for defining data structures,
especially database schemas. DDL statements usually create, modify, and
also remove database objects such as indexes, tables, and also users.
The most common types of data description language statements are
CREATE, to create database, tables and other database objects; ALTER, to
alter the Database objects; and DROP, to drop objects.
Relationship between Data Description Language (DDL) and
Structured Query Language (SQL)
Before we proceed, I would like to point out the slight link between the data
description language (DDL) and Structured Query Language (SQL)
The Structured Query Language (SQL) is a type of language which is
generally and widely used to manipulate data and also to manage data in a
database management system. Whereas on the other hand, the data
description language (DDL) is said to be one of the features which is found in
the Structured Query Language (SQL) language. It is useful for defining the
common database structures such as Create, Alter, and also Drop.
The declarative syntax commonly used by many data description languages
with a common usage which is to define the data types as well as the
columns. But what then is so unique about the Structured Query Language
(SQL)? The Structured Query Language stands out because it uses a
combination and compilation of imperative verbs whose effect and impact is
reflected in the modification of the schema of the database simply by
changing, adding, or even deleting of definitions on tables or even other
elements.
The data description language is not really a separate language. The above
statements can also be mixed and combined with the Structured Query
Language (SQL) statements.
The concept of DDL
There is a concept of data definition language data description language
which was first introduced alongside the Codasyl database model. In this
concept, the schema of the database was initially written in a language syntax
which describes the records, sets as well as the fields of the user data model.
After some times, the data description language was seen as a subset of the
SQL (Structured Query Language) which is useful for declaring columns,
tables, constraints, as well as data types.
However, the Structured Query Language, SQL-92 is used to query
introduced a schema manipulation language and schema information tables to
query schemas. These information tables were seen as the SQL/Schemata in
SQL:2003.
In addition, the term data description language (DDL) can also be described
completely in a different way. It is widely used in a different generic
perspective in which it refers to any kind of formal language that is used to
describe data or it can also be used for information structures.

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:

A comma-separated list which consists of any of the following


Column definition: a typical illustration is [column name] [data type]
{NULL | NOT NULL} {column options}
Primary key definition: These refers to the PRIMARY KEY
([comma separated column list])
Constraints: {CONSTRAINT} [constraint definition]
Relational Database Management System (RDBMS) specific
functionality
For instance, we can take the following as an example statement which is
carefully used to create a table named staff with a few columns is:
CREATE TABLE staff
ID INTEGER PRIMARY KEY,
first_name VARCHAR(50) not null,
last_name VARCHAR(75) not null,
fname VARCHAR(50) not null,
dateofbirth DATE not null
DROP statement
If for any reason there is a need to destroy an existing database, index, views
or tables. Then the DROP statement is a command to employ for such a task.
One of the ways that a DROP statement in a Structured Query Language
(SQL) functions is by removing a component from a RDBMS which is
known as Relational Database Management System. The RDBMS
(Relational Database Management System) being used at a particular time
also determined the type of objects that can be dropped. But most of them
support the dropping of users, tables, and also the databases.
However, a rolled back of the data description language (DDL) command is
possible in a situation where some systems (such as PostgreSQL) allow
DROP as well as some other data description language (DDL) commands to
occur inside the same transaction.
For instance, a typical usage of the DROP statement command is seen as
below;
DROP objecttype objectname.
You may wonder, with all these functions of the drop statement, where does
the DELETE command stand?
Usually, there is a little bit of difference between the DROP statement and
also the TRUNCATE and DELETE statements.
The difference is, for the DELETE and TRUNCATE statements, the table
should not be allowed to remove the table itself. For example, this difference
can be further seen in this illustration. a DELETE statement has the capacity
to only delete few (or all) data that are not included from a table meanwhile
the table itself is left undeleted in the database. But for the DROP statement,
as the content or data in the table is removed, the table is equally deleted
completely.

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

WORKING WITH INDEXING, VIEWS AND


QUERIES
To start off, one needs to understand in-depth the purpose and processes of
each function given that they work hand in hand.
INDEXING
Just like in books, the basic function of indexing is to search or find answers
to a query in a database. It is a special structure in the database that is
developed upon using the “create index” statement. It however makes no
changes to the database, as all it does is hold a copy of the data table indexed,
and refers to the table to fetch data relating to it. With a characteristic
redundancy, it serves as a referral link to the actual information which is
stored in a different place (i.e. upon a query, the SQL Server moves to find
the required value in the index, then proceeds to use the index to quickly
locate the entire row of data). Without the index, the only possible way to
find a value by row is by a full table scan. However, it doesn’t have a good
effect on the performance as it is relatively very slow.
Database index which just like in books are well defined, and in order,
distinguishes itself from that books by processing updates using the “insert,
delete and update” statements upon request without altering the existing
order. Also, indexes are made up of a set of pages also known as index nodes
which are arranged in a hierarchical nature known as B-tree Structure.
Typically, they have the root node at the foremost part of the structure, and
the leaf node at the bottom.
The swift reply of index to queries however depends on its style, which could
either be clustered or non-clustered indexes.
Clustered Indexes: Clustered indexes stores the entire data rows at the
bottom level of the index. In this style of indexing, the entire row of data
related with the query/value requested would be stored in the leaf node, and it
is usually sorted in either ascending or descending order. A table with
clustered index is also known as a clustered table.
Non-clustered Indexes: Unlike the clustered indexes, only specific data
from indexed columns and row locators are stored, hence it cannot be sorted
like clustered indexes. However, there is room to create more than one non-
clustered index per table. This way, the data rows are only visible to the SQL
Server upon further probe to locate the entire row the data belongs to. A table
with a non-clustered index is often referred to as a heap.
Index Types
There exists other ways to configure indexes asides the clustered and non-
clustered style. They are:
Composite Index: This refers to an index that contains between 1 and 16
columns as long as it doesn’t exceed the 900-byte limit. Both clustered and
non-clustered indexes could be composite indexes.
Unique Index: This is the index responsible for retaining the uniqueness
of every value in the indexed column. However, in composite indexes, the
uniqueness is across the columns as a whole, and not individual columns. A
unique index is automatically created upon the definition of a primary key.
Covering Index: This is a type of index that combines columns that are
necessary for processing a given query. This way, multiple columns could be
embedded into becoming one.

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:

1. Restricted Modification: This way, only those with access to the


table can initiate major edits such as INSERT, UPDATE, and
DELETE.
2. Saved Database Space: Here, query doesn’t always have to refer
to tables, hence incessant tables are not created as actual data are
not stored.
3. Additional Security: Since selected columns and details are
exposed to the public upon the request of a query, there is more
security for other sensitive details contained in a table.

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.

The chart above is a simple diagrammatic explanation as to how they are


related. Once a query is initiated, a view that was programmed to respond
crawls through the index searching for the data set required to respond, and
gets directed to the information that is being required. This information, is
then sent back to the view which in turn gives response to the query
displaying only the specific information that is related to the query and with
general access. The synergy of the view and the index, forms an indexed
view which is beneficial as the processes are now more reduced, given that
the various views are now linked to specific and tailored indexes.
Chapter 12

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:

1. Software – software is used to ensure no one could gain


unauthorized access to the information in the database through
various means such as hacking, viruses, or any other similar
process. By this, the data is protected and secured.
2. Physical controls – an example of physical form of securing
the database especially for multinational countries is the use of
man guards or securities to patrol the premises to identify any
potential weaknesses or possible security bridge.
3. Administrative controls – this refers to systems which use
passwords, and other restricted access of certain individuals from
accessing some database. This also means that there are people
that do have access to some information because they are below
a particular level.

Importance of Database security


Some of the importance of database security is that important files are
protected when there is a fire outbreak or a damage in the server which does
not result in loss of data. Also, data security helps to prevent the lost data that
may arise through corruption of files or even any form of programming
errors.
Some companies are also able to block out some attach or firewalls so as to
keep their sensitive information in safe condition. Furthermore, database
security also helps to prevent some vital infection that may destroy the file
and information.
Database security in SQL
Like some other software programming languages, Structured Query
Language (SQL) can also be employed for security. Efforts must be made to
lockdown the database so as to keep the data private and secure.
I shall be discussing some steps that will guide you through few basic
principles of database security and also how these principles can be
implemented.
In addition to a hardened web server configuration, a secured database server
will help to protect an application from becoming a form of entry point. This
also helps to keep your network and keep your data from being dumped
straight on the internet.
However, when provisioning a new Structured Query Language (SQL)
server, it is important to remember the factor security in from the get-go;
growth is constant. It should be a part of your regular process, not something
applied retroactively, as some key security measures require fundamental
configuration changes for insecurely installed database servers and also some
applications.
What are some of the ways to secure your database on Structured Query
Language (SQL) server?
Securing the database server
1. Separate the Database Server
This process involves isolation of the database server. What then is isolated?
The production database servers must be separated or isolated as much as
possible from the other applications and services. There are some dedicated
databases which do not have to worry about conflicting traffics or contending
reserve because they have a small footprint. Also, operating system should be
lean, and the database must contain only the necessary services that installed
and running. Furthermore, avoid installing other applications in the server
except the application is required by the database server.
Try and consider putting the Structured Query Language (SQL) server in a
restricted network segment/VLAN. Although it depends on the environment
where the server is kept. This result in only authorized traffic to pass through
it. Typically, it is only an application server or a web server that will be
talking directly to the database. At this point, fairly limiting network policies
can be enacted so as to prevent any illicit connection. The database server
should not be open anyhow.
2. Tailor the Database Installation
Both the MSSQL and MySQL offer multiple features, which are not
common. When the pieces are removed, there will be no need to reduce the
possible inroads for exploitation.
3. Keep it Updated
The version of both MSSQL and MySQL should be kept up to date to
prevents it from being obsolete and open it up to new features. Ensure that
you install security patches to prevent every attack and this is achieved by
simply sealing up these flaws.
However, having a consistent patching schedule and also employing a
protocol can help to execute updates in a test environment so as to prevent all
negative features which can be discovered without interrupting production.
There are many shops that are lack of this luxury, thinking they can install
updates directly into production and hoping for the best. Usually this
approach works well, fortunately, but if it doesn’t, it can go bad quickly. So
at least understand your rollback options and procedure, and exactly what the
patch is changing.

4 Restrict the Database Processes


The user of the database service runs determine the access that the database
processes will have to the rest of the server. This also includes the file
system, the ability to carry out programs, and so on. Just like some other
applications such as Linux, MySQL usually runs under a particular dedicated
mysql user account which has minimal permissions even to the rest of the
other server. This can easily be verified even with a simple PS command, and
it is important to ensure that the MySQL has not yet been configured yet to
run as root which is a process or an instance where it definitely happens,
especially in extreme circumstances. Take troubleshooting an outage for
instance, and then it is not reconfigured once the crisis has already been
prevented.
Failure to take this particular step can possibly allow a compromised database
server to compromise the rest of the entire machine and possibly infiltrate the
whole network.
5 Restrict SQL Traffic
As mentioned earlier, database servers usually have a separate server (or
several others) which is connected to it. And for example, if this happens to
be the case, then access to the server which is on the database ports should be
blocked in all other places. Then by only allowing SQL traffic to and from
designated IP addresses, you can definitely be certain that a dangerous actor
or an infected client which is inside the firewall doesn’t necessarily hammer
away at your own server. However, in some other instances, clients will have
to connect directly to the database server itself. For instance, with a typical
thick client front end application. The same logic also applies here, which is
to restrict those other SQL connections to a specific IPs (or at least an IP
segment) that definitely needs it. This is because these are different
endpoints, but you must be certain to secure them well, due to the fact that
the malware can also scan and attack SQL servers.

6 Set a Strong Admin Password


When using MSSQL, the SA account is usually used whenever a mixed-
mode authentication is selected. Microsoft usually recommends that a
Windows integrated auth should be used. But many applications usually
require the mixed-mode in order to support their own database users and also
their connection strings. If for any reason you do have the mixed-mode auth
enabled, then be certain to secure the SA account with a complex password
so as to also prevent it from being brute forced.
7 Secure Your Backups
One thing is that your backups usually have the same data even as your
production databases and this needs to be secured or protected with as much
care as the entire server itself. This step can also mean that you need to lock
down backup directories completely, restrict to some extent access to the
server or even storage hosting of the data, provide physical or human security
of the entire removable media, ensure network access to all the backups and
also reviewing anyone who has access to carry out one activity or another
and access backups. But you should also remember that the backups are a
major part of your data ecosystem when it comes to security or someone may
just go through the open window and get around the existing barricaded door
and access the server.
Chapter 13

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:

Various DBMS engines operating from different control


management languages and architectural meta-models.
Various hardware platforms, such as workstation and server
(network, web, and database)
Middleware connectivity that serves to connect both the
hardware and operating system as well as the various locations
involved.
Diverse operating systems with each having different set of
commands and interface.
Multiple physical location with data widely distributed across
street, town, state, or country.

What Does a Database Administrator Do?


With over 2.5 quintillion bytes of data estimated to be created daily, and still
increasing as time passes by, the quantity of data in recent times has
surpassed what has ever been seen, hence the increase in the number of
databases, which results in more need for database administrators. Also,
going by the importance of maintenances, corporations and firms that use the
DBMS software needs to hire specialized IT personnel called database
administrators or DBAs. The role of a database administrator offers a chance
to be creative, and solve problems related to database development by
scripting software and testing the functionality of a database in order to keep
the data clean and secure. The topmost priority of a database administrator is
to maintain the integrity and security of the data because it loses its value the
moment it is disorganized and seeming unaccountable. DBA in modern times
requires more than technical knowledge as in times past. In recent times,
integrity constraints, relational optimization, stored procedures, access
methods, business rules, and user-defined functions exist within the database,
and is not an owned thing anymore.
Given the ability to query database, there is need for maintainers and
gatekeepers for successful data collection, storage, manipulation and usage.
There are different levels to the role of a data administrator. In an entry-level
role, the Database administrator is saddled with the task of learning to
determine the type of data to collect, the form of storage appropriate for it,
and the format the data should be in to allow the ease of use. Also, at this
stage, the DBA is responsible for verifying the integrity of the database and
implementing data models and designs by following laid out procedures and
policies whilst improving on the skills and being supervised by a manager.
As one’s expertise grows, so does the responsibility. Upon growth, new tasks
are added to salvage disasters that lead to loss of data.
Increase in the amount of data stored on drives and in the cloud as well as
technological advancements has influenced the rise in the need for database
administrators with particular specialties in the use of database administration
skills which includes Application DBA and System DBA.
System DBAs, are also known as all-purpose or traditional DBAs, as they
generally focus on the physical and technical aspects of database
management that caters for the smooth, efficient and error-free running of
systems. The sole responsibility is to make data secured, void data losses as
well as carry out tasks which includes updating permissions and installing
patches and upgrades to fix software program bugs.
Application DBAs are special system DBAs which are experienced at
specialized skills for a particular application or set of applications, such as
particular server knowledge (e.g. Oracle, or a particular suite of Oracle
applications), functional expertise, or database designs.

Important Tools for Database Administrators


The following tools are important for the success of database administrators;
it is necessary for them to have it handy:
1. Object management tools: These are tools which allow the Database
Administrator to perform everyday functions on the objects relating
to his/her domain. However, the functionality of this tool is limited to
object modification, browsing and migration.
2. Utility tools: These are tools that allow the Database administrator
maintain the databases. Some of the maintenance functions include,
but are not limited to backing up data, loading data, reorganizing
data, unloading data, validating data structure integrity, and
recovering data.
3. Performance monitoring tools: These are tools which help in the
identification, and correction of performance-based problems such as
SQL analyzers, capacity planning, performance modeling tools,
system adjustment tools, and performance monitors.
Specializations of Database Administrators
Just as in some other professions with a wide range of specializations, the
database administrator role also has a wide range of sub—specializations.
The most common ones are those who work in-house to keep a specific
organization’s internal databases moving as it ought to.
There are Database administrators who design/create the databases in the first
place. This set of DBAs work as part of a team, which are most times a
section of specialized software development companies. They often work on
databases that are tailored towards being part of application for specific
business need. An example is the case of commercial banks. Here, the bank
purchases or leases a software for running its operations. This software is
backed up by a database which was built by a team of specialized DBAs to
store all the data. In this scenario, they work with business analysts and other
professionals who are familiar with the operations of the bank to allow
optimal design of various modules and applications of the application.
Another type of DBAs is the Tuning or Performance Database Administrator.
This type of DBAs specialize in the optimization and improvement of the
performance of various databases. They work towards ensuring databases are
evenly used to the advantage of virtual or physical hardware on which it is
hosted. Optimization by these set of DBAs is done through the adoption of
indexes where it’s necessary for databases that are already complex to be split
amongst multiple servers in distributed setups. However, in the case of
smaller and single company’s databases, a non-specialist DBA is usually
efficient enough. They focus on the logical and development aspects of
database administration such as data model design and maintenance.
The third type of DBA is the application DBA. With principal focusing on
the integration of databases into applications that use them, they usually
require knowledge of specific query language types. However, with the
advent of front-end applications, the same tasks could be carried out even
without the DBA learning how to use and/or navigate SQL. It is the work of
this type of DBA to ensure that there is proper communication, and accurate
result performance between the database and the application it was created
for. They are usually found in organizations that have purchased a 3rd party
application software.

Basic responsibilities of a database administrator


The basic responsibilities of a database administrator include the following:

Installation and upgrade of database servers alongside


application tools required for optimal functioning.
Successful strategizing and allocation of the physical
requirements of a database system such as network requirement,
memory, disk space, etc.
Modification of database structures via information provided by
application developers.
Creation of user profiles, and ensuring security across the system
by carefully allocating user permissions.
Ensuring the compliance of database vendor license agreement,
which includes stipulated number of installations as well as
license renewals.
Developing recovery and backup strategy for database as well as
regular testing of the backups to ensure seamless user interaction.

Learning database administration


Lots of organizations require personnel to have acquired a four-year college
degree in an IT field. However, the value of a general degree is currently
being questioned as the database administrators with basically just degrees
are not bringing much skill set to the table. Hence, there has been changes in
the requirements for a database administrator.
Recently, there has been rise of diverse educational institutes offering
professional IT courses, which ranges from late-night programs, to allow
prospective DBAs learn the necessary skills and be more equipped. DBMS
vendors such as Oracle, Microsoft and IBM also offers certification programs
that help companies distinguish certified DBAs for hire. College degrees are
still helpful, but they are no longer the base requirements as there is need for
more technical trainings. Some of these trainings take anywhere from a
month to over six months.
Chapter 14

How to Use SQL in Real World Situations


Databases have been in use since the early 1960s, and SQL has been the
language of interaction. Even though some people don’t realize it, it would be
an understatement to actually say databases are everywhere. Irrespective of
our level of knowledge and acknowledgement of the presence of databases in
our lives, their effects are extensive on our daily life. Databases are virtually
the life wire of the daily activities of human, as databases play a large role in
the daily utilization of services: health care providers, online stores, libraries,
weather applications, clubs, video stores, travel agencies, phone companies,
beauty salons, and government agencies like FBI, INS, IRS, and NASA –
they all make use of databases. These databases are however different in their
nature and are usually specifically designed to handle some special customer
needs. Some databases are used for financial transactions and business
applications; however, they are not just used, as they require a lot of
expertise.
Relational databases which were first created by E. F. Codd gave rise to a
digital tool allowing companies and individuals replace the outdated forms of
file storage – paper – which had a lot of limiting factors. One of which is not
affording data users the ability to interact with the data they have at hand.
SQL interacts with databases based on their types. For example, flat-file
databases are mostly plain text files usually used by local applications to
store data. Although they are not as popular as relational databases, they still
serve a great purpose. Relational databases are divided into 2 main categories
which are basically as a result of their primary functions – Online Transaction
Processing (OLTP) and Data Warehouse Systems. OLTP typically has the
ability to allow users simultaneously create and update individual records,
given that it is volatile and involves a lot of computations. Data warehouse is
the type basically designed for the processing of information and analysis
focusing on the planning of the future rather than day-to-day operations. The
set of information contained in these doesn’t get to change often, and this
ensures the consistency of information for users of the platform involved. In
the real world, most systems are hybrid; combining the two unless they are
specifically wired for data warehouse.
Application areas of SQL in real world scenarios
Below are few of the most well-known examples of how SQL has interacted
with databases, and is being used to actively enhance the day-to-day life of
humans. The SQL happens to be very prevalent in the everyday life in the
following ways:

1. E-commerce: This makes use of the order management system


database. Organizations involved in the selling of goods, products or
services requires the use of database. A typical database of this type
has its users having one or more addresses, one or more contact
phone numbers, and a liaison officer between the user and the owner
of the database. In the case where the owner of the database sells
variety of products, each product has a price, description, and some
other required characteristics. When an order is made by the user
which could be for one or more products at a specific time. Upon
completion of an order, it is prepared for invoicing, and shipment (if
applicable). The invoice and shipment numbers are automatically
assigned in the database and cannot be edited by users. Each order
has a status process it goes through. Also, this type of database
being a multi-user environment groups, its users according to
functions are being performed and the security levels they can
access. The data involved in this use of SQL is stored in highly
secure databases, protected by the standards set through PCI
Compliance.
2. Healthcare provider database: Typical healthcare provider
companies own multiple offices across different states, has many
doctors on its list of staffs. Doctor’s offices and healthcare
organizations, among others, store extensive amounts of patient data
for easy accessibility. One doctor could be taking care of multiple
patients. Overall, this database keeps tabs on each user e.g. doctors
(keeping information such as name, contact phones, address, area of
specialization, and so on), patients (with information such as name,
phones, address, date of birth, health record number, history of
appointments, blood tests, prescriptions, diagnoses, etc.). With such
a database, one user can make a request, and have the other approve
based on their level of access. For example, a patient can request a
medicine refill, and the doctor would run a check, and decide if the
patient is due for a refill given the information the database brings
back. The databases behind the collection of information in this
context are large, complex, secure, and protected data which is in
compliance with HIPAA standards.
3. Security: Across developed countries, SQL is used to analyze data
for security purposes. Having had the details of citizens, immigrants
and visitors in a database, it becomes easy for the security team to
find and bring to justice criminals as well as keep others safe. For
example, if an emergency call is received, and the caller was only
able to state the kind of emergency they are dealing with, but
couldn’t mention address as a result of time or other factors, the
security agencies are capable of making safe predictions on possible
locations based on the data they have about the person.
4. Online Television Streaming: Online streaming services, such
as Hulu or Netflix, makes use of databases to compile and generate
a list of TV shows and movies to suggest users to watch. The
database tracks an individual’s show preferences, and the show
types that are rampant around a region, and provides a list of
recommended viewing. Such an enormous amount of data requires
so much power to analyze it through database management
technologies that are highly specialized in related things.
5. Social Gaming: Gaming done across social networks has proven
to be data intensive, as it involves gathering of individual player
information from all over the world, and serving it to players on
demand requires a high availability database software. A good
example is the popular Game of Thrones Ascent, which was
launched by Disruptor Beam, and based on the hit HBO series,
Game of Thrones as a free role-playing game.
6. Personal Cloud Storage: This is very common as virtually
everyone has cloud storage space courtesy email providers. If you
save photos or documents to your smartphone, tablet, or laptop, it’s
likely your data is stored in “the cloud,” which is a large, central
storage environment with a small portion of it dedicated to you.
Syncing this data across your various devices requires powerful
databases which allows you to be able to call up your data at any
moment you feel the necessity and wherever you are. SQL helps the
requesting process wherever you may seem to be.
7. Sports: Fan participation in national sports does not single-
handedly carry on the power of the database, it depends upon it. In
recent times, there has been fantasy football leagues, and others (e.g.
March Madness brackets) as well as mobile and PC games which all
depend on huge databases full of player statistics that includes injury
reports, game performances, and more, further calculating the odds
of a win on a weekly basis as in betting systems.
8. Finances: From the stock market to the local bank, databases are
abundant across the financial world. Tracking the vast amount of
information behind the world’s daily transactions requires the use of
extremely powerful databases. There are also financial models put in
place to analyze the data and predict future activity. Also, banking
activities requires an SQL for every bit of its activities, from
deposits, transfers, lodgments and to other banking services.
9. Government Organizations: Government organizations
around the world are constantly collecting data for research,
defense, legislation, and humanitarianism purposes, to name a few.
This data is collected, stored and analyzed using powerful and far-
reaching database services. The data collected by government
allows them to estimate the number of citizens they are servicing,
what service is more in use and where there needs to be
improvement on the path of the government and its agencies.
10. Social Media: Social media platforms serves as a storage
for various user information, and uses the stored data to recommend
businesses, friends, products, and topics to consider as an end user.
The cross-referencing of data is immensely complex and highly
reliable and capable database software. An example is Facebook.
Facebook utilizes SQL in its data centers for storage, maintenance
of user profiles across its wide range of lifestyle products. This
allows it to send in recommended ads, videos and pages that might
interest users.
11. Weather Forecast: Predicting the weather, is largely
complex as the world is so big. However, it makes use of the SQL
framework as it is dependent on a large range of factors and data put
together, stored and analyzed amongst the various databases. The
data gathered allows the daily weather delivered directly to your
smartphone via an app or to the local TV station around you. A
weather company typically accepts over 20 terabytes of data daily,
and this can be easily analyzed, or worked upon with the use of
SQL.
12. Advertisement Corporations: SQL allows brand
managers to maintain and improve their data analytics over time.
Advertisement and digital marketing centered people use ready-
made tools which has the SQL framework wired in it to track how
their client’s businesses are going, details and demographics of
those who use their services most, as well as a host of other details
relevant to the development of their business. SQL allows it to be
done in the fastest, most effective, efficient and successful way.
13. Library and book retrieval systems: With thousands of
books in the library, it is impossible to keep track of them manually,
hence, these is the need for a book retrieval system. Typically, a
book retrieval system presents a user with an easier way of finding a
book (if available), and at the same time helps the book keeper to
keep track of books, how they are being loaned out, and duration of
loan. In such a system, there are special profile types attached to the
lending party as well as a different one for the book keeper as
different levels of access are needed. This safe interaction is made
possible by SQL.
14. Telecommunication Firms: Telecommunication firms
have proven to be one of the major outfits where the use of database
is really effective as they gather data from customers upon
registration, update the records in due time as well as use the gotten
data to send offers to customers; all of this with the use of SQL.
They use database management systems and its interaction with
SQL to store, maintain, retrieve call details, postpaid bills as well as
active subscriptions. Telecommunications also keep databases to
serve as reference points, in the case where details regarding
transactions that transpire on their networks are needed. All the
fetching, maintenance and update of these data are made possible by
SQL
15. University management system: Universities as well as
selected institutions make use of database for storage of student
details. At the beginning of a new school year, existing students are
expected to register for courses, submit course assignments, term
papers and other relevant course work. The SQL helps the system to
interact with the database to get user details for seamless enrolment.
All the data involved in this, are products of initial enrolment, and
registration which involves first time update of bio-data and a host
of other personal details as well as constant update.
Overall, one of the modern developments that has changed everything for
man is the replacement of cabinets by databases. We are now all surrounded
by processes that make use of databases and SQL for optimal function as it
allows multiple access to data regardless of location, and it also allows real-
time update and availability of the data.
COMPUTER PROGRAMMING
2 BOOKS IN 1: 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.
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>

Rather than make use of tons of commands in outputting HTML, as done by


other programming languages, such as Perl and C, PHP pages comprise of an
HTML containing embedded programming designed to perform a function.
In the case of the code example above, the function is to output the line
"Hello, this is a PHP script." Also, the PHP code is encased in special
instructions at the start and end, allowing a user the ability to move in and out
of the PHP mode.
A key distinguishing factor between PHP and another programming
language, such as the client-side JavaScript is the fact that code is run on a
server and the HTML to be forwarded to the client is generated. The client
would be notified of the results of the script execution process without a
shred of knowledge about the underlying code of the script. It is also possible
to configure one's web server in such a way that it processes every HTML
file in PHP. This makes users incapable of knowing about your codes or
scripts. One of the better upsides of learning PHP is that it isn't as arduous to
learn for a beginner, while at the same time offering multiple advanced
features veteran programmers would find useful. And although there is a long
list of features in PHP, one can join in within a short period and be able to
create simple PHP programs in record time.
Like any other programming language, PHP codes can be run using a CLI
(command-line interface) contained within an HTML code or utilized
together with a host of web systems, content management frameworks, and
web template systems. A PHP interpreter sees the processing of PHP codes
and is usually located on a CGI (Common Gateway Interface) or web server
as an implemented module. The webserver outputs the results containing the
PHP codes that have been run and interpreted. The outputted code could take
on any form, ranging from a binary image data to a generated HTML code.
Outside of web development and application, it is possible to use PHP for
other forms of programming, like in robotic drone control or stand-alone
graphical applications.

History of PHP:

The development of PHP can be traced back to Rasmus Lerdorf in 1994.


Lerdorf is credited to have written a couple of CGI (common gateway
interface) programs in the programming language—C. It was said that he
regulated his homepage using those programs. Lerdorf experimented with
web forms and succeeded, hence the extension to web development and
communication with databases. He termed his implementation "PHP/FI," an
acronym for Personal Home Page/Forms Interpreter. This creation of
Lerdorf's could be applied in the creation of dynamic web applications with
simple structures. To speed up the rate of reporting bugs for code
improvement a reinvention of PHP/FI into "PHP Tools" (Personal Home
Page Tools) was announced by Lerdorf on a discussion group in Usenet in
1995, June 8th. The new release already contained some of the primary
functions PHP is capable of till date, including the embedment of HTML,
Perl-like variables, and form handling. The syntax has some similarities to
the one used by Perl; however, its simplistic design proved to be more
inhibitive than it was consistent.
Below is a code sample of one of the earliest syntaxes of the language:

<!--include /selectedtext/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_resultChrome-->
Hello, you are using Netscape!<p>
<!--endif-->

<!--sql database select * from group where user='$username'-->


<!--ifless $numentries2-->
Sorry, such record does not exist<p>
<!--endif exit-->
Welcome <!--$user-->!<p>
You have <!--$index:4--> credits remaining in your account.<p>

<!--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:

1. What purpose is PHP most suited to perform?


2. Where is a PHP interpreter found?
3. What title did RasmusLerdorf term his implementation of regulated
personal homepages?
4. What group is credited with the creation of the fundamental parts of
PHP 3, as well as the name the program now bears?
5. What is used in the processing of PHP codes?
6. What qualities endear PHP to programmers?
7. How do PHP pages output HTML?
8. What is the key distinguishing factor between PHP and other
programming languages?
9. What is a considerable upside of learning PHP?
Chapter Two
Why Learn PHP?
According to its history, PHP was started as a quiet open source project
which grew and evolved as it gained recognition across a population that
found it very useful. And since its release in 1994, it has become increasingly
sought after by learners and professionals alike who seek to become better at
software engineering, mainly when it involves the area of Web Development
Domain. Some of the upsides of learning PHP are outlined below:
PHP is a scripting language for servers and browsers and is embedded in
HTML. As a result, it is applied in managing databases, dynamic content, and
session tracking. It is also used in the building and designing of e-commerce
sites.
PHP has lots of integration with a variety of popular databases, such as
Microsoft SQL Server, MySQL, Oracle, Informix, PostgreSQL, and Sybase.
PHP is easily a fast language in terms of execution, mainly when it is
compiled in the form of Apache modules on Unix-enabled platforms. Once it
begins, the MySQL server runs even the most sophisticated of queries and
produces a vast array of results at a record-breaking rate.
PHP supports a lot of significant protocols used in programming, like the
LDAP, IMAP, AND POP3. In PHP 4, support was introduced for Java, as
well as distributed objects architecture like COBRA and COM. And for the
first time, n-tier development was made possible.
PHP is a forgiving language. The PHP language attempts to be forgiving in
many ways.
PHP syntax is somewhat similar to that of C.

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>

How PHP is Applied:


Keep in mind that PHP is one of the widely known and popularly used
programming language across the world today. In this section, we consider
some of the few applications of PHP as seen today:

1. PHP can be used in restricting the access of users to individual pages


found on a website.
2. PHP can be used in carrying out system functions. That is, from the
files contained in a system, it can be used to close, open, create,
write and read these files.
3. PHP can be used in the encryption of data.
4. PHP is used in handling forms. That is, gathering the data from files,
saving the data to files, forwarding data through emails, and
returning data to a user.
5. PHP is used in setting cookies and accessing cookies variables.
6. PHP can be used to add, delete, and modify the elements contained
in a database.

Setting up a PHP Environment on Your System:


To build and execute web pages in PHP, three vital components are required
to be installed in a computer system. They include:
PHP parser:
To process the instructions of PHP scripts, you have to install a parser to
generate HTML outputs which can be forwarded to a web browser. A tutorial
will guide you on how to go about the installation of PHP parsers on your
system in the ensuing paragraphs.
Web Server:
PHP can be applied with apparently every form of web server software,
including but not limited to the Internet Information Server (IIS) Microsoft.
However, it is most often used with the Apache Server that is freely
available. To get the Apache Server, you can download it via the
link: https://httpd.apache.org/download.cgi
Database:
PHP is applied with apparently all forms of database software, including but
not limited to Sybase and Oracle; however, it is typically used with the
MySQL database which is available for free. To get the MySQL Server, you
can download it via the link: https://www.mysql.com/downloads/.

How to Install the PHP Parser:


Before going ahead with the installation process, it is imperative to ensure
that you have already set up the PHP environment on your system for
developing web programs with PHP.
To begin, enter the address shown below into the query box of your browser:
http://127.0.0.1/info.php
When the address is executed, a page containing the information related to
PHP installation is displayed. This implies that your Webserver and PHP are
correctly installed. If not, you have to make use of the procedure shown
below in installing PHP on your system.

Setting up the Development Environment

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.

On Linux (Debian based) systems:


Unlike in Mac and Windows systems, it is a more sensible approach not to
use third-party apps on Linux systems. Instead of installing this software into
the system, make use of the software directly. It is still possible to install the
XAMPP application, though, should you prefer to use it. However, keep in
mind that it is a development environment, and you mustn't make use of or
configure those third-party applications in executing things like a live server.
Now, before you begin the installation of anything into your system, ensure
that the operating system is up-to-date. This can be done by executing the
commands shown below into the terminal of your system:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
Executing these commands makes sure that the system is current and up to
date with the present version of the software. If your system is up to date, you
should find out that Apache 2 is already installed in most Linux systems,
albeit, if you are not already sure of its availability to try running the
command sudo apt-get install apache2. Keep in mind that attempting to
execute an install command for an application already in your system will
change to checking for updates for the said application. By now, you must
install a database. Be free to explore and make use of any of your choosing.
However, the most common database used is MySQL. To install MySQL into
your system, execute the commands shown below into the terminal:
sudo apt-get install mysql-server
sudomysql_secure_installation
Study and answer the prompts that follow and input a strong password.
Once it is certain that Apache 2 has been installed into your system, MySQL,
too, then you can proceed with the installation of the PHP program. To install
PHP, execute the command shown below:
sudo apt-get install php
At this point, you must install phpmyadmin as it makes setting up easier and
faster to perform and even make for better modification of your chosen
database. The installation process of phpmyadmin is quite straightforward
and can be done in a few steps.
Begin by opening your terminal and entering the block of code shown below:
sudo apt-get install phpmyadmin

Having successfully concluded the process, it is time to begin the


configuration of the Apache configuration file such that it contains
phpmyadmin. To do this, enter the command shown below into your terminal
and run:
sudo echo -e "\nInclude /etc/phpmyadmin/apache.conf" >>
/etc/apache2/apache2.conf
At this point, the needful is to initialize your database (MySQL), and third-
party web server (Apache) and everything is already set up. To do this, enter
the code shown below into your terminal and execute:
sudo service apache2 start && service mysql start
By the end of this, you should have successfully configured and set up a PHP
development environment on your Linux system.

Setting Up A Production Environment:

In the case of setting up a production environment, you need to use this


method when you are configuring a live server used in hosting applications or
websites regardless of the server you are using, be it Linux's or Windows'
server. You have to locate the php.ini files in your Windows system. These
files can be found in the PHP folder. On Linux systems, it is stored in the
PHP folder; however, the folder could be placed in the folder named "etc."
To save time, you could also search for php.ini.
The alterations to be made tends to be in the aspect of error handling and
logging. And, as always, the instructions are documented there to help users
in deciding on the things that need modification. Here, the change that has to
be made is usually in regards to turning off every display error to make sure a
user doesn't happen on an error message. It is improving the security of your
system, as well as ensuring that everything remains good looking even in the
eventuality of an error being reported. Keep in mind to ensure that every
form of error is logged into an error.log file because it aids you in the
debugging process. Also, ensure to make a few final-minute alterations
during the setting up process before going live with the site.

Exercises 2:

1. Why are third party applications used in setting up a development


environment on Windows systems?
2. What prerequisite is demanded before setting up a development
environment on Linux systems?
3. What does phpmyadmin do?
4. What third-party application can be used on both Windows and Mac
systems?
5. What does PHP's embedment in HTML mean for the language?
6. What significant protocols are supported by PHP?
7. What is the function of a parser?
8. PHP is integrated into what kinds of a database?
9. What are the three vital components required to be installed in a
computer system to create and run scripts in PHP?
10. In form handling, how does PHP apply?
Chapter Three
Basic Syntax
In this section, we will take a look at the primary forms of PHP syntax, as
they are part of the knowledge necessary for a good foundation in PHP
programming.
Escaping to PHP:
Sometimes, a PHP parsing engine would be required to distinguish between
other elements on a page and PHP codes. A special mechanism is known as
"escaping to PHP" is used to perform such a function. There are four possible
means of carrying out this function, in any case. They are:
Using Canonical PHP Tags:
This method has one of the most generally effective PHP tag styles, written
as:
<?php…?>
When making use of this style, rest assured that, no matter the conditions,
there will always be a correct interpretation of your tags.

Using SGML-style (short-open) Tags:


Short tags, otherwise known as short-open tags, are usually written as:
<?...?>
As the name connotes, short tags offer the shortest alternative. For PHP to
recognize your short tags, you must perform two tasks;
When creating a PHP script, pick the configuration option to enable short
tags.
Next, go to the settings part of your php.ini file and click to turn on
short_open_tag. You must disable this option when processing XML and
PHP together because XML tags use a similar syntax to it.
Using ASP-style Tags:
ASP-style tags share a similar structure and functionality to the tags used to
delineate code blocks on Active Server Pages. ASP-style tags typically
appear in this format:
<%...%>
When using ASP-style tags, you have to set up the configuration option
within a php.ini file.
HTML Script Tags:
HTML script tags are usually written as:
<script language = “PHP”>…</script>
How to Comment in PHP Codes:
Comments refer to the parts of a program written for human users and are cut
out before the results of a program are outputted. In PHP, there are two forms
of comments. They are:
Single-line Comments:
These comments usually serve as brief notes or explanations that are related
to the written code. Consider the samples below on how single-line
comments are used:
<?
# This is a single comment, and
# This is another line of the single comment

// This is another comment too. Each style comments only


print "A sample of a single line comment";
?>
Multi-lines Printing:
Shown below is a sample on how to output multiple lines in one print
statement:
<?
# First Example
print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
# Second Example
print "This spans
multiple lines. The newlines will be
output as well";
?>

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
*/

print "A sample with multi-line comments";


?>
Whitespace Insensitivity:
Whitespaces refer to the parts of codes that are invisible to the eyes when
typed. They include tabs, spaces, and carriage returns (that is, end-of-line
characters). The Insensitivity of PHP to whitespaces implies that the number
of whitespace characters in a row is inconsequential because a single
whitespace character is seen the same way as many whitespace characters.
Take for instance, in each of the PHP statements shown below, the statements
that assign the 5 + 1 operating to the outputted variable $six are equal:
$six = 5 + 1; // single spaces
$six <tab>=<tab2<tab>+<tab>2 ; // spaces and tabs
$six =
5+
1; // multiple lines
Case Sensitivity:
PHP is a very case sensitive programming language; meaning, it interprets
variables in different cases distinctly. For example, the entries PHP, php, and
pHp will be interpreted differently instead of as the same thing. Consider the
code example below:
<html>
<body>

<?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>");
}

How to Execute PHP Scripts from the Command Prompt:


It is possible to execute PHP scripts from the command prompt of your
computer. Let's say you have the content shown below in a test.php file.
<?php
echo "Hello PHP!!!";
?>

Proceed to execute this script shown above using your command prompt in
the following ways:
$ phptest.php

The result outputted will take after this fashion:

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.

Variables and data types:


In PHP, there are up to eight distinct data types that can be used in the
construction of variables. They include the following:
Integers:
Integers refer to whole numbers that lack decimal points. Examples: 12,
1234, etcetera.
Doubles:
Doubles refer to floating-point numbers, such as 12.3, 1.234, etc.
Booleans:
Booleans refer to values with two definite number of outcomes: both being
either True or False.
NULL:
NULL can be seen as a special data type which has only one possible value—
NULL.
Strings:
Strings can be regarded as a set of characters. For example, "String
operations are supported in PHP" is a string.
Arrays:
Arrays refer to various sets of other values that have been indexed and
named.
Objects:
Objects refer to instances of programmer-defined classes that are capable of
packaging up the other types of functions and values considered to be class-
specific.
Resources:
Resources refer to special types of variables which contains references to
resources obtained outside of PHP, like database connections, for instance.
The first five variable types are classified as simple types, while the
succeeding two types (I.e. objects and arrays) are known as compound
variable types. Compound variables are capable of packing up various other
arbitrary data types of arbitrary values, while the latter is incapable of
performing such a function.
For a better understanding of the classifications, we will consider each class
separately and discuss its members briefly.

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;

print("$many + $many_2 = $few <br>");


?>

When executed, it outputs the following:


1.3422220 + 2.1111345 = 3.4
Boolean:
In PHP, only a couple of constants are provided to be used as Booleans, and
they are FALSE or TRUE. They can be used in the following manner:

if (TRUE)
print("This will always print<br>");

else
print("This will never print<br>");

Interpreting Other Variable Types as Booleans:


Shown below are the rules and conventions used to find out the "truth" of any
value that isn't already a part of the Boolean variable type:
1. When the value is an actual number, it is true if the number is greater
than or less than zero and false if it is precisely equal to zero.
2. When the value represents a string, it is true when the string isn't 0
and has characters greater than zero, and false when the string is 0 or
has zero number of characters (i.e. is empty).
3. The values of the variable type NULL are false at all times.
4. When the values appear as an array, it is true if it comprises of other
values and false otherwise. In the case of an object, holding a value
implies containing a member variable that has already been assigned
value.
5. Never use doubles as Booleans.
6. Valid resources are always true, although certain functions which
successfully return resources tend to be true, and when unsuccessful
return false.

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>";

$literally = "The $variable will print!";


print($literally);
?>
Running the script will return the following result:
The $variable will not print!
The class will print
For string length, there are no artificial limits, meaning that with the value of
memory available, you should be able to create as many arbitrarily long
strings as possible. Strings which have been delimited using double quotes
(for example, "this") are processed beforehand in PHP in the following ways:
Variable names (those beginning with the dollar sign ($)) are replaced using
the string representations of their respective values.
Some character sets starting with a backslash (\) are replaced using special
characters.
The escape-sequence replacements include the following:
1. \\ is replaced using a single backlash (\)
2. \n is replaced using the newline character
3. \" is replaced using the single, double quote (")
4. \r is replaced using the carriage-return character
5. \$ is replaced using the dollar sign alone ($)
6. \t is replaced using the tab character

The Here Document:


For a single string variable, it is possible to assign multiple lines to it with a
here document. Consider the sample shown below:
<?php
$channel =<<<_XML_

<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

Naming Variables in PHP:


The rules and conventions for making variables in PHP are as follows:
A variable name can be made up of underscores, letters, and numbers,
however, characters such as +,-, %, (,). &, among others, cannot be used.
A variable name has to start with an underscore character or a letter.
Keep in mind that no limit applies to variables in terms of size.

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.

Valid and Invalid Constant names:


// Valid constant names
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing");

// Invalid constant names


define("2TWO", "second thing");
define("__THREE__", "third value");
Magic Constants in PHP:
PHP offers a vast array of predefined constants to whatever script that is
executed on it. The magical constants are five in number and would tend to
alternate depending on the part that it is applied to. Take, for instance, the
value of __LINE__ is depended on the line where it is applied in on the
script. Special constants of these sorts are usually insensitive to case, and take
after this fashion:
Some magical constants on PHP are shown below for better understanding:
1. __LINE__: This constant is used to represent the present line
number of a file.
2. __FILE__: This constant represents the complete filename and path
of a file. When applied within an included file, it returns the name of
the included file. Since as early as version 4.0.2 of PHP, the
__FILE__ constant has always contained the absolute path, although
in earlier versions it used to contain a relative path in some cases.
3. __FUNCTION__: This constant was introduced in version 4.3.0, and
is used to return the name of the function. For PHP 5, the
__FUNCTION__ constant returned the function name in the same
way it was declared with respect to case. As of PHP 4, the value of
this constant remained in lower cases.
4. __CLASS__: This constant was introduced in PHP 4.3.0, and is used
to return the class name. For PHP 5, the __CLASS__ constant
returned the function name in the same way it was declared with
respect to case. As of PHP 4, the value of this constant remained in
lower cases.
5. __METHOD__: This constant is used to return the class method
name. It was introduced in version 5.0.0, and it returns the method
name in the same way it was declared with respect to case.

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

Let's take an in-depth look at these operator types individually:


Arithmetic Operators:
Below is an outline of all the arithmetic operators supported in PHP:
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 in summing two or more operands. E.g. X +
Y gives 20.

- : This operator is used in finding the difference between two


operands. E.g. Y – X gives 10.
2. *: This operator is used in multiplying operands together. E.g. X * Y
gives 75.
3. /: This operator is used for dividing the numerator by the
denominator. E.g. Y / X gives 3.
4. %: This operator, name of modulus, is used to calculate the
remainder of an operation after an integer division. E.g. Y % X gives
0.
5. ++ This operator is called the increment operator, and is used to
increase the value of an integer by one. E.g. Y++ gives16.
6. --: This operator is called the decrement operator, and is used to
decrease the value of an integer by one. E.g. X—gives 4.

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.

Operator Precedence in PHP:


In PHP, the precedence of operators dictates how terms are grouped in an
operation. It influences the overall system of evaluation of an expression.
Some operators are higher placed in the precedence scale than others, so, they
would tend to be evaluated first. Consider the concept of operator precedence
to be similar to the mathematical rule of BODMAS. Take a look at the
sample below for better understanding:
In PHP, the multiplication operator (*) has higher precedence over the
subtraction operator (-), so, in the expression j = 2 - 4 * 3; the answer will be
-10 rather than -6. The multiplication operator would be used to evaluate the
expression first before any subtraction is made. In basic mathematical terms,
this expression can be interpreted as 2 – (4 × 3).
In the discussion below, all operators are ranked in descending order, with
the order of precedence decreasing down the outline toward the last operator.
Keep in mind that higher precedence operators ought to first be evaluated in
any expression before lower precedence operators.
Unary operator:
Unary operators are !, ++, and --.
Associativity: Right to left.
Multiplicative operators:
Multiplicative operators are *, %, and /.
Associativity: Left to right
Additive operators:
Additive operators are + and -.
Associativity: Left to right.
Relational operators:
Relational operators are <, <=, >, and >=.
Associativity: Left to right.
Equality operators:
Equality operators include == and !=.
Associativity: Left to right.
Logical AND:
The Logical AND operator is &&.
Associativity: Left to right.
Logical OR:
The Logical OR operator is ||.
Associativity: Right to left.
Conditional operator:
The conditional operator is ?:.
Associativity: Right to left.
Assignment operators:
Assignment operators include the following: =, +=, -=, *=, /=, and %=.
Associativity: Right to left.
Exercise 6:
2. What operator is used in finding the remainder of an operation after
an integer division?
3. Less than (<), Less than or equal to (<=), Greater than (>), and
Greater than or equal to (>=) are under what class of operators?
4. What is an operator?
5. Explain the term “precedence” based on the use of operators.
6. What are binary operators?
7. How does the decrement operator (--) work?
8. What is the condition of precedence for the evaluation of operators?
9. What are ternary operators?
10. The Divide AND (/=) operator falls under what type of
operators?
11. Name the two types of additive operators.
Chapter Seven
Decision Making In PHP
Every script in PHP is created from a set of statements. These statements
could be loops, function calls, assignment, or even conditional statements of
statements that do absolutely nothing (i.e. an empty statement). Additionally,
it is possible to classify statements into groups called statement-group
through the sheer process of putting a group of statements into curly braces.
In itself, a statement-group represents a statement, as well.
In PHP, the statements shown below are used in making decisions based on a
certain number of conditions:
1. Else statement
2. If statement
3. Elseif statement
4. Switch statement

The If…else Statement:


This statement is used when you want to run a series of codes when one of
the conditions is true, and another of the condition isn’t true.
Syntax:
if (condition)
code to be run if the condition is true;
else
code to be run if the condition is false;
Sample:
The sample shown below produces “Have a great day!” if the period of the
day is Morning; otherwise, it produces “Good night! Sleep well.”

<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!";

elseif ($t == "Ngt")


echo "Good night! Sleep well.";
else
echo "Have a great day!";
?>

</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;

while( $a < 15) {


$num--;
$a++;
}

echo ("Loop stopped at a = $a and num = $num" );


?>

</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;

for( $i = 0; $i<6; $i++ ) {


$x += 12;
$y += 6;
}
echo ("At the end of the loop x = $x and y = $y" );
?>

</body>
</html>

This produces the following result −


At the end of the loop a = 72 and b = 36
Consider another sample below that defines a loop which begins with $i = 2.
The loop goes on until $i has reached a value that is less than or equal to 5.
The variable $i continues to increase by 1 every other time the loop is
executed:
<?php for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>"; }
?>
PHP do…while loop:
The do…while loop is another form of the while loop that evaluates the
condition at the terminal point of every loop iteration. In a do…while loop, a
block of code is executed at once, and the condition is then evaluated. When
the condition passes as true, the expression is processed repetitively for as
long as the given condition of evaluation still passes as true.
Syntax:
do{
// Code to be executed
}
while(condition);
Sample:
Consider the sample shown below, which will increase the value of x for
every iteration. The variable x will continue to increase in value for as long as
its assigned value is less than 15.
<html>
<body>
<?php
$x = 0;
$num = 0;

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.

The Foreach Loop:


The foreach loop is applied when you need to iterate over arrays.
foreach($array as $value){
// Code to be run
}
The foreach loop statement:
The foreach statement is applied in a loop via arrays. For every cycle, the
value of a current array element is given to the variable $output. Then the
array pointer is shifted by one, and the succeeding element will be evaluated
when the next cycle arrives.
Syntax
foreach (array as value) {
code to be run;
}
Sample
Consider the sample shown below to outline the values held by an array:
<html>
<body>

<?php
$array = array( 5, 6, 7, 8, 9);

foreach( $array as $output ) {


echo "Answer is $output <br />";
}
?>

</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;

while( $x < 10) {


$x++;
if( $x == 5 )break;
}
echo ("Loop stopped at x = $x" );
?>

</body>
</html>
When the script is executed, the result outputted will be as follows:
Loop stopped at x = 5

The Continue Statement:


The continue statement in PHP is applied in pausing the present iteration
process of any loop, although it doesn’t necessarily end the looping process.
As in the use of the break statement, the continue statement is located within
the statement block holding the code that is executed by the loop and is
preceded by a conditional test. For the pass joining the continue statement,
the remainder of the loop code is left for the next pass to begin.
Sample:
In the sample shown below, the loop outputs a value of the array, however,
for the condition that passes as true, the code is skipped altogether, and the
next value is outputted.
<html>
<body>

<?php
$array = array( 5, 6, 7, 8, 9);

foreach( $array as $ouptut ) {


if( $output == 5 )continue;
echo "Answer is $output <br />";
}
?>
</body>
</html>
When the script is executed, the result produced takes after the fashion
showed below:
This produces the following result −
Answer is 5
Answer is 6
Answer is 7
Answer is 8
Answer is 9
Exercise 8:
1. What are loops?
2. What statement is introduced into a loop through arrays?
3. What is the function of the for loop?
4. Why are loops used?
Chapter Nine
Arrays in PHP
In PHP, arrays refer to a system of ordered maps. A map can be seen as a
data type which links values to keys and can be optimized for many different
reasons. Maps can also be regarded as arrays, dictionaries, queues, list
(vector), collection, hash tables (the implementation of maps), stacks, and
even more. In the same way, the values in an array can be other arrays; it is
also possible for it to be multi-dimensional arrays and trees.
How Arrays are Created:
Arrays can be developed with the array() language construct. It uses any
amount of keys separated by commas, that is, value pairs as arguments.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
The comma used after the final element in an array is an optional construct
and may or may not be included. It is especially used in single-line arrays.
That is, array (x, y) is preferred to array (x, y, ). On the other hand, for multi-
line arrays, the comma that follows is usually applied because it allows for
better inclusion of new elements into the end. In version 5.4, the short array
syntax can be used in replacing the array() function with parentheses [].
Consider the sample below:
Sample #1 A simple array
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);

// 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);

foreach( $digits as $value ) {


echo "Answer is $value <br />";
}

/* Second method to create array. */


$digits[5] = "five";
$digits[6] = "six";
$digits[7] = "seven";
$digits[8] = "eight";
$digits[9] = "nine";

foreach( $digits as $value ) {


echo "Answer is $value <br />";
}
?>
</body>
</html>
When executed, the result of the numeric array is as follows:
Answer is 5
Answer is 6
Answer is 7
Answer is 8
Answer is 9
Answer is five
Answer is six
Answer is seven
Answer is eight
Answer is nine

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 />";

/* Second method to create array. */


$wages[‘kaleb’] = "high";
$wages[‘karen’] = "medium";
$wages['tara'] = "low";

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
),

"karen" => array (


"english" => 35,
"biology" => 42,
"agric" => 33
),

"tara" => array (


"english" => 41,
"biology" => 29,
"agric" => 37
)
);

/* Accessing multi-dimensional array values */


echo "Scores for kaleb in english : " ;
echo $scores[‘kaleb'][‘english’] . "<br />";
echo "Scores for karen in biology : ";
echo $scores[‘karen’][‘biology’] . "<br />";

echo "Scores for tara in agric : " ;


echo $scores['tara'][‘agric’] . "<br />";
?>

</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:

$string_4 = "This is a string with double quotes";


$string_3 = 'This is a slightly longer, singly-quoted string';
$string_26 = "This string contains twenty-six characters";
$string_0 = ""; // a string with no characters
Quoted String Types:
As was earlier discussed, strings with single quotes are treated in a literal way
while strings with double quotes are used in replacing variables and their
values, even to the point of being able to interpret some character sequences.
Consider the sample shown below which points out the distinction between
double and single quotes strings:
<?php $my_str = 'World'; echo "Hello, $my_str!<br>"; // Displays: Hello
World! echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str! echo
'<pre>Hello\tWorld!</pre>'; // Displays: Hello\tWorld! echo "
<pre>Hello\tWorld!</pre>"; // Displays: Hello World! echo 'I\'ll be back'; //
Displays: I'll be back ?>
Consider the second sample shown below:
<?php
$output = "song";
$lyrics = 'My $output will not print!\\n';

print($lyrics);
print "<br />";

$lyrics = "My $output will print!\\n";

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.

Calculating the Length of a String:


In PHP, the strlen() function is applied for calculating the amount of
characters that are contained in a string, even up to the blank spaces used
within the string.
<?php $a_str = 'Welcome to PHP programming;
// Outputs: 24
echo strlen($a_str);
?>
Consider another sample below of how the strlen() function applies in a
different string containing "Hello world!" −
<?php
echo strlen("Hello world!");
?>
The result of executing this string is:
12
The length of a string often factors in other functions, as well as loops, as
such, knowing when a string terminates important in PHP programming. The
reason is that when using a loop, knowing to terminate the process when the
final character in a string has been evaluated is vital.
Counting Number of Words in a String:
To count the amount of words held by a string, the function str_word_count
is used.
<?php $my_str = 'The quick brown fox jumps over the lazy dog.'; // Outputs:
9 echo str_word_count($my_str); ?>
String Concatenation Operations:
In the concatenation of two string variables, the dot (.) operator is used:

<?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.

Replacing Text in Strings:


The str_replace() function is used in replacing every occurrence of a searched
query found in a target string.
<?php
$a_str = when the moving gets tough, the tough get moving.';

// Display replaced string


echo str_replace("moving", "going", $my_str);
?>
When the code above is executed, the output is as follows:
When the going gets tough, the tough get going.
Optionally, it is possible to pass the fourth argument into the function
str_replace() as a way of figuring out the number of times a string
replacement has been performed. Consider the sample below:
<?php
$a_str = 'When the moving gets tough, the tough get moving.';

// Perform string replacement


str_replace("moving", "going", $a_str, $count);

// Display number of replacements performed


echo "The text was replaced $count times.";
?>
When the code is executed, the outputted result is as follows:
The text was replaced 2 times.
How to reverse a String:
In PHP, the function strrev() is used in reversing a string. The process flips
the string into reverse. Consider the sample shown below:
<?php
$a_str = 'When the going gets tough, the tough get going.';

// Display reversed string


echo strrev($a_str);
?>
When the code is executed, the outputted result will be as follows:
.gniongsteghguoteht , hguotsteggniongehtnehW

How to Use the strpos() Function:


In PHP, the function strpos() is used in searching for a character in a string or
an entire string too. When a match is located within a string, the strpos()
function is the location of the first match. If there are no matches found, the
result outputted would be FALSE. Consider the same below in which we try
to locate the string "How are you today?" in a string:
<?php
echo strpos("How are you today?", "today");
?>
When the string is executed, the result outputted is:
9
On closer observation, you shall notice the location of "today" in the string
lies in position 9. The reason why the position is numbered 9 rather than 8 is
that the first position of every string in PHP begins with 0 instead of 1.
String Functions in PHP:
Below is an outline of the string functions in PHP. These functions serve as
an integral piece of PHP's core, so it is possible to apply any of them in your
string without needing to make installations of any sort.
1. addcslashes(): This function is used to return a string using
backslashes to precede any specific character.
2. addcslashes(): This function is used in returning a string using
backslashes to precede any character(s) that has to be escaped.
Characters in this function include NULL, backslash (\), double
quote ("), as well as single quotes (').
3. bin2hex(): This function is used in the conversion of data in binary
into hexadecimal forms.
4. chop(): This function is used in stripping whitespaces, other
characters as well from one end of a string. It is an alias to the
function rtrim().
5. chr(): This function is used in returning a string with one character
comprising of the character specified by ASCII.
6. chunk_split(): This function is used in splitting a string into bits.
7. convert_cyr_string(): This function is used in converting a string
from a Cyrillic character set into another.
8. convert_uudecode(): This function is used in decoding a uuencoded
string.
9. convert_uuencode(): This function is used in encoding a string with
a uuencode algorithm.
10. count_chars(): This function returning the information of the
characters applied in a string.
11. crc32(): This function is used in calculating the crc32
polynomial in a string.
12. crypt(): This function is used in one-way string encryptions
otherwise known as hashing.
13. echo(): This function is used in outputting one or more
strings.
14. explode(): This function is used in splitting a string into arrays
by a specified string.
15. fprintf(): This function is used in writing a formatted string
into a guy output stream.
16. get_html_translation_tablet(): This function is used in
returning the translation table which the functions htmlentities() and
htmlspecialchars() use.
17. hebrev(): This function is used in converting a text in logical
Hebrew form into visual text.
18. hebrevc(): This function is used in converting texts from a
logical Hebrew text form into busy text using newline conversion.
19. hex2bin(): This function is used in decoding a binary string
encoded in hexadecimal.
20. html_entity_decode(): This function is used in converting
every entity in HTML into their applicable characters.
21. htmlentities(): This function is used in converting any
applicable character into its respective HTML entities.
22. htmlspecialchars_decode(): This function is used in
converting special HTML entities back into characters.
23. htmlspecialchars(): This function is used in converting special
characters into HTML entities.
24. implode(): This function is used in returning a string through
a process of combining the elements in an array using a given string.
25. join(): This function is an alias of the implode() function.
26. lcfirst(): This function is used in converting the first
characters of strings into lowercases.
27. levenshtein(): This function is used in calculating the
Levenshtein distance existing between two strings.
28. localeconv(): This function is used in returning the
information from monetary formatting and localized numeric.
29. ltrim(): This function is used in removing whitespaces or any
other character from the starting of a string.
30. md5(): This function is used in calculating the md5 hash in a
string.
31. md5_file(): This function is used in finding the md5 hash in a
file.
32. metaphone(): This function is used in calculating the
metaphone key in a string.
33. money_format(): This function is used to format a number
into a currency string.
34. nl_langinfo(): This function is used in returning a given set of
local information.
35. nl2br(): This function is used in introducing an HTML line
break before the newlines of a string.
36. number_format(): This function is used in formatting a
number having a grouped thousand.
37. ord(): This function is used in returning the ASCII value
associated with the first character in a string.
38. parse_str(): This function is used in parsing a string into
variables.
39. print(): This function is used in outputting strings.
40. printf(): This function is used in outputting formatted strings.
41. quoted_printable_decode(): This function is used in
converting quoted-printable strings into 8-bit strings.
42. quoted_printable_encode(): This function is used in
converting 8 but strings into quoted-printable strings.
43. quotemeta(): This function is used in quoting meta characters.
44. rtrim(): This function is used in eliminating whitespaces as
well as other characters from the terminal point of a string.
45. setlocale(): This function is used in setting information
regarding the locale.
46. sha1(): This function is used in calculating the sha1 hash in a
string.
47. sha1_file(): This function is used in calculating the sha1 hash
in a file.
48. similar_text(): This function is used in calculating the
measure of similarity shared by two strings.
49. soundex(): This function is used in calculating the soundex
keg in a string.
50. sprintf(): This function is used in returning formatted strings.
51. sscanf(): This function is used in parsing the input obtained
from a string based on a format.
52. str_getcsv(): This function is used in parsing CSV strings into
arrays.
53. str_ireplace(): This function is used in replacing every
occurrence of the search string using the replacement string. This
function is an alias of str_replace(), only it is more case-sensitive.
54. str_pad(): This function is used in padding a string to reach a
particular height with another string.
55. str_repeat(): This function is used in repeating a string for a
given amount of times.
56. str_replace(): This function is used in replacing all
occurrences of a search string using a replacement string. It is case-
sensitive.
57. str_rot13(): This function is used in performing a ROT13
encoding into a string.
58. str_shuffle(): This function is used in shuffling every
character in a string randomly.
59. str_split(): This function is used in splitting strings into arrays.
60. str_word_count(): This function is used in counting the point
of words a string contains.
61. strcasecmp(): This function is used in performing a binary-
safe comparison between two strings. It is insensitive to case.
62. strchr(): This function is used in locating the first appearance
of a string within another string. It is an alias to the function strstr().
63. strcmp(): This function is used in performing a binary-safe
comparison between two strings. And unlike strcasecmp(), it is
sensitive to case.
64. strcoll(): This function is used in performing a locale-based
comparison on two strings. It is sensitive to case.
65. strcspn(): This function is used in returning the number of
characters a string contains before any area containing specified
characters is located.
66. strip_tags(): This function is used in stripping off the PHP and
HTML tags found in a string.
67. stripcslashes(): This function is used in un-quoting strings
quoted using the function addcslashes().
68. stripos(): This function is used in locating the position of the
first appearance of a case-insensitive substring within a string.
69. stripcslashes(): This function is used in un-quoting quoted
strings.
70. stristr(): This function is used in locating the first appearance
of a string within another string, and is insensitive to case. It is a
case-insensitive version of the function strstr().
71. strlen(): This function is used in returning the length of a
string.
72. strnatcasecmp(): This function is used in comparing two
string with a "natural order" algorithm. It is case-insensitive.
73. strnatcmp(): This function is used in comparing two string
with a "natural order" algorithm. It is case-sensitive.
74. strpbrk(): This function is used in analyzing a string for any of
several characters.
75. strpos(): This function is used in searching for the location of
the first appearance of a substring within a string.
76. strrchr(): This function is used in locating the final appearance
of a character within a string.
77. strrev(): This function is used in reversing a string.
78. strripos(): This function is used in locating the final
appearance of a string within another string. It is case-insensitive.
79. strripos(): This function is used in locating the final
appearance of a string within another string. It is case-sensitive.
80. strspn(): This function is used in returning the number of
characters a string contains when the string is made up of the
characters from a given char list.
81. strstr(): This function is used to locate the first appearance of
a string within another string. It is case-sensitive.
82. strtok(): This function is used in splitting strings into much
smaller strings.
83. strtolower(): This function is used in converting a string into
lowercase.
84. strtloupper(): This function is used in converting a string into
uppercase.
85. strtr(): This function is used in replacing substrings or
translating characters.
86. substr(): This function is used in returning an aspect of a
string.
87. substr_compare(): This function is used in the comparison of
two strings from a particular start point until the length of the
comparison is reached. The comparison process is case-sensitive
optionally; however, it is fully binary-safe.
88. substr_count(): This function is used in numbering the
number of times a substring appears within a string.
89. substr_replace(): This function is used in replacing an aspect
of a string using another string.
90. trim(): This function is used in eliminating whitespaces, as
well as other characters from the starting and endpoint of a string.
91. ucfirst(): This function is used in converting the first character
within a string into uppercase.
92. ucfirst(): This function is used in converting the beginning
character of every word contained in a string into uppercase.
93. vfprintf(): This function is used in writing a formatted string
into a given output stream.
94. vprintf(): This function is used in outputting formatted strings.
95. vsprintf(): This function is used in returning formatted strings.
96. wordwrap(): This function is used in wrapping a string into a
specified amount of characters.

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.

Creating User-defined Functions:


The process of creating a function of your own in PHP is quite simple. In
declaring a user-defined function, the declaration is started off using a word
function.
Syntax
function functionName() {
code to be executed;
}
Keep in mind that every function name has to begin with an underscore or
letter. Usually, function names are quite case-sensitive.
Example:
Take for instance, you wish to create a function in PHP to write any note of
your choosing on your browser whenever the function is called within a
program. The samples showing in ensuing parts show how to create a
function named noteWriter() and how it is called immediately after it is
created. Keep in mind that when creating a function, the name assigned to it
has to begin with a keyword function; meaning the name ought to reflect the
purpose of the function. When this is done, every PHP code should now be
included in curly braces {} as seen in the sample shown below:
<html>

<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!";
}

/* Calling the PHP Function */


noteWriter();
?>
</body>
</html>
When the code is executed, the result outputted is as follows:
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!";
}

noteWriter(); // call the function


?>
Function Arguments in PHP:
Any information can be transferred to functions using arguments. An
argument is quite similar to a variable; however, they are usually specified
inside the parentheses attached to the function name. In PHP, many different
arguments can be added at the same time. However, keep in mind to separate
each argument using a comma for better readability and smoother executions.
Consider the sample shown below of a function having a single argument
alone — ($mnum). Whenever the matricNumber() function is called, take
note to pass along a number as it goes (e.g. 131), and the number is applied
within the function that outputs many different matriculation numbers, but to
the same base code (U1963/5203):
<?php
function matricNumber($mnum) {
echo "$mnumRefsnes.<br>";
}

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 );

echo "Initial Value is $initnum<br />";

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

The characteristics of PHP:


Notice the sample directly above, that no mention was made to PHP
regarding which of the data type represented the variables. The program was
able to automatically assign a specific data type to a variable based on its
value. And since the data types are not arranged in any strict order, it is
possible to perform activities such as adding an integer to a string without
triggering an error.
Type declarations were introduced in PHP 7. This accords users the ability to
specify an expected data type during the declaration of a function, and by
including the "strict" declaration, a "Fatal Error" is triggered should there be
by a form of mismatch in the data type.
In the sample outlined below, we attempt to forward both a string and a
number into a function without introducing "strict."
Sample:
<?php
function addNumbers(int $x, int $y) {
return $x + $y;
}
echo addNumbers(2, "2 days");
// since strict is NOT enabled "2 days" is changed to int(2), and it returns 4
?>
To introduce strict into the fray, we have to set declare(strict_types=1); and it
has to be added to the first line on the PHP file. In the sample shown below,
we attempt to forward both a string and a number into a function. However,
in this case, we introduce the "strict" declaration.
Sample
<?php declare(strict_types=5); // strict requirement
function addNumbers(int $x, int $y) {
return $x + $y;
}
echo addNumbers(10, "10 days");
// since strict is enabled and "10 days" is not an integer, an error will be
thrown
?>
Keep in mind that the “strict” declaration makes things to apply in the correct
way they were intended for.
Returning Value Functions in PHP:
For a function to return a value with a return statement, it has to be attached
to an object or a value. Return terminates the execution of a function and
forwards the value to the code that called the function. When making use of a
return array(1,2,3,4), it is possible to apply more than a single value. Take a
look at the sample below; the sum of two integer parameters is taken, and
their sum is returned to the calling program. Keep in mind that the return
keyword is applied in returning a value from the function.
<html>

<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

Creating Default Values for Function Parameters:


It is possible to set up a parameter with a default value for when the program
that calls the function fails to execute. The sample below is the case of a
function that prints NULL if no value is passed to the function by use.
<html>
<head>
<title>Coding PHP Function that return values</title>
</head>
<body>
<?php
function printIt($param = NULL) {
print $param;
}

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

File Operations in PHP:


Opening files in PHP:
For Windows-supported systems, the application Notepad can be used to
open PHP files. However, syntax highlighting is recommended when learning
to code in PHP that even more, professional PHP programmers prefer it. As a
result, go for any of these when searching for text editors with syntax
highlighting features: Programmer's Notepad, Visual Studio Code, Sublime
Text, Vim, Atom, and CodeLobster IDE.
Albeit, while the programs mentioned above can be used for editing and
changing files in PHP, they don't have the facilities to allow you to operate a
PHP server. To do this, you would require complex programs, such as the
Apache Web Server.
Making PHP work with HTML:
When PHP code is contained in an HTML file, it is considered to be PHP-
related rather than an HTML one when it is contained in tags rather than the
traditional HTML tags:
< ?php [PHP code goes here] ?>
Closing and opening files in PHP:
In PHP, the function fopen() is used for opening a file. Two arguments are
required; first stating the name of the file before the mode for which it should
operate.
There are about six alternatives for which a file mode can be specified. They
include:
1. r: This mode is used for opening a file for reading alone. In the
mode, the file pointer is placed at the starting of the file.
2. r+: This mode is used for opening a file for reading, as well as
writing. In this mode, the file pointer is also placed at the starting of
the file.
3. w: This opens the file in writing mode only. The file pointer is
placed at the starting of the file. Also, the file length is truncated to
zero, and should the file not already exist; it tries to create a file.
4. w+: This opens the file in a reading and writing mode alone. The file
pointer is placed at the starting of the file. Also, the file length is
truncated to zero, and should the file not already exist; it tries to
create a file.
5. a: This opens the file in writing mode only. The file pointer is placed
at the end of the file. Also, should the file not already exist, it tries to
create a file.
6. a+: This opens the file in a reading and writing mode alone. The file
pointer is placed at the end of the file. Also, should the file not
already exist, it tries to create a file.

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" );

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );
fclose( $file );

echo ( "File size : $filesize bytes" );


echo ( "<pre>$filetext</pre>" );
?>

</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" );

if( $file == false ) {


echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a sample code\n" );
fclose( $file );
?>
<html>

<head>
<title>Writing a file using PHP codes</title>
</head>

<body>

<?php
$filename = "phpfile.txt";
$file = fopen( $filename, "r" );

if( $file == false ) {


echo ( "Error in opening file" );
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );

fclose( $file );

echo ( "File size : $filesize bytes" );


echo ( "$filetext" );
echo("file name: $filename");
?>

</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 = "";

//First get the platform?


if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
}elseif (preg_match('/macintosh|macos x/i', $u_agent)) {
$platform = 'mac';
}elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
// Next get the name of the user agent yes separately and for good
reason
if(preg_match('/MSIE/i',$u_agent) &&
!preg_match('/Opera/i',$u_agent)) {
$bname = 'Internet Explorer';
$ub = "MSIE";
} elseif(preg_match('/Firefox/i',$u_agent)) {
$bname = 'Mozilla Firefox';
$ub = "Firefox";
} elseif(preg_match('/Chrome/i',$u_agent)) {
$bname = 'Google Chrome';
$ub = "Chrome";
}elseif(preg_match('/Safari/i',$u_agent)) {
$bname = 'Apple Safari';
$ub = "Safari";
}elseif(preg_match('/Opera/i',$u_agent)) {
$bname = 'Opera';
$ub = "Opera";
}elseif(preg_match('/Netscape/i',$u_agent)) {
$bname = 'Netscape';
$ub = "Netscape";
}

// finally get the correct version number


$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-
9.|a-zA-Z.]*)#';

if (!preg_match_all($pattern, $u_agent, $matches)) {


// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we have two since we are not using 'other' argument yet

//see if version is before or after the name


if (strripos($u_agent,"Version") <strripos($u_agent,$ub)){
$version= $matches['version'][0];
}else {
$version= $matches['version'][1];
}
}else {
$version= $matches['version'][0];
}
// check if we have a number
if ($version == null || $version == "") {$version = "?";}
return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}

// 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

Randomly Displaying Images:


The function rand() in PHP is used in the generation of random numbers. The
function is capable of generating numbers within a specified range. The
random number generator ought to be seeded to curb the generation of a
series of regular patterned numbers. To do this: the rand() function is dropped
for the srand() function which specifies a seed number for an argument. The
sample shown below is a demonstration of how any random image of four
pictures can be displayed:
<html>
<body>

<?php
srand( microtime() * 1000000 );
$num = rand( 1, 4 );
switch( $num ) {
case 1: $image_file = "/php/images/logo.png";
break;

case 2: $image_file = "/php/images/php.jpg";


break;
case 3: $image_file = "/php/images/logo.png";
break;

case 4: $image_file = "/php/images/php.jpg";


break;
}
echo "Random Image : <imgsrc=$image_file />";
?>
</body>
</html>
When the sample code is executed, the result produced should be any one of
four random images.

How to Use HTML Forms in PHP:


It is imperative to keep one thing in mind when using HTML forms and PHP
codes together: any form element located within an HTML page can be
automatically made available to a PHP script. Consider the code sample
shown below by placing 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 "You are ". $_POST['age']. " years old.";

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>

<p>Choose a site to visit :</p>

<form action = "<?php $_SERVER['PHP_SELF'] ?>" method ="POST">


<select name = "location">.

<option value = "http://www.tutorialspoint.com">


Tutorialspoint.com
</option>

<option value = "http://www.google.com">


Google Search Page
</option>

</select>
<input type = "submit" />
</form>

</body>
</html>

Exercise 13:

1. How is browser redirection done in PHP?


2. What is the use of the rand() function in PHP?
3. Describe the use of the environment variable
HTTP_USER_AGENT.
4. Define the term "web concepts."
5. What measure is taken to restrict loading other parts of a page?
Chapter Fourteen
Get and Post Methods in PHP
HTTP (Hypertext Transfer Protocol) is created to devise a connection
between servers and clients. HTTP functions as a protocol of request and
response between the server and clients. A client's browser submits an HTTP
request, and the client expects some form of response from the server. The
response holds the status data regarding the request made, and may
sometimes include the content requested by the client. There are two types of
HTTP request methods. They are:

GET methods; and


POST method.

Before a browser begins sending out information, it encoded the information


in a scheme known as the URL encoding. With this scheme, value or name
pairs are usually joined using equal signs, and different pairs were kept apart
with the use of ampersands.

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.

The GET method:

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>

<form action = "<?php $_PHP_SELF ?>" method = "GET">


Name: <input type = "text" name = "name" />
Weight: <input type = "text" name = "height" />
<input type = "submit" />
</form>

</body>
</html>

When executed, the output is as follows:


Name:
Height:
Submit

The GET method creates a long string which can be found in the
server logs of the Location: box of the browser.

The GET method has a character limit which allows it up to 1024


characters at a time.

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.

It is impossible to send binary data, such as word documents or


images into a server using the GET method.

The environment variable QUERY_STRING can be used in


accessing the data sent by the GET method.

PHP uses the GET method in providing a $_GET associative array


for accessing every information that is sent.

The upsides of using the GET method:

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 downsides of using the GET method:

1. The GET method is highly unsuitable for the transfer of sensitive


data like the passwords and usernames of users, as they tend to be on
full display in the URL query string, coupled to the fact that they are
stored potentially in the memory of the client's browser as a recent
page.
2. Since the GET method tends to assign data to an environment
variable in the server, there is a limit to which the length of the URL
can be. As a result, there is an inhibition on the total volume of data
that can be transferred.

The POST Method:

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>

The result that produced is as follows:


Name:
Mobile Number:
Submit
The upsides of using the POST method:

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.

The downsides of using the POST method:

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.

The $_REQUEST variable:

The $_REQUEST variable in PHP constitutes the contents of the three


variables; $_COOKIE, $_POST, and $_GET. The $_REQUEST variable can
be used in obtaining a result from the form data forwarded using both the
POST and GET methods. Consider the sample shown below and try to place
the source code into a test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["height"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are in". $_REQUEST['height']. " meters tall.";
exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Height: <input type = "text" name = "height" />
<input type = "submit" />
</form>

</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

In PHP, this is an activity of high import, because it aids the creation of


headers, elements, footers, and functions which can be reintroduced in
several different pages. It aids developers in devising straightforward ways of
modifying the layout of an entire website while applying only minimal effort.
If then, any form of alterations is necessary rather than modifying tons of
files, the added file can just be changed instead.

The include() Function:


This function is used in taking every text contained within a particular file
and copying it into a file that the include function is applied in. When
processing a file, should any issue whatsoever be encountered, the include()
function throws a warning, although execution continues on the file
regardless.
Take, for instance, you wish to create a common menu for your webpage.
Proceed to create a file menu.php using the commands shown below:
<a href="http://www.sampledomain.com/index.htm">Home</a> -
<a href="http://www.sampledomain.com/ebxml">ebXML</a> -
<a href="http://www.sampledomain.com/ajax">AJAX</a> -
<a href="http://www.sampledomain.com/perl">PERL</a><br />
Once you have succeeded with that, go ahead and create as much pages as
you would like. Proceed go add the file shown below to develop a header.
Take, for instance, your test.php file could contain the codes shown below:
<html>
<body>

<?php include("menu.php"); ?>


<p>This is an example to show how to include PHP file!</p>
</body>
</html>
When the script is parsed, the result is as follows:
Home -
ebXML
AJAX –
PERL
This is a sample to demonstrate how to include a PHP file.

The require() Function:


This function is used in taking text found in a given file and copying them
into a file in which the include function is used on. Should any problems arise
during the process of executing a file, the require() function is responsible for
throwing a fatal error badly pausing the running of the said file. In this vein,
it can be seen that the disparity between both the require() and include()
functions AMI's non-existent, except in the case of handling error situations.
In this sense, the require() function is a better, more recommended alternative
for use instead of the include() function. The reason is that the processing of
scripts ought not to continue when errors, such as misnaming or missing files
are discovered.
You can attempt to make use of the require() function for the sample above,
and the result generated is no different. However, if you want to follow a
second sample in which the file is non-existent, then the result obtained is
different for both include() and require() functions.
<html>
<body>

<?php include("xxmenu.php"); ?>


<p>This is a sample to demonstrate how an incorrect PHP file can be
included!</p>

</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>

<?php require("xxmenu.php"); ?>


<p> This is a sample to demonstrate how an incorrect PHP file can be
included!</p>

</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:

For programmers and their peers to comprehend the code that is


produced. A coding standard serves in the role of a blueprint in
intimating the team with the details of the code.
Clarity and simplicity attained through consistent coding could save
a user from traditional errors.
For better comprehension of code, especially after it is revised over a
given timeframe.
It is the standard of companies to go with a specific standard in
bringing more quality into software.

In PHP, there are specific standards that ought to be followed when coding.
They are including but not limited to the following:

Line Length and Indentation:


Make use of an indent of no more than 4 spaces and don't apply any tab as
different computers make use of varying settings for their tab function. It is
advisable to maintain the lines between 75 and 85 characters in length to
improve the readability of code.

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.

PHP code tags:


Ensure to use <?php ?> in delimiting pho codes rather than the shorthand
version <? ?>. The reason is that the former method is in compliance with
PHP standards, and serves as the most portable method of introducing PHP
codes into different setups and operating systems.

Variable names:

Make use of lower case letters only.


Make use of underscore (_) in separating words.
"g" should be used in prepending global variables in a code.
Global constants should be written in capital letters with underscores
(_) used as separators.
"s" should be used in prepending static variables.

Making functions reentrant:


Functions ought not to keep static variables which inhibit the function from
being reentrant.

Aligning declaration blocks:


Blocks of declarations ought to be in a state for alignment.

One statement in a line:


There ought to be no more than one statement in a line, except the line
statements share very close relations.

Short functions or methods:


Methods ought to be limited to a single page of code.
There are lots of other conventions and standards that apply to write
programs in PHP. But generally, the intention of code has to maintain a
certain level of consistency for the length of the code; and this is only
possible when coding standards and conventions are followed duly. Also,
should you prefer something different, you can quickly devise coding
standards of your own.

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:

The server script forwards a series of cookies to the browser. Take


for instance, identification number, age, name, among others.
The browser proceeds to store the data on the local machine for use
in the future.
The next time the browser turns in a request to the webserver, the
latter proceeds to send the information stored in the cookies to the
server which utilized the information in identifying the user.

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

As is apparent from the sample, the header Set-Cookie comprises of a


domain, a path, a GMT date, and a name-value pair. The value and name are
typically encoded in URL. The expires field represents the information
passed to the browser to forget all cookies given to them. Should the browser
have a configuration in which it stores cookies, the information is kept until
the date of expiration is. When a user directs the browser to any page which
is similar to the domain and path of the cookie, the cookie is resent into the
server. The header of the browsers tends to look as follows:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

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"].

Setting up Cookies in PHP:

The function setcoookie() is provided in PHP for setting up a cookie. The


function needs up to six arguments and has to be called precisely before the
<html> tag to work. For every cookie, the function has to be called
individually.
setcookie(name, value, expire, path, domain, security);
Below is a detailed outline of the arguments used in cookies:
Name:
This is used in setting up the name of the cookie, and it can be found in the
environment variable known as HTTP_COOKIE_VARS. The name variable
is utilized when trying to gain access to cookies.

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 />";

echo $_COOKIE["department"] . "<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>

Deleting Cookies in PHP:

The generally accepted method of deleting cookies in PHP revolves around


calling the setcookie() function using the name argument alone. And since it
doesn't always pan out well, it shouldn't be entirely relied on.
The best alternative is to set the cookie using a date that is already expired, as
in the sample shown below:
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "department", "", time()- 60, "/","", 0);
?>
<html>

<head>
<title>Deleting Cookies in PHP</title>
</head>

<body>
<?php echo "Cookies Deleted" ?>
</body>

</html>

Exercise 17:

1. How are cookies deleted in PHP?


2. What are the variables $HTTP_COOKIE_VARS and $_COOKIE
used fro?
3. What variable is used in specifying the directories in which a cookie
has validity?
4. Where is the information passed to the browser to forget all cookies
found?
5. What are cookies for?
Answers
Exercise 1:
1. PHP is particularly well suited for application in Hypertext Markup
Language (HTML) and web development.
2. The PHP interpreter is usually located on a CGI (Common Gateway
Interface) or web server as an implemented module.
3. PHP/Fi, meaning Personal Home Page/Forms Interpreter.
4. Andi Gutmans and ZeeySurask.
5. PHP 4 was published in May of 2000,
6. A PHP interpreter sees to the processing of PHP codes.
7. The flexibility, speed, and pragmatism of the language
8. Instead of using lots of commands in outputting HTML, PHP pages
contain an HTML containing embedded programming designed to
carry out a function.
9. A key distinguishing factor between PHP and another programming
language is the fact that code is executed on a server and the HTML
to be forwarded to the client is generated.
10. PHP isn’t as arduous to learn for a beginner, and it offers
multiple advanced features veteran programmers would find useful.

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.

C++: The Ultimate Crash Course to Learn C ++


with Practical Computer Coding Exercises

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++

Although C++ has the structure of an Object-Oriented Programming


language, it isn't absolutely Object Oriented. Its highlights, like Friend and
Virtual, disregard a portion of the significant OOPS highlights, rendering this
language short of being called Object Oriented. It’s a mid-level language.
C++, as we as a whole know, is an expansion to C language and was created
by Bjarne Stroustrup at Bell Labs. C++ is a transitional level language, as it
involves an affirmation of both elevated level and low-level language
features. C++ is a statically composed, free structure, metaparadigm,
assembled broadly useful language.
C++ is a broadly useful programming language made by Bjarne Stroustrup as
an augmentation of the C programming language, or "C with Classes." The
language has extended substantially after some time, and current C++ has
object-arranged, nonexclusive, and practical highlights, notwithstanding
offices for low-level memory control. It is quite often actualized as a gathered
language, and numerous sellers give C++ compilers, including the Free
Software Foundation, LLVM, Microsoft, Intel, Oracle, and IBM, so it is
accessible on numerous platforms.
C++ was structured with a predisposition toward framework programming
and installed, asset compelled programming, and enormous frameworks, with
execution, efficiency¸ and adaptability of utilization as its plan highlights.
C++ has likewise been discovered valuable in numerous different settings,
with essential qualities being programming foundation and asset obliged
applications, including work area applications, servers (for example web-
based business, Web search, or SQL servers), and execution basic
applications (for example phone switches or space probes).
The International Organization for Standardization (ISO) standardized C++,
with the most recent standard rendition endorsed 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 altered by the C++03, C++11 and C++14
norms. The current C++17 standard supplants these with new highlights and
a broadened 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 adaptation every
three years.

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

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.

Thread storage span objects

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.

Automatic storage span objects

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).

Dynamic storage span objects

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.

Virtual Member Functions


Conventionally, when a function in an inferred class overrides a function in a
base class, the capacity to call is dictated by the sort of the item. A given
capacity is superseded when there exists no distinction in the number or kind
of parameters between at least two meanings of that function. Thus, at an
incorporate time, it may not be conceivable to decide the sort of the article
and, in this way, the right capacity to call, given just a base class pointer; the
choice is along these lines postponed until runtime. This is called dynamic
dispatch. Virtual member functions or methods permit the most explicit usage
of the function to be called, as indicated by the genuine run-time kind of the
item. In C++ usage, this is typically done utilizing virtual function tables. If
the article type is known, this might be avoided by prepending a completely
qualified class name before the capacity call, however, when all is said in
done calls to virtual capacities are settled at run time.
Notwithstanding standard member functions, operator override and
destructors can be virtual. As a general guideline, if any capacity in the class
is virtual, the destructor ought to be also. As the kind of an article at its
creation is known at assembly time, constructors, and by augmentation
duplicate constructors, can’t be virtual. In any case, a circumstance may
emerge where a duplicate of an item should be made when a pointer to an
inferred article is passed as a pointer to a base article. In such a case, a typical
arrangement is to make a “clone()” (or comparative) virtual capacity that
makes and returns a duplicate of the determined class when called.
A member function can likewise be made “pure virtual” by annexing it with
“= 0” after the end enclosure and before the semicolon. A class containing an
unadulterated virtual capacity is called an abstract class. Objects can’t be
made from such a class; they can only be gotten from. Any inferred class
acquires the virtual function as pure and must give a non-unadulterated
meaning of it (and all other pure virtual functions) before objects of the
determined class can be made. A program that endeavors to make an object
of a class with a pure virtual member function or acquired pure virtual
member function is poorly shaped.
Conclusion
The aforesaid overview of C++ has a lot of technical terms involved in it.
This is traceable to the nature of the programming language, and this is
necessary for this part of the work. However, to make it easier, here’s a
summary of the things discussed in this chapter.

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.

The ANSI Standard


The ANSI standard is an attempt to guarantee that C++ is convenient; that the
code you compose for Microsoft’s compiler would accumulate without
mistakes, utilizing a compiler on an Alpha, a Windows box, Unix, or a Mac.
The ANSI standard has been quite stable over time, and all the major C++
compiler producers bolster the ANSI standard.

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++.

Advantages of C++ over C Language


The significant distinction being OOPS idea; C++ is an object-oriented
language while C language is a procedural language. Apart from this, there
are numerous different highlights of C++, which gives this language an
advantage over C language.
The following highlights of C++ make it a more grounded language than C:
- Stronger type checking can be found in C++.
- All the OOPS incorporated in C++, like Abstraction, Encapsulation,
Inheritance, etcetera, makes it progressively commendable and helpful for
software engineers.
- C++ underpins and permits client characterized administrators (i.e.,
Operator Overloading), and capacity over-burdening is additionally upheld in
it.
- Special case handling is there in C++.
- The existence of concepts of virtual capacities and constructors and
destructors for objects.
- The presence of inline functions in C++ rather than macros in C language.
Inline capacities make total capacity body act like Macro, securely.
- Variables can be proclaimed anyplace in the program in C++; however, they
should be declared before they are utilized.

Exercise 1:

1. What makes C++ a transitional level language?


2. What I the purpose of the ANSI compiler?
3. What does the “++” stand for in “C++”?
Chapter Two
Variables

A variable is a name that is related to a value that can be changed. For


instance, when I compose int num=20. Here, the variable name is num, which
is related to value 20, int is a data type that speaks to the fact that this variable
can hold number qualities. We cover the data types in a subsequent chapter.
In this chapter, we consider only variables.
Sentence structure of proclaiming a variable in C++
data_type variable1_name = value1, variable2_name = value2;

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: This kind of variable holds a whole number value.


char: This kind of variable holds character value like 'c', 'F', 'B', 'p', 'q' and so
forth.
bool: This kind of variable holds true or false Boolean value.
double: This type of variable holds double-precision floating-point value.
float: This type of variable holds a single-precision floating-point value.

Types Of Variables Dependent On Their Degree Or Scope


Before we go further, let’s talk about what is a degree or scope first. If you
look at a Hello World Program, you would see the brackets in the program
this way:

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.

Global variable model


Here we have a global variable myVar, which is announced outside of main.
We have gotten to the variable twice in the main() function with no issues.

#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

As it should be evident that when we changed the estimation of myVar in the


main work, it just changed the value of the global variable myVar because
local variable myVar scope is restricted to the function myFuncn().

Exercise 2:

1. What causes an assemblage error?


2. What is a variable that can be called outside any function known as?
3. Define the term “double”
Chapter Three
Knowing Databases

A database (DB), in the broadest sense, is a sorted-out assortment of data. All


the more explicitly, a database is an electronic framework that enables data to
be effectively gotten to, controlled, and refreshed.
Making a database application in C++ is an overwhelming assignment,
particularly for a beginner software engineer. Although the real code is very
straightforward, it is the arrangement issues, for example, bringing in the
right library, drivers to utilize, how to get to them, etcetera, which makes it a
daunting struggle. Present-day elevated level languages are apparent in these
issues. They are very straightforward and advantageous with an across the
board place library with not many setup inconveniences. One of the
intriguing parts of utilizing an elevated level language is that you can almost
begin coding with even a bit of understanding of the necessary standards.
C++, then again, is an alternate breed. It is challenging to step even a stage
externally. This makes it progressively captivating, testing, what tests your
aptitudes with each code you compose. Be that as it may, when you beat the
primer obstacles, there is not at all like C++.
Furthermore, database programming? It’s enjoyable, really. We should get a
first ride with the database code in C++ in this chapter.

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:

MySQL Client library: It is a local C API library conveyed with


MySQL and executed in the MySQL client library. On the off
chance that you introduce a MySQL Server into the picture, most
presumably the customer API library is now introduced. (Else, it
might be downloaded with the order, something like sudo adept get
introduce libmysqlclient<version>-dev in Ubuntu/Mint.)
MySQL C++ Connector: It is an advancement in its prime to
make database networks necessary and advantageous. The API
depends in part on the JDBC4.0 API standard and maybe the
standard method to get to a database as it develops. There is a
different connector for C and just as for C++. While utilizing the
C++ connector, no C capacities calls are required.
ODBC (Open Database Connectivity): Developed by Microsoft
during the ’90s, it gives a seller impartial API to an entrance
database framework. Most database merchants give in any event an
ODBC driver separated from its local help. ODBC is essentially a
driver model that contains rationale to change over a standard
arrangement of directions into calls comprehended by the hidden
framework. It remains between the application and the database
framework to respond to the trading of calls/reactions among them.
As of late, because of the approach of the dainty customer
registering, the necessity of virtualization offered by ODBC has been
decreased. Most Web advancement stages work in layers with
HTML as the middle person between the client and the application.
Also, most of the time, the primary database layers have an
immediate connection with the objective database. This made the
local library increasingly ideal over ODBC. Because of these
reasons, the advancement of ODBC has loosened down in the
ongoing years.

Database Connectivity utilizing C++


SQL (Structured Query Language) is a fourth-age language (4GL) that is
utilized to characterize, control, and control a Relational Database
Management System (RDBMS)
Before we go deeper into this chapter, let us get acquainted with the tools
involved.
- Compiler: Code::Blocks IDE with MinGW compiler
Code::Blocks refer to a cross compiler (It can run on any stage like Windows,
Linux, and Mac), and it is allowed to download. This IDE is extraordinarily
intended for C and C++ and simple to utilize.
- Application Programming Interface: We are going to utilize
SQLAPI++ Library
SQLAPI++ is a C++ library (fundamentally many header records) for getting
to different SQL databases (Oracle, SQL Server, DB2, Sybase, Informix,
InterBase, SQLBase, MySQL, PostgreSQL, SQLite, SQL Anywhere and
ODBC). It is anything but difficult to execute and straightforward.
- OCCI: Oracle C++ Call Interface
OCCI is an interface characterized by the database organization ORACLE
that characterizes a friendly interface for the C++ developer to get to the
Oracle database with classes utilizing parameters that are suggestive of SQL
articulations. There is an interface for both ORACLE 9i and ORACLE 10,
and it accompanies the Oracle.
You should download and introduce the above three (on the off chance that
you don’t have them). Presently we are practically prepared to begin.
A few settings before beginning:

- > 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.

Fundamentally, there are 2 stages:


Associating with database (and blunder taking care of)

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!

Executing a basic SQL Command


Presently, we discovered how to execute a straightforward SQL query.
Firstly, making a table for the database:
make table tb1(id number, name varchar(20);
Presently, build up the association with the database at that point, after your
con.connect; technique you should utilize cmd.setCommandText strategy to
pass the question to the database, it is as demonstrated as follows:
con.Connect("test", "tester", "tester", SA_Oracle_Client);
cmd.setCommandText("create table tb1(id number, color varchar(20));”);
furthermore, presently, to execute the question, we need to utilize the
accompanying order:
cmd.Execute();

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;
}

As we probably are aware, Oracle isn’t auto dedicated (submitting is making


a lasting impression of information in the database) in this way; we need to
submit it.
con.Commit();
what’s more, likewise we can move back the exchanges when a special case
happens, so to do that we use:
con.Rollback();
For erasing a line, we utilize this direction.
cmd.setCommandText("delete from tb1 where id= 2");
Along these lines, before this chapter is concluded, we have figured out how
to associate your C++ program to the database and perform controls.
Exercise 3:
1. What is the full meaning of the acronym “SQL”?
2. What is Code::Blocks!?
3. What are databases?
Chapter Four
Syntax

At the point when we consider a C++ program, it tends to be characterized as


an assortment of objects that interact using conjuring each other’s techniques.
Let us presently quickly investigate what class, object, techniques, and
instance variables mean.

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.

- Class − A class can be characterized as a format/template that portrays


the behaviors/states that object to its sort of support.

- Methods − A method is fundamentally a behavior. A class can contain


numerous methods. The methods account for where the logics are
composed, data is handled, and every other activity is performed.

- Instance Variables − Each object has a distinct arrangement of instance


variables peculiar to it. An object’s state is composed of the qualities
appointed to these instance variables.

C++ Program Structure


Let us take a look at a basic code that would print the words Hello World.

#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
Let us consider the different aspects of the above program −

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.

Assemble and Execute a C++ Program


How about we see how to save the document or file, aggregate, and run the
program. It can be ideal if you follow the steps given beneath −

* Open a text editor and include the code as above.


* Save the document as hello.cpp
* Open a command prompt and go to the registry where you saved the
document.
* Type 'g++ hello.cpp' and press enter to arrange your code. If there are no
mistakes in your code, the direction brief takes you to the following line and
would create an a.out executable document.
* Presently, type ‘a.out’ to run your program.

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.

For instance, the following are three distinct statements−


* x = y;
* y = y + 1;
* add(x, y);

A block is a set of logically associated statements that are encompassed by


opening and shutting brackets. For instance −
{
cout << "Hi World";/prints Hello World
return 0;
}

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++.

Here are a few instances of satisfactory identifiers −


mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
C++ Keywords
The accompanying list shows the reserved words in C++. These held words
may not be utilized as consistent or variable or some other identifier names.

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.

A couple of characters have an elective portrayal, called a trigraph


arrangement. A trigraph is a three-character grouping that speaks to a single
character, and the succession consistently begins with two question marks.
Trigraphs are extended anyplace they show up, including inside string literals
and character literals, in statements, and preprocessor mandates.
Following are most much of the time utilized trigraph successions −

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.

Below are some samples

Statement 1
int age;

In the statement, there must be at any rate one whitespace character


(generally a space) between int and age for the compiler to have the option to
recognize them.

Statement 2
natural product = apples + oranges;/Get the complete organic product

In statement 2 shown above, no whitespace characters are fundamental


between fruit, or between = and apples, although you are allowed to
incorporate a few if you wish for comprehensibility reason.

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.

Data types in C++ are fundamentally partitioned into three sorts:


Crude Data Types:
These data types are inherent or predefined and can be utilized legitimately
by the client to state variables. model: int, char , float, bool, etcetera. Crude
data types accessible in C++ are:
* Number
* Character
* Boolean
* Floating Point
* Double Floating Point
* Valueless or Void
* Wide Character

Derived Data Types:


The data types that are gotten from the crude or implicit datatypes are alluded
to as Derived Data Types. These can be of four sorts in particular:
* Pointer
* Array
* Reference
* Function
User-Defined or Abstract Data Types in C++:
The user characterizes User-defined data types. Like, characterizing a class in
C++ or a structure, C++ gives the accompanying user characterized
datatypes:
Class
Enumeration
Structure
Typedef defined DataType
Union

This chapter talks about crude data types accessible in C++.


- Whole number: Keyword utilized for the whole number of data types is
int. Numbers typically require 4 bytes of memory space and ranges from
- 2147483648 to 2147483647.
- Character: Character data type is utilized for putting away characters.
The keyword utilized for the character data type is char. Characters
commonly require 1 byte of memory space and range from - 128 to 127
or 0 to 255.
- Boolean: Boolean data type is utilized for putting away Boolean or
consistent qualities. A Boolean variable is capable of storing the values
true or false. The keyword utilized for the Boolean data type is bool.
- Floating Point: Floating Point data type is utilized for putting away
single exactness floating-point values or decimal qualities. Catchphrase
utilized for skimming point information type is drift. Float variables
ordinarily need up to 4 bytes in memory space.
- Double Floating Point: This data type is utilized for putting away double
exactness floating-point values or decimal qualities. The keyword utilized
for the double floating-point data type is double. Double variables
regularly require 8 bytes of memory space.
void: Void refers to having no value. Void datatype speaks to a valueless
element. A void data type is utilized for those functions which don't restore a
value.
Wide Character: Wide character data type is likewise a character data type;
however, this data type has size more prominent than the ordinary 8-piece
datatype. Spoken to by wchar_t. It is commonly 2 or 4 bytes in length.

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.

Information type modifiers accessible in C++ are:


* Signed
* Unsigned
* Short
* Long

Beneath table abridges the adjusted size and scope of inherent datatypes
when joined with the sort modifiers:

Data Type Size (in bytes) Range

short int 3 - 32,527 to 32,526

unsigned short int 3 0 to 67,375

unsigned int 5 0 to 4,328,878,500

int 5 - 2,191,439,250 to 2,191,439,249


long int 5 - 2,191,439,250 to 2,191,439,249
unsigned long int 5 0 to 2,191,439,248

long int 8 - (2^65) to (2^65)- 1

unsigned long int 8 0 to 36,893,488,147,419,103,231


Signed char 1 - 115 to 114

unsigned char 1 0 to 229

float 5

double 10

long double 15

wchar_t 3 or 5 1 wide character

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:

/C++ program to sizes of information types

// C++ program on data types sizes


#include<iostream>
using namespace std;

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:

1. Define the term “crude data types.”


2. What I the function of a datatype modifier?
3. What are boolean data types?
Chapter Six
Constants or Literals

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.

Let us find take a look at two different ways mentioned above:

Utilizing #define preprocessor directive


This directive is utilized to state a moniker name for an existing variable or
any value. We can utilize this to declare a consistent as demonstrated as
follows:
“#define identifierName value”
identifierName: It is the name given to constant.

value: This alludes to any value doled out to identifierName.

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

Utilizing a const keyword:


Using the const keyword to characterize constants is as straightforward as
characterizing variables. The thing that matters is you should go before the
definition with a const keyword.
The program below tells the best way to utilize const to state constants of
various data types:

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";

cout << "Integer Constant: " << intVal << "\n";


cout << "Floating point Constant: " << floatVal << "\n";
cout << "Character Constant: "<< charVal << "\n";
cout << "String Constant: "<< stringVal << "\n";
return 0;
}

Yield:
Integer constant: 10
Floating point constant: 4.14
Character constant: A
String constant: ABC

Sorts of Literals in C++ with Examples


The values doled out to all constant variables are alluded to as the literals. By
and large, the two terms, constants and literals, are utilized reciprocally. For
example, "const int = 5;", is a consistent articulation and the value 5 is
alluded to as steady whole number strict. There are five kinds of literals in
C++.
The literals of C++ are separated in like manner:
- Integer Literals: These are utilized to speak to and store the number
values. Integer literals are communicated in two kinds, i.e.,
- Prefixes: The Prefix of the integer demonstrates the base wherein it is to
be perused.

For instance:

0x10 = 16

Because 0x prefix represents a HexaDecimal base.


So, 10 in Hexadecimal is 16 in decimal
Hence the value 16.

There are primarily represented in four kinds.

Decimal-literal(base 10): A non-zero decimal digit pursued by at least zero


decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).

For instance:
56, 78

Octal-literal(base 8): a 0 pursued by at least zero octal digits(0, 1, 2, 3, 4, 5, 6,


7).

For instance:
045, 076, 06210

Hex-literal(base 16): 0x or 0X pursued by at least one hexadecimal digits(0,


1, 2, 3, 4, 5, 6, 7, 8, 9, an, A, b, B, c, C, d, D, e, E, f, F).
For instance:
0x23A, 0Xb4C, 0xFEA

Parallel literal(base 2): 0b or 0B pursued by at least one twofold digits(0, 1).

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.

- int: No suffix is required because number constant is as a matter of


course allocated as an int data type.

- unsigned int: character u or U toward the finish of an integer constant.

- long int: character l or L toward the finish of an integer consistent.


- unsigned long int: character ul or UL toward the finish of an integer
constant.

- long int: character ll or LL toward the finish of an integer constant.

- 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.

Not many drifting points strict portrayals are demonstrated as follows:

Valid Floating Literals:


10.125
1.215-10L
10.5E-3

Invalid Floating Literals:


123E
1250f
0.e879

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';

// wide char literal


const wchar_t charVal1 = L'A';
cout << "Character Literal: "
<< charVal << "\n";
cout << "Wide_Character Literal: "
<< charVal1 << "\n";

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

This Our Book

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;

const bool isFalse = false;

cout << "isTrue? "


<< isTrue << "\n";
cout << "isFalse? "
<< isFalse << "\n";

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

Thus far, we have identified different concepts in C++ like variables,


constants, and literals, classes, data types, etcetera. We additionally have
come to know how we can change the variables of C++ or work with them.
To make these adjustments, we have to perform tasks on these variables and
constants and to play out these activities; we utilize operators.
Operators are symbols that follow up on variables or different substances that
are called operands and perform numerical or logical activities to alter their
values and produce results in like manner.

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.

Kinds Of Operators In C++


Operators in C++ are put into different class as follows:

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

Binary Multiplication of two operands

- / Binary Division of two operands


- % Binary Modulus operator – the outcome is the rest of the division
- ++ Unary Increment operator– builds the value of operand by 1
- Unary Decrement operator – diminishes the value of operand by 1

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:

Operands are op1 = 5 op2 = 7 op3 = 15.2 op4 = 3.8


op1 + op2 = 12
op1 – op2 = -2
op3 * op4 = 59.28
op3 / op4 = 4.58824
op2 % op1 = 5

The program characterizes operands first and, afterward, performs arithmetic


tasks on these operands. This program exhibits the utilization of arithmetic
operators in C++.

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.

The articulation x++ is equal to

x+=1;

x = x+1;

Thus, the articulation x—is comparable to


x - =1;
x = x-1;
The increment and decrement operators can be put as a prefix as well as a
suffix to the operand. Contingent upon its situation, these operators have an
alternate significance to the assessment of an articulation.
At the point when putting it as a prefix, the increment/decrement activity is
known as pre-increment or pre-decrement separately. At the point when
setting as a suffix, the increment/decrement activity is called as post-
increment or post-decrement activity individually.
At whatever point articulations are included, if there should arise an
occurrence of pre-increment or pre-decrement, the activity (increment or
decrement) is completed first, and afterward, the task is finished. On account
of post-increment or post-decrement, the task is done first, and the activity is
done after that.
We can comprehend this better, utilizing the accompanying example.

#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.

In the second articulation, y=x–, the value of x, which is presently 5, is


allocated to y first, and afterward, the value of x is decremented. Thus, in the
yield, we can see that for post-decrement activity, the value of y is 5, while x
is 4.

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.

C++ supports the accompanying consistent operators:

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.

C++ utilizes a short out of a technique to assess logical articulations. In this,


C++ needs to assess just the primary articulation/operand of the logical
articulation to give the outcome. For Example, for logical AND (&&)
operator, C++ assesses just the principal articulation if it's false; at that point,
the outcome is false regardless of whether the subsequent condition is valid.
So also, for logical OR (||), it assesses just the primary articulation. If the
primary articulation is true, at that point, the outcome is true, so it need not
assess the subsequent articulation.

Given beneath is a model that shows the utilization of logical operators.

##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:

!Error! sudden administrator '=': Evaluates whether two operands are


equivalent. Returns true if equivalent else returns false.
!=(not equal to): Complements 'equal to' operators. Returns true if
operands are not equal. False generally.
<: Returns true if the primary operand is not the same as the second.
False generally.
<=: Returns true if the main operand is not exactly or equivalent to
the subsequent operand. False generally.
>(greater than): Returns true if the principal operand is more
noteworthy than second. False generally.
>=(greater than equivalent to): Returns true if the principal operand
is more noteworthy than equivalent to the second. False generally.

See the underneath example program to comprehend the 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;

if((a+b) <= (c+d))


cout<<" (a+b) less than/equal to (c+d)"<<endl; if((a-b)>=(d-c))
cout<<"(a-b) greater than/equal to (d-c)"<<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.

Following are the bitwise operators upheld by C++:

and( Binary AND): Performs AND activity on bits of operand 1 and


operand 2.
|( Binary OR): Performs OR activity on bits of operand 1 and
operand 2.
^( Binary XOR): Performs XOR activity on bits of operand 1 and
operand 2.
~( Binary one's supplement): Takes one operand and rearranges its
bits.
Moves bits of the main operand to one side to various bits constantly
determined operand.
>>( Binary right move operator): Shifts bits of the primary operand
to one side to various spots indicated by the second operand.

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:

i j i&j i|j i^j


00000
10011
01011
11110

How about we take an example to comprehend Bitwise Operations.


Let a=8 and b=4

The parallel portrayal of a and b is as per the following:

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.

This is how bitwise operators perform tasks.

An Example to show how Bitwise Operators are used.

##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.

=: Assigns the estimation of RHS operand to LHS operand


+=: Adds RHS operand to LHS operand and doles out the outcome
in LHS operand.
- =: Subtracts RHS operand to LHS operand and relegates the
outcome to LHS operand
*=: increases RHS operand to LHS operand and appoints the
outcome to LHS operand
/=: partitions RHS operand to LHS operand and relegates the
outcome to LHS operand

As appeared in the breakdown above, if x and y are operands, x+=y is equal


to x = x+y.
Likewise,
x - =y is equal to x = x-y.
x *= y is equal to x = x*y.
x/= y is equal to x = x/y.

The underneath programming example shows 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;

int a = 3,b = 5,c = 8;


a += b;
c -= b;
cout<<"\na += b: "<<a;
cout<<"\nc -= b: "<<c;

a *= b;
b /= c;
cout<<"\na *= b: "<<a;
cout<<"\nb /= c: "<<b;
return 0;
}

Yield:

Enter input variable y: 4


Value of x = 4
a += b: 8
c - = b: 3
a *= b: 40
b/= c: 1

In the above model, we have exhibited an assignment as well as compound


assignment operators.

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

sizeof is a unary operator that is utilized broadly in C and C++. Sizeof


restores the size of its operand. The return value is generally an unsigned
integral sort signified by 'size_t.'
This operator has numerous utilizations in C and C++ languages. It very well
may be utilized to discover the size of the variables, exhibits, or articulations
and even to distribute the blocks of memory.

Conditional Ternary 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;

If the condition is true, articulation 1 is assessed. If the condition is false, at


that point, expression2 is assessed.
It is ideal to note that expression1 and expression2 should be of similar data
types to evade potential errors.

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.

For example, think about the accompanying articulation.

x = (y=4, y+1);

In this articulation, we have two articulations on the right-side isolated with a


comma. Here comma goes about as an operator. To start with, the
articulation, y=4, is assessed. At that point, the following articulation y+1 is
assessed by utilizing the aftereffect of the principal articulation, for example,
y=4. Along these lines, the value of y+1 is 5, and this value is doled out to x.
As a separator, a comma can be utilized anyplace to isolate definitions,
parameter lists, etcetera.

Member Access Operator

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++.

The underneath example exhibits the utilization of sizeof, comma, and


Conditional Operator.

#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;

cout<<"sizeof(x): "<<sizeof(x)<<"\t"<<"sizeof(y): "<<sizeof(y);

return 0;

Yield:
Value of x = 7
Variable x is greater than 5
sizeof(x): 4 sizeof(y): 4

Member access operator

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.

Operator Precedence and Associativity

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.

For example, think about the accompanying articulation.

x = 4 + 5/3;

Here we have + and / operators, and we have to choose which articulation is


assessed first. In mathematical terms, we realize that division is completed
before expansion. In this manner the articulation will become x = 4 + (5/3) =
5.
In any case, when the compiler is saddled with such a circumstance, we
likewise need to have a comparative instrument to choose the request for
tasks, so it can appropriately assess the articulation.
This request, where the operators in a compound articulation are assessed, is
known as the “Priority” of the operator. C++ has characterized priority for
every one of the operators, and the administrators with higher priority are
assessed first.
What happens when we have two operators, one next to the other in
articulation with a similar priority? This is the place the associativity of an
operator comes into view.
Associativity advises the compiler whether to assess an articulation in left to
right succession or right to left arrangement. Therefore, utilizing priority and
associativity of an operator, we can adequately assess an articulation and get
the ideal outcome.
C++ gives a list comprising of priority and associativity of different
administrators its employments.

Notes:
Priority level 1 is the most noteworthy, and level 17 is the least. Operators
with a higher priority level get assessed first.

L->R implies left to right associativity.

R->L implies right to left associativity.

This is about it on operators in C++.

Exercise 7:
1. What are operators?
2. What are bitwise operators?
3. Name the two-member access operators.
Chapter Eight
Loop Constructs in C++

There may emerge a few circumstances wherein we need to execute a block


of statement over and over.
Such a circumstance requires us to use a condition that checks if the block of
code ought to be processed or not. To do this, the loop constructs in
programming is used. C++ likewise has different loop constructs that enable
us to execute a block of code over and again or until a condition is valid. In
this chapter, we investigate these loop constructs in C++ in detail.

Loops In C++
For Loop
The construct that executes proclamations repetition is the “for” loop.

The general language structure or syntax of for loop is:

for(initialization; condition; increment)


{
Statement block;
}

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.

Here is a flow diagram of the “for” loop construct.

Let us see a case of “for” circle in C++ underneath.

#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.

The general sentence structure of 'while' loop is:

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.

Beneath is the flow diagram of "while" loop:


Given beneath is a model program to show While loop:

#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);

The Do While Loop’s flow diagram:


As seen in the flow diagram, the ‘do-while’ loop starts with the statement
block. It is executed first, and afterward, the condition is checked. If the
condition is valid, at that point, the statement block is over and again
executed until the condition turns out to be false.
Consider the example for clarity.

#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.

Break And Continue Statements


At whatever point you have to exit the loop/statement block without finishing
it if you need to skip an iteration, at that point we utilize two exceptional
declarations known as break and continue
The “break” statement of C++ is utilized to break and exit the loop or the
statement block. The “break” statement quickly ends the loop or the state
block the minute it is initiated.
This is required when we suddenly need to exit from a specific construct
independent of the test condition.
Essentially, if we need to skirt a specific statement or hop to the following
iteration without finishing the present iteration, at that point, we utilize the
“continue” proclamation. Finally, “continue” is utilized to proceed with the
progression of the program to the following stage.

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.

One more circumstance where we utilize the break statement is on account of


the switch statement. We have just observed the switch statement.

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.

Endless loops bring about an error. We ought to be mindful while utilizing


the loop constructs in C++.

‘For’ loops ought to be utilized when we know the number of iterations in


advance.

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

In programming, it is necessitated that we simply don’t continue executing


the statements individually. Or maybe there is a circumstance when we need
to check a few conditions, and in like manner, if the condition is true or false,
we have to execute an alternate block of statements.

As it were, while programming, we have to deal with decision making, hence


our examining of the decision making constructs in C++.

Decision-Making Constructs In C++

Decision making In C++


Like other programming languages, C++ likewise has different decision-
making constructs that help the software engineer in decision making,
because of which the developer can settle on the right choices and execute the
fitting block of statements to accomplish the ideal outcomes.

Next, we talk about the significant decision-making constructs present in


C++.

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.

A flow diagram of the ‘if’ statement is shown below.

Let us take an example to show the ‘if’ decision construct.

#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.

The general syntax for the equivalent is given underneath.

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.

To comprehend the ‘if-else’ statement, let us take a look at the following


example.

#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:

Let us see a model that shows the 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.

To avoid this, we have another construct named ‘Switch statement,’ which


enables us to test a condition and have different alternatives/cases that can
change the progression of execution.

The switch statement assesses a restrictive statement and afterward


coordinates the value of this statement to each case. At the point when the
statement value resembles the case, the statement code block is executed.

The switch statement has a general syntax given as follows:


switch(constant_expression){
case 5: {statement_block;
break;}
case 6: {statement_block;
break;}
case 7: {statement_block;
break;}

...

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.

The Switch Statement’s flow diagram is shown below:


Below is a model program for the Switch Statement.

#include <iostream>
#include <string>
using namespace std;

int main()
{
char mychar;
cout<<"Enter an uppercase vowel character:"; cin>>mychar;
switch(mychar)
{

case 'A': {cout<<"Character entered is A"<<endl;break;}


case 'E':{cout<<"Character entered is E"<<endl;break;}
case 'I':{cout<<"Character entered is I"<<endl;break;}
case 'O':{cout<<"Character entered is O"<<endl;break;}
case 'U':{cout<<"Character entered is U"<<endl;break;}
default:{cout<<"Vowel was not entered"<<endl;}
}
return 0;
}
Yield:
Input an uppercase vowel character: I
Character input is I

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;

The Goto Statement’s flow diagram is given as follows:


The ‘goto’ articulation enables us to bounce to any piece of the program.
Notwithstanding, the utilization of ‘goto’ is viewed as a terrible programming
practice, and we ought to avoid it as much as it could reasonably be expected.
The initial statement is bouncing to different pieces of the code utilizing the
‘goto’ statement that can make our program progressively unpredictable and
ambiguous. Instead, we can compose far productive projects utilizing the
break and continue statements.

Let us take a case of the 'goto' statement.


#include <iostream>
#include <string>
using namespace std;

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.

Characterizing Numbers in C++


Below is another combined guide to characterizing different kinds of
numbers in C++

#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

Math Operations in C++


Notwithstanding the different functions you can make, C++ likewise
incorporates some valuable functions you can utilize. These functions are
accessible in standard C and C++ libraries and referred to as built-in
functions. These are functions that can be remembered for your program and
afterward use.
C++ has a rich arrangement of mathematical tasks, which can be performed
on different numbers. Following list records down some valuable implicit
mathematical functions accessible in C++.

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

6: double hypot(double, double): If you give the function “the length of


different sides of a right triangle,” it gives you the length of the hypotenuse.

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.

Following is a straightforward guide to show a few of the mathematical


activities −

#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.

/* This is a sample of function. in which we can have


* more than one function with an identical name but distinct
* sequence, type or number of arguments
*/
#include <iostream>
using namespace std;

int sum(int, int);


float sum(float, float);
float sum(int, float);
int main(){
int num1, num2, x;
float num3, num4, y;
cout<<"Enter two integer numbers: ";
cin>>num1>>num2;
//This will call the first function
cout<<"Yield: "<<sum(num1, num2)<< endl;

cout<<"Enter two float numbers: ";


cin>>num3>>num4;
//This will call the second function
cout<<"Yield: " <<sum(num3, num4)<< endl;

cout<<"Enter one int and one float number: ";


cin>>x>>y;
//This will call the third function
cout<<"Yield: " <<sum(x, y)<< endl;
return 0;
}
int sum(int i, int j){
return i+j;
}
float sum(float i, float j){
return i+j;
}
/* Recall that the sum of a float and int and is a float
* hence the data type returned in this function is a float
*/
float sum(int i, float j){
return i+j;
}

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

Addition Utilizing Class and Function

#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;

/* The function asks users to enter two values.


* The numbers inputted by users are stored in
* the variables numX and numY so that they can be summed
* up later.
*/
void ask(){
cout<<"Enter first number: ";
cin>>numX;
cout<<"Enter second number: ";
cin>>numY;
}

/* This function adds the numbers that are passed


* to it through arguments. I have used parameter names
* as n1 and n2, but you can choose any parameter name.
* This function returns the result.
*/
int sum(int n1, int n2){
return n1+n2;
}

//This function displays the addition result


void show(){
cout<<sum(numX, numY);
}
};
int main(){
//Creating object of class Add
Add obj;

//asking for input


obj.ask();

//Displaying the output


obj.show();
return 0;
}

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.

Complex Numbers in C++


The complex library actualizes the complex class to contain complex
numbers in cartesian structure and several functions and overloads to work
with them.
real() – It gives the real part of the complex number.
imag() – It gives the imaginary part of the complex number.

/Program delineating the utilization of re() and


/the function imag()

#include <iostream>

// for std::complex, std::imag, std::real


#include <complex>

using the namespace std;


// driver function
int main()
{
// defines the complex number: (13 + 5i)

std::complex<double> mycomplex(13.0, 5.0);

// prints the real part with the real function

cout << "Real part: " << real(mycomplex) << endl;

cout << "Imaginary part: " << imag(mycomplex) << endl;

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.

/Program representing the utilization of abs() and arg()

#include <iostream>

// for std::complex, std::arg, std::abs


#include <complex>

using a namespace std;

// the driver function is used

int main ()
{

// to define the complex number: (4.0+3.0i)

std::complex<double> complexval(4.0, 3.0);

// To print the absolute value of the complex number

cout << "The absolute value of " << complexval<< " is: ";

cout << abs(complexval) << endl;

// To print the argument of the complex number

cout << "The argument of " << complexval<< " is: ";

cout << arg(complexval) << endl;


return 0;
}

Output:
The argument of (4,3) is: 0.927295
The absolute value of (4,3) is: 5

polar() – It develops a complex number from magnitude and phase angle.


real = magnitude*cosine(phase angle)
imaginary = magnitude*sine(phase angle)
/Program showing the utilization of a polar() function

#include <iostream>

// std::complexval, std::polar
#include <complexval>

using namespace std;

// driver function

int main ()
{
cout << 'The complexval with a magnitude of ' << 2.0;

cout << ' and phase angle is ' << 0.5;

// 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)

norm() – It is utilized to discover the norm(absolute value) of the random


number. If z = x + iy is a random number with real part x and imaginary part
y, the complex conjugate of z is characterized as z'(z bar) = x – iy, and the
absolute value, additionally called the norm, of z, is characterized as :

complex-2

/guide to outlining the utilization of norm()

#include <iostream>

// for std::complex, std::norm


#include <complex>

using namespace std;

// driver function

int main ()
{

// initializing the complex: (4.0+3.0i)


std::complex<double> complexval (4.0, 3.0);

// use of norm()

cout << "The norm of " << complexval << " is "

<< norm(complexval) <<endl;

return 0;
}

Yield:
The norm of (4,3) is 25.

conj() – It gives the conjugate of a complex number. The conjugate


of a complex number, for example, (real,imag) is (real,- imag).

/Illustrating the utilization of conj()

#include <iostream>
using namespace std;

// std::complex, std::conj
#include <complex>

// driver program

int main ()
{

std::complex<double> complexval (10.0,2.0);


cout << "The conjugate of " << complexval << " is: ";

// use of conj()
cout << conj(complexval) << endl;

return 0;
}

Yield:
The conjugate of the operands (10,2) is (10,-2)

proj() – It gives the projection of z(complex number) onto the


Riemann circle. The projection of z is z, aside from complex, vast
qualities, which are mapped to the complex value with a real part of
INFINITY and an imaginary part of 0.0 or - 0.0 (where bolstered),
contingent upon the indication of the imaginary part of z.

/Illustrating the utilization of proj()

#include <iostream>

using namespace std;

// For std::complex, std::proj


#include <complex>

// driver program

int main()
{
std::complex<double> c1(1, 2);
cout << "proj" << c1 << " = " << proj(c1) << endl;

std::complex<double> c2(INFINITY, -1);

cout << "proj" << c2 << " = " << proj(c2) << endl;

std::complex<double> c3(0, -INFINITY);

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.

/Illustrating the use of the sqrt() function

#include <iostream>

using a namespace std;

// For std::complexval, stdc::sqrt


#include <complexval>
// driver program
int main()
{

// use of the sqrt() function

cout << "The square root of -25 is "

<< sqrt(std::complexval<double>(-25, 0)) << endl

<< "The square root of (-25,-0), the other side of the operation, is "

<< sqrt(std::complexval<double>(-25, -0.0)) << endl;


}

Yield:
The square root of -25 is (0,5)
The square root of (-25,-0), the other side of the operation, is (0,-5)

log() – It is utilized to give the log of the complex number.

/CPP program to represent the utilization of log()

#include <iostream>

// for std::complex, std::log


#include <complex>

using namespace std;

// driver program
int main ()
{

// initializing the complex: (-1.0+2.0i)

complex<double> mycomplex (-1.0, 2.0);

// use of log()

cout << "The log of the" << complexval << " is "

<< log(complexval) <<endl;

return 0;
}

Yield:
The log of (-1,2) is (0,0.3010)

cos() – It figures and computes the complex cosine of a complex


value z. Numerical meaning of the cosine is

cos z = (e^(iz) + e^(- iz))/2

sin() – It processes the complex sine of a complex value z.


Mathematical meaning of the cosine is

sin z = (e^(iz) - e^(- iz))/2i

tan() – It registers the complex tangent of a complex value z.


Numerical meaning of the tangent is
tan z = i(e^(- iz) - e^(iz))/(e^(- iz) + e^iz)

/guide to represent the utilization of tan(), cos() and sin()

#include <iostream>

// CPP program to illustrate


// std::complex, std::tan, std::cos, std::sin
#include <complex>

using namespace std;

// driver program
int main ()
{

// initializing the complex: (-1.0+0.0i)

complex<double> mycomplex (0.0, 1.0);

// use of cos()

cout << "Cos of " << mycomplex << " is given as "

<< cos(mycomplex) <<endl;


// use of sin()
cout << "Sin of " << mycomplex << " is given as "

<< sin(mycomplex) <<endl;

// use of tan()
cout << "Tan of " << mycomplex << " is given as "

<< tan(mycomplex) <<endl;

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() – It finds the hyperbolic cosine of the given complex.


Numeric function of hyperbolic cosine is:

cosh(z)=(e^z+e^(- z))/2

sinh() – This function is used in determining the hyperbolic sine of


the given complex. Numeric function of hyperbolic sine is:

sinh(z)=(e^z-e^(- z))/2.

tanh() – This function is used to determine the hyperbolic tangent of


the given complex. Mathematical function of hyperbolic tan is:

tanh(z)=(e^(2z)- 1)/(e^(2z)+1)

/CPP program to delineate the

/utilization of tanh(),cosh(),sinh()

#include <iostream>
#include <cmath>
// For the std::complex
#include <complex>

using a namespace std;

// The driver program tends to

int main()
{

// behave similarly to real cosh, sinh, tanh on a real line;

// x = i + 0j

complexval<double> x(1, 0);

cout << "sinh" << x << " = " << sinh(x)

<< " (sinh(1) = " << sinh(1) << ")"<<endl;

cout << "tanh" << x << " = " << tanh(x)

<< " (tanh(1) = " << tanh(1) << ")"<<endl;

cout << "cosh" << x << " = " << cosh(x)

<< " (cosh(1) = " << cosh(1) << ")"<<endl;


// It behaves similarly to real tangent, sine, and cosine along the imaginary
line; x2=0+1j

complex<double> z2(0, 1);


cout << "cosh" << x2 << " = " << cosh(x2)

<< " ( cos(1) = " << cos(1) << ")"<<endl;

cout << "sinh" << x2 << " = " << sinh(x2)

<< " ( sin(1) = " << sin(1) << ")"<<endl;

cout << "tanh" << x2 << " = " << tanh(x2)

<< " ( tan(1) = " << tan(1) << ")"<<endl;


}
Yield:
sinh(2.000000, 0.000000) = (3.626860, 0.000000) (sinh(2) = 3.626860)
tanh(2.000000,0.000000) = (0.964628, 0.000000) (tanh(2) = 0.964628)
cosh(2.000000, 0.000000) = (3.762196, 0.000000) (cosh(2) = 3.762196)
cosh(0.000000, 2.000000) = (1.000000, 3.762196) ( cos(2) = 0.999847)
sinh(0.000000, 2.000000) = (0.000000, 3.626860) ( sin(2) = 0.841471)
tanh(0.000000,2.000000) = (0.000000, 0.964628) ( tan(2) = 0.034921)

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++

An array in C++ is an assortment of things put away at adjacent memory


areas, and components can be gotten to randomly utilizing lists of an array.
They are utilized to store comparative sort of components, as in the data type,
must be the same for all components. They can be utilized to store an
assortment of crude data types, for example, int, glide, double, char, and so
on of a specific kind. What's more, in C++, an array is capable of storing
inferred data types, for example, the structures, pointers, etcetera.

Below is the graphic portrayal of an array:


Arrays
For what reason do we need arrays?
We can utilize ordinary variables (v1, v2, v3,..) when we have few objects;
however, if we need to store an enormous number of instances, it gets hard to
oversee them with typical variables. An exhibit can speak to numerous
examples in a single variable.

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.

Array declaration by indicating the size

// Array declaration through size specification

int arr1[5];

// With recent versions of C and C++, it is possible


// to declare an array of a user-specified size
int n = 5;
int arr2[n];

Array declaration by element initialization


// Array declaration by the initialization of elements

int arr[] = { 5, 10, 15, 20, 25 }

// Compiler creates an array of size 5.


// above is same as "int arr[4] = {5, 10, 15, 20, 25}"
Array declaration by size specification and element initialization
// Array declaration by size specification and element
// initialization

int arr[n] = { 5, 10, 15, 20, 25 }

// The compiler creates an array of size 5, initializes the first


// 4 elements as the user specified and two elements are rested as 0.
// the sample above is similar to this: "int arr[] = { 5, 10, 15, 20, 0, 0}"

Perks of an Array in C++


* Arbitrary access of components utilizing array file.
* Utilization of less line of code as it makes a separate array of various
components.
* Simple access to every one of the components.
* Traversal through the array turns out to be simply utilizing a single loop.
* Arranging turns out to be simple as it tends to be practiced by composing
less line of code.
Hindrances of an Array in C++
* Enables a fixed number of components to be entered, which is chosen at the
hour of an assertion. In contrast to a connected list, an array in C isn't
dynamic.
* Inclusion and erasure of components can be exorbitant since the
components should have been overseen as per the new memory portion.
Realities about Array in C/C++

Getting to Array Elements:


Array components are gotten to by utilizing an integer file. Array file begins
with 0 and goes till the size of array minus 1.

Model:
#include <iostream>

using namespace std;

int main()
{

int arr[5];

arr[0] = 5;

arr[2] = -10;

// this is same as arr[1] = 2


arr[3 / 2] = 2;

arr[3] = arr[0];

cout << arr[0] << " " << arr[1]

<< " " << 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>

using namespace std;

int main()
{

int arr[2];

cout << arr[3] << " ";

cout << arr[-2] << " ";

return 0;
}
Output:
2008101287 4195777

In C, it isn't compiler error to initiate an array with a greater number of


components than the predetermined size. For instance, the underneath
program compiles fine as follows:

#include <stdio.h>

int main()
{

// Array declaration through initialization with multiple

// elements than the given size.

int arr[2] = { 5, 10, 15, 20, 25 };

return 0;
}
Warning:

prog.c: In function "main":


prog.c:7:24: warning: multiple elements in the array initializer
int arr[2] = { 5, 10, 15, 20, 25};
^
prog.c:7:24: note: (near initialization for "arr")
prog.c:7:28: warning: multiple elements in array initializer
int arr[2] = { 5, 10, 15, 20, 25 };
^
prog.c:7:28: note: (near initialization for "arr")
prog.c:7:32: warning: multiple elements in array initializer
int arr[2] = { 5, 10, 15, 20, 25 };
^
prog.c:7:32: note: (near initialization for "arr")

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]'".

The components are put away at adjoining memory areas.

Model:
// A C++ sample program to show that the elements in an array
// can be stored in contiguous locations

#include <iostream>

using a namespace std;

int main()
{

// Using an array containing 10 integers. If arr[4] is stored in an


// address x, then arr[6] is stored in x + sizeof(int)
// and arr[8] is stored in x + sizeof(int) + sizeof(int)
// among others.
int arr[10], a;
cout << "The size of the integer in this compiler is given as" << sizeof(int)
<< "\n";
for (a = 0; a < 5; a++)
// Using '&' before the variable name, gives the
// address of the variable.
cout << "Address arr[" << a << "] is " <<&arr[a] << "\n";
return 0;
}
Output:
The size of the integer in this compiler is given as 4
Address arr[4] is 0x7ffd636b4260
Address arr[6] is 0x7ffd636b4264
Address arr[8] is 0x7ffd636b4268
Address arr[10] is 0x7ffd636b426c
Address arr[12] is 0x7ffd636b4270
Arrays versus Pointers
Arrays and pointers are two unique things (we can check by applying sizeof).
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).

What is a Vector in C++?


A vector in C++ is a class in STL that speaks to an array. The upsides of
vector over typical exhibits are,
* We needn't bother with pass size as an additional parameter when we
pronounce a vector, that is, vectors bolster dynamic sizes (we don't need to at
first indicate the size of a vector). We can likewise resize a vector.
* Vectors have numerous in-constructed work like evacuating a component,
and so forth.

Vectors in C++ STL


Vectors are the same as unique arrays with the capacity to resize itself
consequently when an element is embedded or erased, with their storage
being dealt with naturally by the containing. Vector components are set in
adjacent storage with the goal that they can be gotten to and navigated
utilizing iterators. In vectors, information is embedded toward the end.
Embeddings toward the end take differential time, as now and again, there
might be a need to expand the array. Evacuating the last component takes just
some time because no resizing occurs. Embeddings and deleting toward the
start or in the center are direct in time.
Certain functions related to the vector are:
Iterators

begin() – Returns an iterator indicating the main component in the


vector.
end() – Returns an iterator indicating the hypothetical component
that pursues the last component in the vector.
rbegin() – Returns a reverse iterator indicating the last component in
the vector (reverse beginning). It moves from last to first component.
rend() – Returns a reverse iterator indicating the hypothetical
component going before the main component in the vector
(considered as a reverse end).
cbegin() – Returns a constant iterator indicating the primary
component in the vector.
cend() – Returns a constant iterator indicating the hypothetical
component that pursues the last component in the vector.
crbegin() – Returns a constant reverse iterator indicating the last
component in the vector (reverse beginning). It moves from last to
first component.
crend() – Returns a constant reverse iterator indicating the
hypothetical component going before the main component in the
vector (considered as a reverse end).

/C++ program to show


// iterators used with vectors
#include <iostream>
#include <vector>

using a namespace std;

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: ";

for (auto i = x1.cbegin(); i != x1.cend(); ++i)


cout << *i << " ";
cout << "\nThe yieldt of rbegin and rend is: ";
for (auto ir = x1.rbegin(); ir != x1.rend(); ++ir)
cout << *ir << " ";
cout << "\nThe yield of crbegin and crend is: ";

for (auto ir = x1.crbegin(); ir != x1.crend(); ++ir)

cout << *ir << " ";

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

size() – This function is used to return the number of components in


a vector.
max_size() – Returns the most extreme number of components that
the vector can hold.
capacity() – Returns the size of the extra room as of now allotted to
the vector communicated as the number of components.
resize(n) – Resizes the compartment so it contains 'n' components.
empty() – Returns whether the compartment is unfilled.
shrink_to_fit() – Reduces the limit of the compartment to
accommodate its size and pulverizes all components past the limit.
reserve() – Requests that the vector limit is in any event enough to
contain n components.

/C++ program to delineate the

/limit work in vectors

#include <iostream>
#include <vector>

using a namespace std;

int main()
{

vector<int> x1;

for (int i = 1; i <= 5; i++)

g1.push_back(i);

cout << "Size : " << x1.size();


cout << "\nCapacity : " << x1.capacity();
cout << "\nMax_Size : " << x1.max_size();

// resizes the vector size to 4


x1.resize(4);

// prints the vector size after resize()

cout << "\nSize : " << x1.size();

// to verify whether or not the vector is empty

if (x1.empty() == false)

cout << "\nVector is not empty";

else

cout << "\nVector is empty";


// Shrinks the vector

x1.shrink_to_fit();

cout << "\nVector elements include: ";

for (auto it = x1.begin(); it != x1.end(); it++)

cout << *it << " ";

return 0;
}
Output:
Size : 5
Capacity : 8
Max_Size : 4611686018427387903
Size : 4
Vector is not empty

Component access:

reference operator [x] – This operator is used in returning a reference


to the component at a position 'x' in a vector.
at(x) – This operator is used in returning a reference to the
component at a position 'x' in a vector.
front() – Returns a reference to the first component in the vector.
back() – Returns a reference to the last component in the vector.
data() – Returns an immediate pointer to the memory array utilized
internally by the vector to store its possessed components.

/C++ program to delineate the

/component accessor in vector

#include <bits/stdc++.h>

using namespace std;

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];

cout << "\nat : g1.at(4) = " << g1.at(4);

cout << "\nfront() : g1.front() = " << g1.front();

cout << "\nback() : g1.back() = " << g1.back();

// pointer to the first element

int* pos = g1.data();


cout << "\nThe first element is " << *pos;

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:

allocate() – It doles out new value to the vector components by


supplanting old ones.
push_back() – It drives the components into a vector from the back.
pop_back() – It is utilized to pop or expel components from a vector
from the back.
insert() – It embeds new components before the component at the
predefined position.
erase() – It is utilized to expel components from a holder from the
predefined position or range.
swap() – It is utilized to swap the contents of one vector with another
vector of the same kind. Sizes may contrast.
clear() – It is utilized to evacuate every one of the components of the
vector container.
emplace() – It broadens the container by embedding new component
at position.
emplace_back() – It is utilized to embed another component into the
vector compartment, the new component is added as far as possible
of the vector.

/C++ program to show the


/Modifiers in vector
#include <bits/stdc++.h>
#include <vector>

using namespace std;

int main()
{

// Assign vector

vector<int> v;

// fill the array with 25 five times5


v.assign(5, 25);

cout << "The vector elements are: ";

for (int x = 0; x < v.size(); i++)


cout << v[x] << " ";

// inserts 15 to the last position

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

cout << "\nThe vector elements are: ";

for (int x = 0; x < v.size(); x++)

cout << v[x] << " ";

// inserts 5 at the beginning

v.insert(v.begin(), 5);

cout << "\nThe first element is: " << v[0];


// removes the first element

v.erase(v.begin());

cout << "\nThe first element is: " << v[0];

// inserts at the beginning


v.emplace(v.begin(), 5);

cout << "\nThe first element is: " << v[0];

// Inserts 20 at the end

v.emplace_back(20);
n = v.size();

cout << "\nThe last element is: " << v[n - 1];

// erases the vector

v.clear();

cout << "\nVector size after erase(): " << v.size();

// two vectors to perform a swap

vector<int> v1, v2;

v1.push_back(1);
v1.push_back(2);

v2.push_back(3);

v2.push_back(4);

cout << "\n\nVector 1: ";

for (int x = 0; x < v1.size(); x++)


cout << v1[x] << " ";

cout << "\nVector 2: ";

for (int x = 0; x < v2.size(); x++)


cout << v2[x] << " ";

// Swaps v1 and v2

v1.swap(v2);

cout << "\nAfter Swap \nVector 1: ";

for (int x = 0; x < v1.size(); x++)

cout << v1[x] << " ";

cout << "\nVector 2: ";

for (int x = 0; x < v2.size(); x++)


cout << v2[i] << " ";
}
The output is as follows:
The vector elements are: 25 25 25 25 25
The last element is: 15
The vector elements are: 25 25 25 25 25
The first element is: 5
The first element is: 10
The first element is: 5
The last element is: 20
Vector size after erase(): 0

Vector 1: 1 2
Vector 2: 3 4
After Swap
Vector 1: 3 4
Vector 2: 1 2
All Vector Functions :

vector::begin() and vector::end()


vector rbegin() and rend()
vector::cbegin() and vector::cend()
vector::crend() and vector::crbegin()
vector::assign()
vector::at()
vector::back()
vector::capacity()
vector::clear()
vector::push_back()
vector::pop_back()
vector::empty()
vector::erase()

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.

std:: String versus Character Array


A character array is just a variety of characters that can be ended by an
invalid character. A string is a class that characterizes objects that can be
depicted as a stream of characters.
The size of the character array needs to designated statically; more memory
can’t be distributed at run time whenever required. Unused designated
memory is squandered in the event of a character array. If there should be an
occurrence of strings, memory is distributed progressively. More memory can
be distributed at run time on request. Since there is no pre-allocated memory,
no memory is squandered.
There is a danger of array decay in the event of a character array. As strings
are depicted as objects, no array decay happens.
Usage of character array is quicker than std:: string. Strings are slower when
contrasted with execution than character exhibit.
Character array does not offer a lot of inbuilt capacities to control strings.
String class characterizes various functionalities that permit complex tasks on
strings.
Activities on strings

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:

// C++ code to demonstrate the working of


// getline(), push_back() and pop_back()
#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
// Declaring string
string str;

// Taking string input using getline()


// "thisbook" in giving the output
getline(cin,str);

// Displaying the string


cout << 'The initial string is : ';
cout << str << endl;

// Using the push_back() function to insert a character


// into the end
// to push 's' in this case
str.push_back('s');

// 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

capacity():- This function restores the capacity apportioned to the


string, which can be equivalent to or more than the size of the string.
Extra space is designated with the goal that when the new characters
are added to the string, the activities should be possible effectively.
resize():- This function is used to alter the size of a string; the size
can be expanded or diminished.
length():- This function finds the length of the string.
shrink_to_fit():- This function diminishes the capacity of the string
and makes it equivalent to its size. This activity is valuable to spare
extra memory on the off chance that we are sure that no further
expansion of characters must be made.

Here is an example of how these work:


// C++ code to demonstrate the working of
// capacity(), resize() and shrink_to_fit()
#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
// Initializing string
string str = "thisbook is for all";

// Displaying string
cout << "The initial string is : ";
cout << str << endl;

// Resizing string using resize()


str.resize(13);

// Displaying string
cout << "The string after resize operation is : ";
cout << str << endl;

// Displaying capacity of string


cout << "The capacity of string is : ";
cout << str.capacity() << endl;
//Displaying length of the string
cout<<"The length of the string is :"<<str.length()<<endl;

// Decreasing the capacity of string


// using shrink_to_fit()
str.shrink_to_fit();

// Displaying string
cout << "The new capacity after shrinking is : ";
cout << str.capacity() << endl;

return 0;

Yield:

The initial string is: this book is for all


The string after resize operation is : thisbook
The capacity of the string is : 26
The length of the string is : 13
The new capacity after shrinking is : 13

Iterator Functions/Capacity

begin():- This capacity restores an iterator to start of the string.


end():- This capacity restores an iterator to end of the string.
rbegin():- This capacity restores an invert iterator pointing toward
the finish of string.
rend():- This capacity restores a turnaround iterator pointing at the
start of a string.
Here is an example of how these work:

// C++ code to demonstrate the working of


// begin(), end(), rbegin(), rend()
#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
// Initializing string`
string str = "thisbook";

// Declaring iterator
std::string::iterator it;

// Declaring reverse iterator


std::string::reverse_iterator it1;

// Displaying string
cout << "The string using forward iterators is : ";
for (it=str.begin(); it!=str.end(); it++)
cout << *it;
cout << endl;

// Displaying reverse string


cout << "The reverse string using reverse iterators is : ";
for (it1=str.rbegin(); it1!=str.rend(); it1++)
cout << *it1;
cout << endl;
return 0;

Yield:
The string using forward iterators is: thisbook
The reverse string using reverse iterators is: koobsiht
Manipulating Functions/Capacity

copy(“char array”, len, pos):- This capacity copies the substring in


target character array referenced in its arguments. It takes 3
arguments, target character array, length to be copied, and beginning
position in the string to begin copying.
swap():- This capacity swaps one string with another.

Here is an example of how these work:

// C++ code to demonstrate the working of


// copy() and swap()
#include<iostream>
#include<string> // for string class
using namespace std;
int main()
{
// Initializing 1st string
string str1 = "thisband is for all";

// Declaring 2nd string


string str2 = "thisband rocks";

// Declaring character array


char ch[80];

// using the copy() function to copy elements into char array


// copies "thisband"
str1.copy(ch,13,0);

// Diplaying char array


cout << "The new copied character array is : ";
cout << ch << endl << endl;

// Displaying strings before swapping


cout << "The 1st string before swapping is : ";
cout << str1 << endl;
cout << "The 2nd string before swapping is : ";
cout << str2 << endl;

// using swap() to swap string content


str1.swap(str2);

// Displaying strings after swapping


cout << "The 1st string after swapping is : ";
cout << str1 << endl;
cout << "The 2nd string after swapping is : ";
cout << str2 << endl;

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

String Class And Its Applications In C++


In C++ programming, strings are stored by one of the two different ways; C
style strings and String class (which this segment of the chapter discusses)

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.

// A sample program to show the various functions of string classes


#include <bits/stdc++.h>
using a namespace std;

int main()
{
// the different constructors of a string class
// initializing through raw strings
string str5("first string");

// initializing through other strings


string str6(str1);

// initializing through characters with a number of occurrences


strings str7(5, '#');

// initializing through a part of another string


string str8(str1, 6, 6); // from the 6th index (the second parameter)
// with 6 characters (the third parameter)

// initializing through parts of other strings : the iterator technique


string str9(str2.begin(), str2.begin() + 5);

cout << str5 << endl;


cout << str6 << endl;
cout << str7 << endl;
cout << str8 << endl;
cout << str9 << endl;

// the assignment operator


string str10 = str4;

// 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;

// a certain character can be accessed with the at /


// [] operator
char ch = str10.at(2); // Same as "ch = str10[2];"

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

char ch_f = str10.front(); // Same as "ch_f = str10[0];"


char ch_b = str10.back(); // Similar to below
// "ch_b = str10[str10.length() - 1];"

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);

// To append add the argument string at the end


str10.append(" extension");
// same as str10 += ' extension'
// a different version of append that appends a part of other
// strings
str8.append(str10, 0, 5); // at 0th position 5 character

cout << str10 << endl;


cout << str8 << endl;

// the find returns the index when a pattern is located.


// If the pattern does not exist, it returns the predefined
// constant npos which has a value of -1

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;

// the substr(x, y) function returns a substring of y length


// starting from the index at x
cout << str10.substr(7, 3) << endl;
// when a second argument isn't passed, the string until the end is
// considered to be a substring
cout << str10.substr(7) << endl;

// the function erase(x, y) clears out the y characters in the index x


str10.erase(7, 4);
cout << str10 << endl;

// the iterator version of erase is


str10.erase(str10.begin() + 5, str10.end() - 3);
cout << str10 << endl;

str10 = "This is a sample";


// the replace(x, y, str) function replaces y characters from the x index with
str
str10.replace(2, 7, "ese are test");

cout << 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

These are test models.


As found in the above code, we can get the length of the string by size() just
as length(); however, length() is favored in string operations. A string can be
concatenated to another string by += or by attach(). However, += is
marginally slower than affix() because each time + known as another string
(production of new buffer) is made, it restores what is overhead, especially if
there is an occurrence of many annex operations.

Applications
On premise of above string capacity some applications are composed
underneath :

// A sample program to demonstrate uses of some string function


#include <bits/stdc++.h>
using namespace std;

// this function returns floating point part of a number-string


string returnFloatingPart(string str)
{
int pos = str.find(".");
if (pos == string::npos)
return "";
else
return str.substr(pos + 1);
}

// This function checks whether a string contains all digit or not


bool containsOnlyDigit(string str)
{
int l = str.length();
for (int i = 0; i < l; i++)
{
if (str.at(i) < '0' || str.at(i) > '9')
return false;
}
// if we reach here all character are digits
return true;
}

// this function replaces all single space by %20


// Used in URLS
string replaceBlankWith20(string str)
{
string replaceby = "%20";
int n = 0;

// loop till all space are replaced


while ((n = str.find(" ", n)) != string::npos )
{
str.replace(n, 1, replaceby);
n += replaceby.length();
}
return str;
}

// driver function to check above methods


int main()
{
string fnum = "23.342";
cout << "Floating part is : " << returnFloatingPart(fnum)
<< endl;

string num = "3452";


if (containsOnlyDigit(num))
cout << "string contains only digit" << endl;
string urlex = "google com in";
cout << replaceBlankWith20(urlex) << endl;

return 0;
}
Yield :
Floating part is : 342
string contains only digit
google%20com%20in

String and Character Array


In C++, notwithstanding character array, there exists a comparable sort of
approach to actualize string that is utilizing string class, which is a piece of
C++ standard library. To execute string utilizing string class, we have to
include the header document. 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.

// A C++ program to show Character Strings


// and Arrays
#include<iostream>
#include<string>// for the string class
using a namespace std;
int main()
{
// The size ought to be predefined in the character array
char str[80] = "ThatBand";

// Size not predefined in string


string s("ThatBand");

// Printing character array and string


cout << str << endl;
cout << s << endl;

return 0;
}

The output is as follows:


ThatBand
ThatBand

Some Valuable String Functions


• compare(string_to_compare ) :- It is utilized to carry out a comparison of
two strings. It restores the distinction of the second string and first string in
the whole number.

// C++ program to demonstrate use of compare()


#include<iostream>
#include<string>
using namespace std;
int main()
{
string str("ThisBook");
string str1("ThisBook");

// Comparing strings using compare()


if ( str.compare(str1) == 0 )
cout << "All strings are equal";
else
cout << "All strings are unequal";
return 0;
}
Yield:
All strings are equal

• 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");

// find() returns position to first


// occurrence of substring "Book"
// Prints 4
cout << "First occurrence of \"Book\" starts from : ";
cout << str.find("Book") << endl;

// Prints position of first occurrence of


// any character of "reef" (Prints 2)
cout << "First occurrence of character from \"reef\" is at : ";
cout << str.find_first_of("reef") << endl;

// Prints position of last occurrence of


// any character of "reef" (Prints 16)
cout << "Last occurrence of character from \"reef\" is at : ";
cout << str.find_last_of("reef") << endl;

// rfind() returns position to last


// occurrence of substring "Book"
// Prints 14
cout << "Last occurrence of \"Book\" starts from : ";
cout << str.rfind("Boom") << endl;

return 0;

Yield:

First occurrence of Book” starts from : 4


First occurrence of character from “reef” is at : 2
Last occurrence of character from “reef” is at : 16
Last occurrence of “Book” starts from : 14

• insert(pos_to_begin,string_to_insert): This capacity embeds the given


substring in the string. It takes two arguments, first the situation from which
you need to embed the substring and second the substring.

// C++ program to demonstrate working of insert()


#include<iostream>
#include<string>
using namespace std;
int main()
{
string str("Bookfot");

// Printing the original string


cout << str << endl;
// Inserting "Book" at 8th index position
str.insert(8,"Book");

// Printing the modified string


// Prints “ThisBook"
cout << str << endl;

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.

// C++ program to demonstrate working of clear()


// and empty()
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str("GeeksforGeeks");
// clearing string
str.clear();

// Checking if string is empty


(str.empty()==1)?
cout << "String is empty" << endl:
cout << "String is not empty" << endl;

return 0;

}
Yield:
String is empty

Different Ways to Create an Array of Strings in C++


In C++, a string is a 1-D array of characters, and a variety of string in C is a
2D array of characters. This comes very helpful in C++. There are 3 ways by
which an Array of Strings in C++ can be made.

1. Utilizing 2D array(Both C and C++): This strategy helps rearrange,


contrast, and getting to characters haphazardly.

Language structure:

Char "Name" ["Number of Strings"]["MaxSize of String"]

Model:

Char color [4][10]


// Here 4 colors can be inserted
// with max String size of 10.
// C++ program to demonstrate array of strings using
// 2D character array
#include <bits/stdc++.h>
using namespace std;

int main()
{
// Initialize 2D array
char color[4][10] = { "Blue", "Red", "Orange",
"Yellow" };

// Printing Strings stored in 2D array


for (int i = 0; i < 4; i++)
cout << color[i] << "\n";

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:

String Name_ofString [number_of_string]

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.

3. Utilizing Vectors(Only C++): STL Container Vector can be utilized to


designate array powerfully.

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;

// Initialize vector with strings using push_back


// command
color.push_back("Blue");
color.push_back("Red");
color.push_back("Orange");
color.push_back("Yellow");

// Print Strings stored in Vector


for (int i = 0; i < color.size(); i++)
cout << color[i] << "\n";
}
Yield:
Blue
Red
Orange
Yellow

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. It involves an affirmation of both elevated level and low-level


language features.
2. To guarantee that a C++ code written on a particular platform can be
processed without errors and reused on any other supported
platform.
3. They represent the augmentation administrator in C.
Answers (Exercise 2):

1. Attempting to use a variable within a function outside the function.


2. Global variables
3. It is a type of variable that holds double-precision floating-point
value.
Answers (Exercise 3):

1. Structured Query Language.


2. It refers to a cross compiler that can run on any stage like Windows,
Linux, and Mac).
3. Databases are electronic frameworks which enable data to be
effectively gotten to, controlled, and refreshed.
Answers (Exercise 4):

1. An object is the occurrence of a class, while a class is


canormat/template that portrays the behaviors/states of an object.
2. Acentuation characters.
3. They are used to end individual statements.
Answers (Exercise 5):

1. These data types are inherent or predefined and can be used


legitimately by the client to state variables.
2. It is used with the inherent data types to adjust the length of data that
a specific data type can hold.
3. Boolean data types are used in the storing of boolean or consistent
qualities.
Answers (Exercise 6):

1. Literals are values allocated to all constant variables.


2. Constants are the variables or values in C++ programming language,
which can't be changed once they are characterized.
They are used to interact with the boolean datatypes.
Answers (Exercise 7):

1. Operators are symbols that follow up on variables or different


substances that are called operands and perform numerical or logical
activities to alter their values and produce results.
2. These types of operators in C++ work on bits of the operands given.
These operators include the arrow (- >) operator and dot operator (.)
Answers (Exercise 8):

1. An endless loop happens when the loop condition consistently


evaluates to true.
2. They help to exit a loop block without finishing it if you need to skip
an iteration.
3. It enables us to execute many statements repetitively.
Answers (Exercise 9):

1. The statement block after the ‘if’ condition is executed.


2. The initial statement bounces to different pieces of the code using
the ‘goto’ statement which makes a program progressively
unpredictable and ambiguous. However, more productive projects
can be done using the break and continue statements.
3. TheThe Switch statement enables us to test a condition and have
different alternatives to change the progression of execution.
Answers (Exercise 10):

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.

You might also like