Computer Programming - This Book Includes - SQL, Linux, Java, Python, C#, Arduino, C# For Intermediates, Arduino For Intermediates Learn Any Computer Language in One Day Step by Step (#2020 Version)
Computer Programming - This Book Includes - SQL, Linux, Java, Python, C#, Arduino, C# For Intermediates, Arduino For Intermediates Learn Any Computer Language in One Day Step by Step (#2020 Version)
Steve Tudor
Text Copyright
All rights reserved. No part of this guide may be reproduced in any form
without permission in writing from the publisher except in the case of brief
quotations embodied in critical articles or reviews.
Legal & Disclaimer
The information contained in this book and its contents is not designed to
replace or take the place of any form of medical or professional advice; and is
not meant to replace the need for independent medical, financial, legal or
other professional advice or services, as may be required. The content and
information in this book has been provided for educational and entertainment
purposes only.
The content and information contained in this book has been compiled from
sources deemed reliable, and it is accurate to the best of the Author's
knowledge, information and belief. However, the Author cannot guarantee its
accuracy and validity and cannot be held liable for any errors and/or
omissions. Further, changes are periodically made to this book as and when
needed. Where appropriate and/or necessary, you must consult a professional
(including but not limited to your doctor, attorney, financial advisor or such
other professional advisor) before using any of the suggested remedies,
techniques, or information in this book.
Upon using the contents and information contained in this book, you agree to
hold harmless the Author from and against any damages, costs, and expenses,
including any legal fees potentially resulting from the application of any of
the information provided by this book. This disclaimer applies to any loss,
damages or injury caused by the use and application, whether directly or
indirectly, of any advice or information presented, whether for breach of
contract, tort, negligence, personal injury, criminal intent, or under any other
cause of action.
You agree to accept all risks of using the information presented inside this
book.
You agree that by continuing to read this book, where appropriate and/or
necessary, you shall consult a professional (including but not limited to your
doctor, attorney, or financial advisor or such other advisor as needed) before
using any of the suggested remedies, techniques, or information in this book.
TABLE OF CONTENTS
CHAPTER 1. INTRODUCTION SQL
CHAPTER 2. DATABASE
CHAPTER 3. TABLES
CHAPTER 4. DATA
CHAPTER 5. SELECTING DATA
CHAPTER 6. VIEWS
CHAPTER 7. WHAT IS A VIEW, HOW TO CREATE A VIEW, HOW TO ALTER A VIEW,
DELETING A VIEW
CHAPTER 8. TRIGGERS
CHAPTER 9. VARIABLES AND STORED ROUTINES
CHAPTER 10. CONTROL FLOW TOOLS
CHAPTER 11. CURSORS
CHAPTER 12. COMMON BEGINNER MISTAKES AND HOW TO FIX THEM
CHAPTER 13. TIPS AND TRICKS OF SQL
CHAPTER 14. WORKBOOK
CHAPTER 15. SQL QUIZ
CONCLUSION
INTRODUCTION LINUX
CHAPTER 1: WHAT IS LINUX?
CHAPTER 2: LINUX EVERYDAY
CHAPTER 3 : SETTING UP
CHAPTER 4 : NAVIGATE LINUX
CHAPTER 5: ESSENTIAL COMMANDS
INTRODUCTION JAVA
CHAPTER 1 : GETTING READY
CHAPTER 2: JAVA BASICS
CHAPTER 3 : VARIABLES
CHAPTER 4 : JAVA OPERATORS
CHAPTER 5 : ARRAYS AND STRING
CHAPTER 6 : INTERACTIVE
CHAPTER 7: CONTROL FLOW STATEMENTS
CHAPTER 8 : LOOPS IN JAVA
CHAPTER 9: CLASSES AND OBJECTS IN JAVA
CHAPTER 10 : ENCAPSULATIONS IN JAVA
CHAPTER 11: POLYMORPHISM IN JAVA
CHAPTER 12: EXAMPLES WITH JAVA
CHAPTER 13: MOST SEARCHED BEGINNER’S QUESTIONS
CHAPTER 14: TIPS AND TRICKS
CHAPTER 15: WORKBOOK
CONCLUSION
INTRODUCTION C
CHAPTER 1 DATA TYPES
CHAPTER 2 DATA TYPE CONVERSION
CHAPTER 3 ARRAYS AND LOOPS
CHAPTER 4 OPERATORS
CHAPTER 5 CLASSES
CHAPTER 6 THE C LANGUAGE VARIABLES
CHAPTER 7 LOOPS IN C
CHAPTER 8 APPLICATION OF GRAPHICAL USER INTERFACE
CHAPTER 9 DECISION MAKING IN C
CHAPTER 10 CONSTANTS AND LITERALS
CHAPTER 11 COMMAND LINE ARGUMENTS
CHAPTER 12 EXTENSION METHODS
CHAPTER 13 NULLABLE TYPES
CONCLUSION
INTRODUCTION
CHAPTER 1 DATA TYPES
CHAPTER 2 DATA STRUCTURES, HANDLING AND FUNCTIONS
CHAPTER 3 HOW TO DEFINE YOUR CLASSES IN C#
CHAPTER 4 CREATING LOOPS IN C#
CHAPTER 5 VALUE TYPES AND REFERENCE TYPES
CHAPTER 6 ENUMERATIONS
CHAPTER 7 DECISION-MAKING
CHAPTER 8 ARRAYS
CHAPTER 9 CREATING OBJECTS AND MAKING THEM WORK
CONCLUSION
INTRODUCTION
CHAPTER 1 KEY TERMS IN UNDERSTANDING ARDUINO
CHAPTER 2 WORKING WITH USER-DEFINED FUNCTIONS
CHAPTER 3 THE SERIAL
CHAPTER 4 CONNECTING SWITCH
CHAPTER 5 TEMPERATURE SENSOR
CHAPTER 6 USING THE STREAM CLASS
CHAPTER 7 CALCULATED DIGITAL REPRESENTATIONS
CHAPTER 8 UNDERSTANDING THE ARDUINO FRAMEWORK
CHAPTER 9 LEARN THE IMPLEMENTATION OF ALGORITHMS
CHAPTER 10 TROUBLESHOOTING
CHAPTER 11 PROJECTS
CHAPTER 12 SPEND TIME THINKING OUTSIDE THE BOX (AND THE ARDUINO)
CHAPTER 13 TROUBLESHOOTING
CONCLUSION
SQL
Steve Tudor
Text Copyright
All rights reserved. No part of this guide may be reproduced in any form
without permission in writing from the publisher except in the case of brief
quotations embodied in critical articles or reviews.
Legal & Disclaimer
The information contained in this book and its contents is not designed to
replace or take the place of any form of medical or professional advice; and is
not meant to replace the need for independent medical, financial, legal or
other professional advice or services, as may be required. The content and
information in this book has been provided for educational and entertainment
purposes only.
The content and information contained in this book has been compiled from
sources deemed reliable, and it is accurate to the best of the Author's
knowledge, information and belief. However, the Author cannot guarantee its
accuracy and validity and cannot be held liable for any errors and/or
omissions. Further, changes are periodically made to this book as and when
needed. Where appropriate and/or necessary, you must consult a professional
(including but not limited to your doctor, attorney, financial advisor or such
other professional advisor) before using any of the suggested remedies,
techniques, or information in this book.
Upon using the contents and information contained in this book, you agree to
hold harmless the Author from and against any damages, costs, and expenses,
including any legal fees potentially resulting from the application of any of
the information provided by this book. This disclaimer applies to any loss,
damages or injury caused by the use and application, whether directly or
indirectly, of any advice or information presented, whether for breach of
contract, tort, negligence, personal injury, criminal intent, or under any other
cause of action.
You agree to accept all risks of using the information presented inside this
book.
You agree that by continuing to read this book, where appropriate and/or
necessary, you shall consult a professional (including but not limited to your
doctor, attorney, or financial advisor or such other advisor as needed) before
using any of the suggested remedies, techniques, or information in this book.
Chapter 1. INTRODUCTION
If you are interested in learning a new coding language, there are a lot of
different options that you can choose from, and it really depends on what you
are looking for and what you want to do with them. Some of these languages
are good for helping you to create a good website. Some are good for creating
a smartphone application or for working on your own game to share with
others. And then you can also choose a coding language that is like SQL,
which are meant to help businesses stay organized and keep track of their
information without all the challenges that can come with this.
a. Introduction to SQL
It is best to start at the beginning. SQL is a programming language that stands
for ‘Structured Query Language,’ and it is a simple language to learn
considering it will allow interaction to occur between the different databases
that are in the same system. This database system first came out in the 70s,
but when IBM came out with its own prototype of this programming
language, then it really started to see a growth in popularity and the business
world started to take notice.
The version of SQL that was originally used by IBM, known back then as
ORACLE, was so successful that the team behind it eventually left IBM and
became its own company. ORACLE, thanks to how it can work with SQL, is
still one of the leaders in programming languages and it is always changing
so that it can keep up with everything that is needed in the programming and
database management world.
The SQL is a set of instructions that you can use to interact with your
relational database. While there are a lot of languages that you can use to do
this, SQL is the only language that most databases can understand. Whenever
you are ready to interact with one of these databases, the software can go in
and translate the commands that you are given, whether you are giving them
in form entries or mouse clicks. These will be translated into SQL statements
that the database will already be able to interpret.
If you have ever worked with a software program that is database driven,
then it is likely that you have used some form of SQL in the past. It is likely
that you didn't even know that you were doing this though. For example,
there are a lot of dynamic web pages that are database driven. These will take
some user input from the forms and clicks that you are making and then will
use this information to compose a SQL query. This query will then go
through and retrieve the information from the database to perform the action,
such as switch over to a new page.
To illustrate how this works, think about a simple online catalog that allows
you to search. The search page will often contain a form that will just have a
text box. You can enter the name of the item that you would like to search
using the form and then you would simply need to click on the search button.
As soon as you click on the search button, the web server will go through and
search through the database to find anything related to that search term. It
will bring those back to create a new web page that will go along with your
specific request.
For those who have not spent that much time at all learning a programming
language and who would not consider themselves programmers, the
commands that you would use in SQL are not too hard to learn. Commands
in SQL are all designed with a syntax that fits in with the English language.
At first, this will seem really complicated, and you may be worried about
how much work it will be to get it set up. But when you start to work on a
few codes, you will find that it is not actually that hard to work with. Often,
just reading out the SQL statement will help you to figure out what the
command will do. Take a look at the code below:
How this works with your database
If you decide that SQL is the language that you will work on for managing
your database, you can take a look at the database. You will notice that when
you look at this, you are basically just looking at groups of information.
Some people will consider these to be organizational mechanisms that will be
used to store information that you, as the user, can look at later on, and it can
do this as effectively as possible. There are a ton of things that SQL can help
you with when it comes to managing your database, and you will see some
great results.
There are times when you are working on a project with your company, and
you may be working with some kind of database that is very similar to SQL,
and you may not even realize that you are doing this. For example, one
database that you commonly use is the phone book. This will contain a ton of
information about people in your area including their name, what business
they are in, their address, and their phone numbers. And all this information
is found in one place so you won't have to search all over to find it.
This is kind of how the SQL database works as well. It will do this by
looking through the information that you have available through your
company database. It will sort through that information so that you are better
able to find what you need the most without making a mess or wasting time.
Client and server technology
In the past, if you were working with a computer for your business, you were
most likely using a mainframe computer. What this means is that the
machines were able to hold onto a large system, and this system would be
good at storing all the information that you need and for processing options.
The user would be able to get onto these computers and interact with the
mainframe, which in this case would be a ‘dumb’ terminal or one that is not
able to interact all on its own. To get the information to show up the correct
function, the dumb terminal would need to rely on all the information that is
inside the computer, such as the memory, processor, and storage.
Now, these systems were able to work, and they got the job done for a very
long time. If your company uses these and this is what you are most
comfortable with using, it does get the work done. But there are some options
on the market that will do a better job. These options can be found in the
client-server system.
These systems will use some different processes to help you to get the results
that are needed. With this one, the main computer that you are using, which
would be called the ‘server,’ will be accessible to any user who is on the
network. Now, these users must have the right credentials to do this, which
helps to keep the system safe and secure. But if the user has the right
information and is on your network, they can reach the information without a
lot of trouble and barely any effort. The user can get the server from other
servers or from their desktop computer, and the user will then be known as
the ‘client’ so that the client and server are easily able to interact through this
database.
How to work with databases that are online
There are a lot of business owners who will find that the client and server
technology is the one that works for them. This system is great for many
companies, but there are some things that you will need to add or take away
at times because of how technology has been changing lately. There are some
companies that like the idea that their database will do better with the internet
so that they can work on this database anywhere they are located, whether
they are at home or at the office. There are even times when a customer will
have an account with the company, and they will need to be able to access the
database online as well. For example, if you have an account with Amazon,
you are a part of their database, and you can gain access to certain parts
through this.
As the trend continues for companies to move online, it is more common to
see that databases are moving online as well and that you must have a
website and a good web browser so that the customer can come in and check
them out. You can always add in usernames and passwords to make it more
secure and to ensure that only the right user can gain access to their
information. This is a great idea to help protect personal and payment
information of your customers. Most companies will require that their users
pick out security credentials to get on the account, but they will offer the
account for free.
Of course, this is a system that is pretty easy to work with, but there will be a
number of things going on behind the scenes to make sure that the program
will work properly. The customer can simply go onto the system and check
the information with ease, but there will be a lot of work for the server to do
to make sure that the information is showing up on the screen in the right
way, and to ensure that the user will have a good experience and actually see
their own account information on the screen.
For example, you may be able to see that the web browser that you are using
uses SQL or a program that is similar to it, to figure out the user that your
data is hoping to see. The SQL system will be used to reach your database, as
soon as the customer can put in what they are looking for. The SQL system,
will see this query. And then bring back information on the website that will
show up on the web browser, and if the system is working properly, the right
information will show up on the page.
Why is SQL so great?
The various types of database management systems that you can work with, it
is time to discuss why you would want to choose SQL over some of the other
options that are out there. You not only have the option of working with other
databases but also with other coding languages, and there are benefits to
choosing each one. So, why would you want to work with SQL in particular?
Some of the great benefits that you can get from using SQL as your database
management system includes:
Incredibly fast
If you would like to pick out a management system that can sort through the
information quickly and will get the results back in no time, then SQL is one
of the best programs to use for this. You will be surprised at how much
information you can get back, and how quickly it will come back to you. In
fact, out of all the options, this is the most efficient one that you can go with.
Well defined standards
The database that comes with SQL is one that has been working well for a
long time. In addition, it has been able to develop some good standards that
ensure the database is strong and works the way that you want. Some of the
other databases that you may want to work with will miss out on these
standards, and this can be frustrating when you use them.
You do not need a lot of coding
If you are looking into the SQL database, you do not need to be an expert in
coding to get the work done. We will take a look at a few codes that can help,
but even a beginner will get these down and do well when working in SQL.
Drop index
Drop view
Create index
Alter index
Alter table
Drop table
Create table
Create synonym
Grand
Alter password
Revoke
Set transaction
This command is the one that you can use any time that you are trying to take
the transactions in your database and give them names. You will often use
this one whenever you are trying to label things for a bit more organization.
All six of these types are going to be important based on the results that you
would like to get out of your search. Each of these will be explored a bit more
as we go through this guidebook so that you understand better how to use
them, when to use them, and how to divide up the information in the proper
way to avoid issues and to keep your database nice and organized with the
help of the SQL language.
You can get it easily and for free from MySQL website, or you can choose to
pay for a commercial release which comes with additional functionality.
MySQL runs on different platforms which include Windows, Mac OS X, and
Linux. If it is possible, find and download it on your computer if you have a
supporting platform. Some web hosting services provide it as their
implementation as part of their package though, and each comes with a
different interface to connect you to the database.
If you are using it as part of a website or application, those people that will
visit the site will not have to download any additional software in order to use
the features of MySQL.
Its performance
MySQL is written in C and C++, and it uses the kernel thread. This allows for
multi-threading so as to take advantage of the many CPUs if they are
available. It uses thread-based memory allocation which is joined by
optimized nested-loop so as to improve its speed.
It uses hash tables as temporary tables whenever you are executing your
queries. It uses SQL functions in an optimized class library in order to
improve speed and reduce the need for accessing memory whenever you are
querying tables in a database.
MySQL databases
With MySQL, you can add, access, modify and also delete any data that is
stored within the database of a MySQL server.
The only limitation will be on the number of tables you can create, and all
this depends on the file system.
If you have large MySQL databases, you can partition them so as to improve
performance and management.
When you are querying, you are free to include tables from different
databases on the same query.
MySQL Tables
There is a large amount of data that you can create with MySQL. You can
create about 4,096 columns and store as many records as you want with no
limitation at all whenever you are designing MySQL tables.
Each field can contain an assorted range of data. You can always fix the
length of a certain field set primary and index keys, require that they have
values and even increment numbers automatically.
SQL syntax is utilized to query tables. Use functions such as select, insert,
update, show, join, and delete, among other syntaxes that are allowed by SQL
languages.
mysql -u root –p
Now you have logged into the MySQL database, it is time for you to create a
new database. In the command given below, we are creating a database
named school :
The output shows that the database was created successfully. However, it will
be good for you to confirm whether or not the database was created. To do
this, use the SHOW command as shown below:
SHOW databases;
The above output shows that the school database was created successfully.
The above command returns the list of databases you have in your system.
The above output shows an error because the database already exists. To
avoid this error, we can use the optional clause IF NOT EXISTS. This is
showed below:
USE school;
After running the above command, the school database will receive all the
commands you execute.
RENAME Database
Sometimes, you may need changing the name of a database. This is after you
realize that the name you have given to the database is not much relevant to
it. You may also need giving the database a database name. This can be done
using the SQL RENAME DATABASE command.
Let us rename the database named movies by giving it the name movies_db.
This means we run the following command:
TO DISK = 'file_path';
The database_name parameter denotes the name of the database you need to
back up. The file_path parameter denotes the file leading to the directory
where you need to back up your database. The above command should be
done when you need to back up the database from the beginning.
However, you can use the differential command if you need to create a
differential backup. When you do this, the backup will only be created from
the time you did your last full backup of the database. To do this, you must
change the command to:
If you need to create a differential backup of the database, just run the
following command:
Create tables
The following are the simple steps:
The name of your table must not be easy to guess by anyone. You can do this
by including your initials and your birthdate. If your name is Henry Sheldon,
and your birthdate is October 20, 1964, you can add that information to the
name of your table.
Let’s say you want your table to be about the traffic sources in your website,
you can name the table“traffic_hs2064”
Take note that all SQL statements must end with a semicolon (;). All the data
variables must be enclosed with quotation marks (“ “), as well.
Example: CREATE TABLE traffic_hs2064
Step #3– Add an open parenthesis in the next line
The parenthesis will indicate the introduction of the columns you want to
create.
Example: CREATE TABLE “table_name”
(
Let’s apply this step to our specific example.
Example: CREATE TABLE traffic_hs2064
(
In our example, the focus of the table is on the traffic sources of your
website. Hence, you can name the first column“country”.
Example: CREATE TABLE traffic_hs2064
(country
Take note:
In summary, creating a table using a SQL statement will start with the
CREATE TABLE, then the “table name”, then an open parenthesis, then the
“column names”, the “data type”, (add a comma after every column), then
add any “CONSTRAINTS”.
Deleting Tables
Deleting tables, rows or columns from your database is easy by using
appropriate SQL statements. This is one of the commands that you must
know to be able to optimize your introductory lessons to SQL.
Make sure you have selected the proper table_name. Using our first sample
example from the previous chapter, this is how your SQL statement would
appear:
Example: DELETE from traffic_hs2064
Step #3–Indicate the specific column or row by adding“where”
If you don’t indicate the“where” all your files would be deleted, so ensure
that your statement is complete.
Example: DELETE FROM ‘table_name”
WHERE “column_name”
Hence, if you want to delete the entire table, simply choose:
DELETE FROM “table_name”;
Using our previous example from chapter 1, this is how your SQL statement
would appear:
Example: DELETE FROM traffic_hs2064
where time = (10)
Deleting the wrong tables from your database can cause problems, so,
ascertain that you have entered the correct SQL statements.
Inserting Data into a Table
You can insert a new data into an existing table through the following steps.
(“column_name”,. . . “column_name”
Using our sample table, you can come up with this SQL statement:
Example: INSERT INTO“traffic_hs2064”
(country, keyword. time)
values (‘America’,‘marketing’, 10);
You can insert more data safely without affecting the other tables. Just make
sure you’re using the correct SQL commands or statements.
Dropping a Table
You can drop or delete a table with a few strokes on your keyboard. But
before you decide to drop or delete a table, think about the extra time you
may spend restoring it back, if you happen to need it later on. So, be careful
with this command.
Dropping a table
Dropping a table is different from deleting the records/data in the table. When
you drop a table, you are deleting the table definition plus the records/data in
the table.
Example: DROP TABLE “table_name”
Using our table, the SQL statement would read like this.
Example: DROP TABLE traffic_hs2064;
Traffic_hs2064
If your base table is the table above, and you want to add another column
labeled City, you can create your SQL query this way:
You can also ALTER a table to ADD a constraint such as, NOT NULL.
You can also ALTER TABLE to DROP COLUMNS such as, the example
below:
Using the second table with this SQL query, the resulting table will be this:
Traffic_hs2064
Country Searchword Post City
America perfect Matchmaker NULL
Italy partner NatureTripping NULL
Sweden mate Fiction NULL
In addition to these uses, the ALTER TABLE can also be used with the
DROP CONSTRAINT like the example below.
Example: ALTER TABLE Traffic_hs2064
DROP CONSTRAINT uc_City;
NOT NULL
This constraint indicates that the NOT NULL values should not be present in
the columns of a stored table.
CHECK
This will ensure that all parameters have values that have met the criteria.
UNIQUE
This ascertains that all values in the columns are distinct or unique.
PRIMARY KEY
This indicates that the values in two or more columns are NOT NULL and
simultaneously UNIQUE.
FOREIGN KEY
This will ascertain that the values of columns from different tables match.
DEFAULT
There is a specified DEFAULT value for columns. This may appear as blanks
or appear as NULL.
Make sure you use these constraints properly to make the most out of your
SQL queries.
Chapter 4. DATA
The purpose of database systems is to store the data in tables. This data is
supplied by application programs running on top of the database. SQL has the
INSERT command that helps us enter data into a table for storage. The
command creates a new row in the table.
Note that we have specified the name of the table to insert data into, followed
by the names of columns in which we need to insert the data, then the data
values that are to be inserted. If you need to insert data into all the columns of
the table, there is no need for you to specify the column names. However, if
you need to insert into some columns while skipping the others, specify the
columns into which you need to insert data.
The following command shows how to insert data into all the columns of the
table:
The command ran successfully as shown above. This means that a row has
been created in the table.
However, you may need to insert data into some columns only. This is the
time you must specify the names of columns into which you need to insert
the data.
Suppose we don’t know the salary of the employee. We can insert data into
the other columns as shown below:
VALUES
(2, 'Mercy', 'Mercy32', 25);
The salary column has not been affected by the above command.
Constraints in MySQL
Constraints are required to restrict the values that are stored in a particular
field. You can limit the type of data entered into a table with the help of
constraints. Constraints can be applied at column level and at table level.
Constraints are defined when the table is created. The following are the
constraints available to you with MySQL:
Updating Data
Updating or changing data is one task you must learn and engage in as a
beginner SQL learner.
The key word for this SQL query is UPDATE. You can follow the steps
below.
Example: UPDATE“table_name”
SET“column_name1”= value1,“column_name2”=
value2;
Example: UPDATE“table_name”
SET“column_name1”= value1,“column_name2”=
value2
WHERE some _“column_name”= some_value;
Students
EXERCISE #1
Let’s say you want to update or change the student“Walker, Jean”with a new
address and city. How would you state your SQL query?
ANSWER:
Your SQL statement should appear this way:
Example: UPDATE students
SET Address =‘34 Staten Sq’, City =‘Laramie’
WHERE LastName =‘Walker’;
If you have submitted the correct SQL query, your resulting table will appear
like this:
Students
EXERCISE #2
You want to update the address of Cowell, Janine to 20 18 St. Laramie City.
th
ANSWER:
UPDATE students
SET Address =‘2018 St.’, City =‘Laramie’
th
If your SQL query is correct, your table will be updated according to your
recent input.
Pivoting Data
Pivoting data is converting your data, which are presented in rows, into
column presentations.
Through the use of PIVOT queries, you can manipulate the rows and
columns to present variations of the table that will help you in analyzing your
table. PIVOT can present a column into multiple columns. You have also the
option to use UNPIVOT query. UNPIVOT does the opposite of what PIVOT
does.
It is extremely useful in multidimensional reporting. You may need it in
generating your numerous reports.
How can you compose your PIVOT query?
ProductSales
Let’s say you want an output that will show the ProductName as the column
headings. This would be your PIVOT query:
Example #1:
With the PIVOT query above, your ProductSales table will now appear like
this:
#ProductNamesPIVOTResults
Deleting data
This action will delete all the records/data in your table but will not delete the
table itself. Hence, if your table structure is not removed, you can insert data
later on.
The complete steps in deleting data or record in a table are discussed in
another chapter.
DROPPING your table is easy as long as you can create the proper SQL.
Chapter 5. SELECTING DATA
Selecting rows and columns
Selecting a datum from your database can be done through the SELECT key.
You only have to specify the data you want to select.
Step #4–Add FROM and the table name, where the data will come from
You can enclose the identified columns and where conditions with open and
close square brackets [ ], but this is optional.
Example: SELECT“column_name”
[“column_name”,“column_name”]
FROM ‘table_name”
WHERE “colum_name”;
You can also write the above example in this way: (no open and close square
brackets)
Example: SELECT“column_name”
FROM “table_name”
WHERE “column_name”=‘America’;
Filtering the data is similar to selecting the data you want to be displayed on
your monitors.
WHERE indicates the content/file that can be found in your table.
Without the WHERE key word, your SQL query would be‘lost in space’not
knowing what data to filter and select.
You can use the following steps to filter your data.
Updating Data
Updating or changing data is one task you must learn and engage in as a
beginner SQL learner.
The key word for this SQL query is UPDATE. You can follow the steps
below.
Step #1 – Create your UPDATE syntax
Prepare your update SQL query or syntax by using the keyword UPDATE.
Double check your SQL syntax
You must double check your statement before clicking the enter button. One
error can cause problems in your database.
Let’s practice making UPDATE SQL statements from the table below. The
table below is on “Online Students”.
Students
ANSWER:
Your SQL statement should appear this way:
If you have submitted the correct SQL query, your resulting table will appear
like this:
Students
StudentNo LastName FirstName Age Address City
1 Potter Michael 17 130 Cheyenne
Reed
Ave.
2 Walker Jean 18 34 Staten Laramie
Sq.
3 Anderson Ted 18 22 Staten Laramie
Sq.
4 Dixon Allan 18 12 Glenn Casper
Rd.
5 Cruise Timothy 19 20 Reed Cheyenne
Ave.
6 Depp Adam 17 276 Laramie
Grand
Ave.
7 Lambert David 19 32 8 St.
th
Cody
8 Cowell Janine 18 140 Casper
Center
St.
9 Kennedy Daniel 17 11 21 st
Laramie
St.
10 Budzinak Leila 20 24 Wing Cheyenne
St.
EXERCISE #2
You want to update the address of Cowell, Janine to 20 18 St. Laramie City.
th
UPDATE students
SET Address = ‘2018 St.’, City = ‘Laramie’
th
If your SQL query is correct, your table will be updated according to your
recent input.
Creating Indexes
Creating indexes is also essential knowledge that you should learn as a SQL
beginner.
These indexes are essential when searching for data or tables because they
provide an immediate and efficient result to queries.
To save time and effort, create indexes only for tables that you often use.
The basic CREATE INDEX SQL query is:
The SQL above will display all files - even duplicate files. If you want your
result table to show only unique data, you can use the keywords CREATE
UNIQUE INDEX, instead.
The basic SQL statement is similar with that of CREATE INDEX.
Here it is:
Example: CREATE UNIQUE INDEX “Index_name”
ON “table_name”; (you can include the
“colum_name”, if you need that data)
Functions
User-defined functions often come to play when creating your Python codes.
These functions can be used when you want a task or code done repeatedly.
Functions can also help in maintaining your codes.
Keep in mind that you have also your built-in functions, which you can easily
‘call’, whenever you need them.
SQL has numerous functions that can be used to work with date and time
values. Let us discuss them.
MySQL Functions
MySQL databases
With MySQL, you can add, access, modify and also delete any data that is
stored within the database of a MySQL server.
There is no limitation as to the number of databases that you can create on a
MySQL server. The only limitation will be on the number of tables you can
create, and all this depends on the file system.
If you have large MySQL databases, you can partition them so as to improve
performance and management.
When you are querying, you are free to include tables from different
databases on the same query.
MySQL Tables
There is a large amount of data that you can create with MySQL. You can
create about 4,096 columns and store as many records as you want with no
limitation at all whenever you are designing MySQL tables.
Each field can contain an assorted range of data. You can always fix the
length of a certain field set primary and index keys, require that they have
values and even increment numbers automatically.
SQL syntax is utilized to query tables. Use functions such as select, insert,
update, show, join, and delete, among other syntaxes that are allowed by SQL
languages.
This is typically a simple and interesting thing to do once you master the
basics of MySQL. Choose between phpMyAdmin interface or Secure Shell
Command Line.
Joins
The databases used in industries have very complex structures. The data
selection is often done from more than one table. Sometimes, tens of tables
combine together to return a meaningful result set. To combine the records of
multiple tables and select them, we use joins. Joins allow you to query data
from multiple tables. There are six types of joins available in SQL:
Inner Join
Left join
Right Join
Full Join
Self Join
Cartesian product
Before we move on towards discussing the details about all the types of joins,
let’s first create another SQL table inside the Employee database. The name
of the table will be Customers. In our scenario, I am assuming that the
database Employee contains the details of all employees in a retail store. This
database also keeps the details about the customers who are served by its
employees. Let’s start with creating a customer table.
Union
The union keyword combines unique results of two select statements. Union
keyword only works when the select statements involved bring result sets
with the same structure (equal number of column and rows), the same order
of column selection, and the same datatypes. The query below is combining
the results of a left joined query and a right joined query using the UNION
keyword.
ALIASES
Sometimes you need to rename a table to facilitate your SQL query. This
renamed table are termed ALIASES.
They are only temporary and do not change the name of your base table in
your databases.
ALIASES are useful when your SQL query uses more than one table; when
you want to combine columns; when your column_names are long or vague
and you want to change them for something simpler and clearer.
You can also use ALIASES when you want to define the functions in your
SQL statement.
Here is an example of a SQL query using ALIASES:
For tables:
Example: SELECT“column_name1,“column_name2”
FROM“table_name”AS“alias_name”
WHERE [condition];
For columns:
Example: SELECT“column_name”AS“alias_name”
FROM“table_name”
WHERE [condition];
Chapter 6. VIEWS
VIEWS are virtual tables or stored SQL queries in the databases that have
predefined queries and unique names. They are actually the resulting tables
from your SQL queries.
As a beginner, you may want to learn about how you can use VIEWS.
Among their numerous uses is their flexibility can combine rows and
columns from VIEWS.
Step #3–Use key words for your SQL syntax just like with any other SQL
main queries.
Step #4–Your basic CREATE VIEW statement or syntax will appear like
this:
Example: Create view view_”table_name AS
SELECT“column_name1”
FROM“table_name”
WHERE [condition];
Let’s have a specific example based on our original table.
EmployeesSalary
Based on the table above, you may want to create a view of the customers’
name and the City only. This is how you should write your statement.
From the resulting VIEW table, you can now create a query such as the
statement below.
SELECT * FROM EmployeesSalary_VIEW;
This SQL query will display a table that will appear this way:
EmployeesSalary
Names City
Williams, Michael Casper
Colton, Jean San Diego
Anderson, Ted Laramie
Dixon, Allan Chicago
Clarkson, Tim New York
Alaina, Ann Ottawa
Rogers, David San Francisco
Lambert, Jancy Los Angeles
Kennedy, Tom Denver
Schultz, Diana New York
Using the keyword WITH CHECK OPTION
These keywords ascertain that there will be no return errors with the INSERT
and UPDATE returns, and that all conditions are fulfilled properly.
Applying this SQL statement to the same conditions (display name and city),
we can come up now with our WITH CHECK OPTION statement.
Example: CREATE VIEW EmployeesSalary_VIEW AS
SELECT Names, City
FROM EmployeesSalary
WHERE City IS NOT NULL
WITH CHECK OPTION;
The SQL query above will ensure that there will be no NULL returns
in your resulting table.
DROPPING VIEWS
You can drop your VIEWS whenever you don’t need them anymore. The
SQL syntax is the same as the main SQL statements.
Example: DROP VIEW EmployeesSalary_VIEW;
UPDATING VIEWS
You can easily UPDATE VIEWS by following the SQL query for main
queries.
Example: CREATE OR REPLACE
VIEW“tablename”_VIEWS(could also be VIEWS_’tablename”) AS
SELECT“column_name”
FROM“table_name”
WHERE condition;
DELETING VIEWS
The SQL syntax for DELETING VIEWS is much the same way as
DELETING DATA using the main SQL query. The difference only is in the
name of the table.
If you use the VIEW table example above, and want to delete the City
column, you can come up with this SQL statement.
Example: DELETE FROM EmployeesSalary_VIEW
WHERE City =‘New York’;
The SQL statement above would have this output:
EmployeesSalary
INSERTING ROWS
Creating an SQL in INSERTING ROWS is similar to the UPDATING
VIEWS syntax. Make sure you have included the NOT NULL columns.
ON TABLE_NAME
[REFERENCING OLD_OR_NEW_VALUE_ALIAS_LIST]
TRIGGERED_ACTION
Dropping a Trigger
The basic syntax for dropping or destroying a trigger is the same as dropping
a table:
DROP TRIGGER TRIGGER_NAME;
Chapter 9. VARIABLES AND STORED
ROUTINES
Variables
Python makes use of variables. As previously discussed, variables can
contain a string of words, an integer (number) or other items. Hence, they act
as containers.
Example:
Let’s say you want your variable to be 50, you can enter this in your Python.
myVariable = 50
This is for the Python version 3. The first letter is in the lower case and the
first letter of the next words are in the upper case. This is termed the‘camel
case declaration’.
You must remember that Python is case sensitive, so use the upper case and
lower case letters whenever necessary.
myVariableTitle = 50
Step #2–Press‘enter’.
After entering or assigningthe value, you can press‘enter’, and the value 50
will appear. This is your value.
You can make use of it in math operations to compute whatever you want to
compute.
If your syntax is wrong, a syntax error appears in red ink, informing you of
the mistake.
You can assign values to your variables by using the equal (=) sign. You
have to name your variable before the equal sign and assign its values after
the equal sign.
Examples:
name =“Billy”
surname =“Trump”
age = 45
height = 5
Your variables are: name, surname, age and height and the values assigned
are:“Billy”,“Trump”, 45, and 5.
If you want to print your variables, you can create your statement or code this
way:
name =“Billy”
surname =“Trump”
age = 45
height = 5
print name
print surname
print age
print height
See image below:
The original shell was used; thus,the variables are printed one by one by
pressing your‘enter’tab/key.
Unlike if you open a‘New File’, the results will be displayed all at once in a
new shell:
If you decide to open a‘New File’, the syntax/statement will appear this way:
When you click‘Run’, and then ‘Run Module’, the results will appear in a
new shell:
It’s smart to name your variables according to their objects/content, so
you won’t get confused accessing them later on.
As discussed, variables can contain names or integers, or different types
of data. Just be sure to separate them with commas.
For variables that you want printed literally in a string, don’t include
them inside braces [ ]. These will appear in the final output.
Take note again, that numbers or integers are not enclosed in quotes
(quotation marks– ‘’), while word-strings are enclosed in single, double
quotes, or triple quotes. (‘ ’, or“ ”, or“”” “””).
Stored routines
Python contains built-in modules and functions that come with the program
when you download it into your computer. Downloading the Python versions
2 and 3 in the same computer may not work, because some of their
contents/functions are incompatible with each other, although they are both
from Python.
The following are quick steps in accessing and learning these built-in
modules and functions:
help(“modulesprofile”)
dir([‘__builtin__’])
See image
below:
The different functions will appear on your Python shell. You can choose any
of the functions you want to use.
You can also access the built-in functions or modules by importing them.
This is done by opening your idle shell, and then typing:
import urllib
and then, type
dir(urllib)
When you press‘enter’, all the Python modules will be displayed on your
shell.
See image below:
help(max)
As shown above, the highest value of the first set is 10, and the second is 11.
Step #5 - Access the Python modules and built-in functions from your
downloaded file.
Another alternative is to access the different Python functions from the files
that you have saved.
Remember, if your Python syntax or statement is wrong, the words will be
colored red. So, it’s easy to detect errors in your commands or statements.
Stored procedures
You can create and save your Python files, so you can easily access and run
them, whenever you need them. There are standard data types used in Python
that you have to learn; these are: strings, lists, numbers, tuples and the
dictionary.
But how do you create, save and run your own files?
Here’s how:
Step #1 – Open your Python shell.
As instructed in the earlier chapter, after you have downloaded and saved the
Python program in your computer/device, you can open your Python shell by
clicking your saved Python and click IDLE (for Python version 3) or follow
the instructions for version 2 as discussed in chapter 7.
The new box is where you can create your file for saving. If you have
noticed, the file is still untitled because you will be assigning the title before
you can save it. You may save the file first before proceeding, or proceed to
write your Python statement/code before saving.
Write your file.
For example, you want to create a file to provide the maximum or largest
value of your variables (a, b, c, d), you can enter in your new file in the
following manner:
a=int(input(“Please enter 1stnumber”))
b=int(input(“Please enter 2ndnumber”))
c=int(input(“Please enter 3rdnumber”))
d=int(input(“Please enter 4thnumber”))
print (max(a,b,c,d))
Make sure you enter the correct items and had used the necessary quotes and
parentheses.
Any error in the signs, indentations, and quotes in your statement will yield
errors.
Python won’t be able to execute your command, and says so in red ink.
When you click on the‘Save As’option, a box will appear allowing you to
select the name of your file, and where you want to save your file. Ascertain
that your file is with the suffix .py.
Let’s say you want to name your file math1. Type the name on the provided
box,and press‘Save’.
When you click on the‘Run Module’option, a new shell will appear. You can
now enter your variables or values.
Test your file if it’s working by providing the values required.Let’s say the
values of your items - a, b, c, and d -are 1356, 1827, 1359 and 1836. When
you press‘enter’, the value 1836 will appear, because it is the largest or
highest value.
Of course, you can add more statements/codes, if you wish. This is just an
example on how to create and save your Python file.
You can add another item/command, (“Please press enter to exit”), to provide
easier access. Save your file again.
See image below.
Take note that Python doesn’t compile your programs, you have to run them
directly.
Deleting files
To delete files, use the key‘del’.
Example:
myname=”Lincoln”
myage=20
del myname
This will delete your variable‘myname’, and whatever is specified in your
command or code.
You can delete as many variables as you want.Don’t worry, you can always
create new files, if you want to.
Stored functions
You can create and utilize your own user-defined functions.
Step #1 – Use a keyword to define function.
The function should be defined first making use of the word ‘def’, and then
the name of its function.
When you want to define a function, you can use the general code
below:
def functionname (arg1, arg2, arg3)
statement1
statement2
statement3
def employee(num)
print (“num”)
See image below:
When you press enter, and input a number, the function will keep going until
you decide to stop. So, the function can work repetitively. See image below:
Press ‘enter’ twice and then you can begin entering the numbers. The
program will print it ad infinitum.
See image below:
When you, or the student enters his grades following the syntax/statement,
the ‘return’ results would be the computed value already. See image below:
The student has to type in the shell, after the arrows (>>>), following the
given format:
grades(80,90,85,75)
Through this method, you can compute the grades of your students- ad
infinitum.
Take note that ‘return’ results are different from ‘return’ statements. Refer to
the chapter involved.
Keep in mind that you have first to define (def) the function, before your
code can work, and print the results.
Remember to add the colon (:) after your def statement. You must also
separate the arguments by commas.
In default parameters, the originally assigned value is printed, when the user
doesn’t enter any value.
You can now enter your employees’ names. See image below.
If you use the del keyword in the object or instance, for example:
Adding employeeName.__del__ ( )
The resources or employees’ name will be deleted or destroyed.
See image below:
When you click ‘Run’, and then ‘Run Module’, a new shell will
open.
See image below:
When you click ‘Run’, and then ‘Run Module’, another Python shell
will open, printing the results. See image below:
You can edit your code to produce results that are in congruence with
your preferences. Isn’t it fun?
Reminders:
For each definition, a colon ( : ) is added at the end of the statement.
‘self’ is always included in each member function, even if there are
no arguments. Example of arguments are those values found inside
the parentheses (self, firstName, LastName).
Double quotes or single quotes can be used with the arguments.
The constructor and destructor can contain arguments other than self.
You can include any arguments you want. Example of arguments are
(self, firstName, lastName). Make sure though that your __init__
arguments are included in the instances or objects’ statements that
come after the ‘def’.
employeeName=EmployeeInfo ( )
employeeName.personalInfo("Virginia", "Walker")
employeeName.printPersonalInfo ( )
If you run the class code above, this would appear in your Python
shell:
Tweak the codes and see what happens. Curiosity doesn’t always kill the cat.
Chapter 10. CONTROL FLOW TOOLS
IF statement
In Python, you can use various condition statements. However, you have to
ascertain that you follow the Python syntax rules and indentation. One of
these rules is to provide an indentation after the ‘if’ and ‘else’ statements,
when you enter their codes. Simply press the tab once to provide the
indentation.
Anyway, the program will assist you in determining errors in your Python
syntax. If there’s an error, it will display the errors, and what’s wrong with
them. You can also press for help, if you’re lost in the sea of Python lingo.
Therefore, relax and enjoy the experience.
Functions
The ‘IF ELSE’ statements, which execute codes, are generally used to
compare values, or determine their correctness. ‘if’ is expressed, if the
condition is ‘true’, while ‘else’ is expressed when the condition is ‘false’.
if expression:
Statement/s
else:
Statement/s
Example:
CASE statement
Ruby language is common in organizations for web application development.
Ruby on Rails is a framework that allows for rapid development, and
business teams focus on other business processes instead of coding functions
from scratch. This framework provides a separator known as MVC structure
(Model-view-controller). The MVC provides support in separating data, user
interface, and business functions.
On the other hand, Python has the most popular MVC frameworks known as
Django web framework for web application development. In addition, Python
is also famous beyond the domains of web applications. For example, the
Pandas library is useful for data preparation. Other libraries such as numpy
and stats-model are also supportive in this case. Matplotlib is a powerful
Python library for data visualization. Tensorflow is popular for machine
learning tasks and projects. Besides, SciPy is another open-source library for
Python, which is used for scientific computing and solving math functions
that used to make engineering students sweat.
WHILE statement
The while statement is the main looping statement and is mostly used
whenever simple iterations are required. Its structure is as follows:
Counter = 10
while counter>0:
print counter
counter = counter-1
print ‘Backward counting from 10 to 1’
This simple while loop will keep on checking the while condition
again and again until the condition becomes false. Until the condition
becomes false, every time the cycle goes through the loop. Then after the
condition becomes false the interpreter resumes the former activity and
continues with the program statements just after the loop. Following diagram
illustrates the flow of while controls.
LOOP statement
As defined in the previous chapter, it is a symbol used to represent repeated
(iterated) word/s or sentence/s in Python programming. Anything that is
being repeatedly used can employ a loop (a piece of code). Hence, it
facilitates the task that you would want to accomplish.
Types of loops
t=0
And you want the user to ‘Enter numbers to add to the total.’, you write the
code for the ‘while; loop this way:
print (‘Enter numbers to add to the total.’)
print (‘Enter x to quit.’)
(Now use the ‘while’ function to allow the action to become repetitive.)
while a ! = 0:
print (‘Current Total: ‘ , t)
a = float(input(“Number? ‘))
a = float (a)
t+ = a
print (‘Grand Total = ‘ , t)
This is how your code will look like.
Chapter 11. CURSORS
In general, SQL commands manipulate, or work around, database objects
using set-based operations, meaning transactions are performed on a block or
group of data. A cursor, on the other hand, retrieves and processes a subset of
data from the database one row at a time. It is actually like a pointer that
refers to a specific table row. When cursor is activated, a user can select,
update or delete the row at which it is pointing. It also enables the SQL
program to retrieve table rows one at a time and send it to a procedural code
for processing. In this way, the entire table is processed row by row.
To simplify things, SQL has SQL has created a way to return error messages
so that users or programmers will be aware of what is happening in the
database system. This will further lead to taking corrective measures to
improve the situation. Some of the common error-handling error-handling
features are the WHENEVER clause and the SQLSTATE status parameter.
SQLSTATE
The host variable or status parameter SQLSTATE is one of the SQL error-
handling tools that includes a wide selection of anomalous programming
conditions. It is a five-character string that consists of uppercase letters from
A to Z and numeral values from 0 to 9. The first two characters refer to the
class code, while the next three signify the subclass code. The indicated class
code is responsible for identifying the status after an SQL statement has been
completed – whether it is successful or not. If the execution of the SQL
statement is not successful, then one of the major types of error conditions
will be returned. Additional information about the execution of the SQL
statement is also indicated in the subclass code.
The SQLSTATE is always updated after every operation. If its value is set to
‘00000’, this means that the execution was successful, and you can proceed
to the succeeding operation. If it contains a string other than the five zeroes,
then the user has to check his programming codes to correct the error
committed. There are multiple ways on how to handle a certain SQL error,
which normally depends on the on the class and subclass codes indicated by
the SQLSTATE.
WHENEVER Clause
The WHENEVER clause should be written before the executable part of the
SQL code, in the declaration section to be exact. The standard syntax for the
said clause is:
In essence, you are going to be able to update, delete, insert, and search for
the things that you are going to be putting into the program. It is very
common for SQL to be described as a declarative language, however, the
program also allows for procedural elements.
This is one of the first languages that was able to use the relational model that
was created by Edgar F Codd. Although it is not going to work with all of the
rules that are set forth for this model, it is one of the most widely used
languages for data bases.
In ’86, SQL became part of the ANSI. Then, in ’87 it became part of the ISO.
However, there have been updates since then that have made it to where the
language can include larger sets. Just keep in mind that the code for SQL is
not going to be one hundred percent portable between data bases unless there
are some adjustments to the code so that it fits the requirements for that data
base.
Learning SQL can be one of the better decisions that you make about your
career because you can push yourself forward with it that way that you can
rely on using your own knowledge rather than having to go to someone else
for their knowledge. In fact, people are going to be coming to you to learn
what it is that you know about the program.
By learning SQL, you are going to be able to do more than you may have
been able to before. Here are a few things that are going to give you a good
reason as to why you should learn SQL.
Money
Learning SQL makes it to where you have the opportunity to earn some extra
money. Developers that work with SQL earn around $92,000 a year! An
administrator for an SQL data base is going to make about $97,000 a year.
So, just learning SQL makes it to where you are able to earn around twice as
much as what the average American household is going to make in a year.
Highly sought after
Employers are wanting people who know SQL! The more knowledge that
you have about SQL the more sought after you are going to by employers.
Knowing SQL is not only going to benefit you but your employer as well
because they are not going to have to pay for you to learn the program. The
interviewing process is going to be better than any other process that you
have gone through and you may find that they are going to be willing to give
you more money just for knowing SQL over the other person. With SQL
knowledge, you are going to be opening yourself up for more careers than
you might have been able to apply for before.
Get answers
SQL is going to give you the answers that you are looking for to any
questions that you may have about business or data that is being stored inside
of your data base. Therefore, you are going to be more self-sufficient and not
as dependent on others when it comes to business. If you are able to answer
questions on your own that you so that you are not stopping someone else
from doing their job, then an employer is going to be able to save money by
hiring you because you are going to be able to answer questions on hiring
someone else to answer those questions. Knowing SQL is going to even help
you if you are wanting to start your own business or push your business that
you have already started to the next step that has just been out of your reach.
More stable than Excel
When you are using Excel for large amounts of data, you may notice that it is
too much for the program and therefore the program tends to crash. A crash
leads to lost data and extra time that you are going to have to go in and fix
anything that may be wrong or entering data that was not saved. SQL is going
to be much more reliable for you to use when you are trying to work with
large amounts of data and it is going to save you some time working with it
because it is not going to require too much for you to work with the processes
that SQL offers.
Making reports
Searching in SQL is relatively easy and you can reuse that search when you
have to double check to make sure that the data in the data base is accurate.
Excel does not give you the proper processes that you need to get ahold of the
data that you are wanting to get ahold of.
SQL coding only has to be written once and saved and then it is going to run
each time that you need it to. This is yet another way that SQL makes it to
where your life is easier because you are not having to take up as much time
trying to get the data that you need.
Do not think that SQL is going to be simple, it is complicated and is going to
take a lot of time to learn, but the more effort that you put into it, the more it
is going to pay off for you. You are going to not only be saving money by
learning SQL, but you are going to be increasing what you will be able to
make with SQL.
After the user has been able to set up their own account, they will have access
to all parts of the database that pertain to them. They can make changes as
well, such as updating their address, changing their payment options, and
even making changes to the orders that they placed. In addition, any time that
the user would like to be able to get into their account, all they need to do is
use the username and password that they picked the first time and log in to
mess around on the database.
Let's take a better look at how this will work by bringing out an example.
Let's say that you are the person who has the credentials that are needed to
log in. For this example, we will use the username ‘PERSON1.’ You can
decide what you would like to place inside this database and you can even
create a brand new table, for this one we will call it ‘EMPLOYEES_TBL.’
When you then go into the records, you will notice that for this new table, it
will be called PERSON1 EMPLOYEES_TBL. This is how others will see the
table name as well so they know who created the table. The schema will be
the same for each person who created this table and owns it.
When you or your user would like to access their own schema, one that is
prepared already, you will not have to list out the exact name of the schema.
Instead, you would simply need to pull up the name that you gave it. So, for
the example that we went through before, you would be able to call up
EMPLOYEES_TBL. Remember that this is just with schemas that are in
your own account. If you would like to be able to pull up schemas that are
present somewhere else, you must add the username ahead of it.
It is important to think about what you would like to have in the table, how
you would like the table to look, how big it should be, and other information
about the table to ensure that it is made properly. Almost all of the versions
of SQL will provide you with characters that will make it easy to submit or
terminate a statement to the server. With ORACLE, the semicolon will be the
option that you would use, but with the Transact-SQL version, it is better to
work with the GO command. But for most of these versions, you would be
able to use the CREATE TABLE command and then when you are ready,
you can start filling them out.
This command must be combined with the ‘FROM’ command to obtain the
necessary data in a format that is readable and organized. You will use this to
help determine the data that will show up. The SELECT clause will introduce
the columns that you would like to see out of the search results, and then you
can use the FROM to find the exact point that you need.
FROM
The SELECT and the FROM commands often go together. It is mandatory
because it takes your search from everything in the database, down to just the
things that you would like. You will need to have at least one FROM clause
for this to work. A good example of a syntax that would use both the
SELECT and the FROM properly are these:
2. CREATE TABLE
C. CERTIFICATIONS
The widespread use of Linux has increased the demand for engineers and
users who know exactly what they are doing. At this point a certification for
Linux becomes advantageous. These certifications can be divided into
programs that are general (not specific to a distribution) and focused (specific
to a Linux distribution). The lists below give an overview of the primary
certifications that currently exist.
Non-specific Certifications
Linux Essentials
LPIC-1: Linux Server Professional Certification
LPIC-2: Linux Engineer
Linux Foundation Certified System Administrator (LFCS)
Linux Foundation Certified Engineer (LFCE)
CompTIA A+
CompTIA Network+
Distribution-specific Certifications
UNIX Variants
The concept of UNIX became licensed to several companies that developed
and maintained their own variant of UNIX. This included Solaris/SUN OS
(SUN Microsystems, nowadays owned by Oracle), AIX (IBM), Scenix
(Siemens), SCO UNIX, Xenix (Microsoft), as well as HP-UX (Hewlett-
Packard), NeXTSTEP, Mac OS (Apple) and Android (Google).
Open-source implementations comprised of the Berkeley System Distribution
(BSD) with its variants: NetBSD, OpenBSD, and FreeBSD. Today, Linux is
the most popular free software among open source developers. There is also a
strong commercial support for the systems mentioned above.
The UNIX Philosophy
UNIX is designed with a number of strict principles in mind. These
principles cover portability, multi-tasking and multi-user orientation in
combination with a time-sharing approach. Furthermore, it is based on
network connectivity following the TCP/IP scheme.
The original development was done in the C programming language that
resulted in independence from a hardware platform. Delivered with a
selection of development tools and libraries, it allows you to easily extend it
to your specific needs. It is simple, but has a powerful ability to automate
tasks that supports complex but maintainable scripts.
Similar to a toolbox, UNIX consists of a variety of tools. Each of them
having a specific purpose and being designed exactly for that task. The idea
is to use one tool per task. In order to achieve more complex goals, you
would combine several tools into a chain. The following example combines
the two commands ‘ls’ and ‘wc’ by means of a pipe to be able to count the
number of Python files in the current directory.
CHAPTER 2: LINUX EVERYDAY
There are a few terms that may confuse Linux beginners. The first thing is its
name, Linux vs GNU/Linux. The term Linux refers to the Linux kernel only.
In reality many users refer to Linux as the operating system as a whole, the
kernel plus libraries and tools. Also the term Linux is used to include all the
programs that run on Linux, or that are available for this great operating
system.
Furthermore, the description GNU/Linux needs understanding. Linux
distributions with this name prefix are fleshed out with GNU
implementations of the system tools and programs. One such example is
Debian GNU/Linux. The GNU project goes back to the initiative of Richard
M. Stallman and his dream to develop a free UNIX system. Based on his
experiences at MIT and the collaboration with other colleagues he choose to
use free software that was already available to rewrite the tools he needed.
This included the TeX typesetting system as well as X11 window system. He
published the rewritten tools under the GPL license whenever possible to
make his work available freely to everyone who was interested in it.
A. LINUX DISTRIBUTIONS
A Linux distribution is a collection of software packages that fit together. A
distribution is maintained by a team of software developers. Each member of
the team focuses on a different package of the distribution. Together as a
team they ensure that the single software packages are up-to-date and do not
conflict with the other packages of the same release of the distribution.
As of 2018 for Debian GNU/Linux 9, the official repositories contain more
than 51,000 different packages. A repository is a directory of packages with a
certain purpose. Debian GNU/Linux sorts its packages according to the
development state. The official repository is named stable and reflects the
current release of stable packages. The other repositories are named testing
and unstable, and work in the same way but do not count as official packages.
Typically a Linux distribution comprises of packages for a Linux kernel, a
boot loader, GNU tools and libraries, a graphical desktop environment with a
windows environment, as well as additional software like a web browser, an
email client, databases and documentation. The software is provided in two
ways; as the source code and as the compiled binary packages. This allows
you to understand how the software is designed, to study it and to adjust it
according to your personal needs.
Depending on the focus of the Linux distribution, it also contains packages
for a specific purpose like network or forensic tools, scientific software for
educational purposes, and multimedia applications.
Ubuntu
Linux Mint
Fedora
Workstation: for pc
Server: for servers
Atomic: for cloud computing
Fedora supports the architectures amd64, ArmHF, powerpc, mips, s390 and
RISC-V. The distribution has a rather short lifecycle where a new release
follows roughly every 6 months. The code name for a release does not follow
a fixed naming scheme but mostly consists of city names.
CentOS
CentOS abbreviates from the name Community Enterprise Operating System.
As with Fedora it is based on Red Hat Enterprise Linux, and compatible in
terms of the binary packages. This allows the use of software on CentOS that
is initially offered and developed with RHEL in mind. In contrast to Fedora it
focuses on enterprise use for both desktop and server, with long-term support.
The initial release of CentOS goes back to May 2004. The software packages
come from three different repositories:
Base: regular, stable packages
Updates: security, bug fix or enhancement updates
Addons: packages required for building the larger packages
that make up the main CentOS distribution, but are not
provided upstream
CentOS is available for the architectures i386 and amd64. Other architectures
are not supported.
openSUSE
The Linux distribution openSUSE has its roots in the distributions SUSE
Linux and the commercial SUSE Linux Professional that saw its first release
in 1994. The name SUSE is an abbreviation for the original German owner
named Gesellschaft für Software- und Systementwicklung GmbH.
OpenSUSE is based on the structures of Red Hat Linux and Slackware, and
uses .rpm as a software archive format. It is available for the architectures
i586, x86-64 and ARM. The openSUSE project aims to release a new version
every eight months. As with Fedora, the code name for a release does not
follow a fixed naming scheme.
Arch Linux
Arch Linux is a free Linux distribution that saw its first release in 2002. It
follows the principle of a rolling release, which results in monthly releases of
the distribution. Currently the core team consists of about 25 developers and
is supported by a number of other developers, called trusted users. Arch
Linux uses Pacman as a package management system. The single packages
are held in four software repositories:
Gentoo
As with Arch Linux, Gentoo follows the principle of a rolling release. New
installation images are available weekly, with the first release available in
2002. Gentoo is special due to being a source code based distribution. Before
installing the software, it has to be compiled first. Supported architectures are
alpha, amd64, arm, hppa, IA-64, m68k, mips, powerpc, s390, sh and sparc.
Slackware
Slackware is the oldest active Linux distribution. The first release dates back
to 1992. Regular releases are available without a fixed interval. It targets the
professional user, and gives him/her as much freedom as possible. Slackware
uses compressed tar.gz archives as a package format, and supports the four
architectures i486, alpha, sparc and arm. The distribution was also ported to
architecture s390.
CHAPTER 3 : SETTING UP
A. DIFFERENT TYPES OF INSTALLATIONS
Debian offers a variety of methods for a proper setup. This includes a
graphical and a text-based installation; we will use the former. For
installation media the Debian developers offer three variants:
1. CD/DVD Installation
Booting Ubuntu Linux from a CD or DVD is one of the two ways through
which you can install the system on your computer.
Boot from the disk. Once the program is burned into the
disk, you can restart your computer and choose to boot from
the CD or DVD. You may be required to change your boot
preferences. Do this by hitting the Setup key when the
computer is restarting.
2. Windows Installer
:
Important Note
1) It is always a good idea to run such a program on CD or DVD in order to
have a first look at it; then, install it if you like what you see. Test driving
will help you in making a decision you will not regret when it comes to
installing operating systems.
2) Make sure that you backup all your files, programs, personal data and
settings first before installations begin so that you will not lose them.
All these tools mean and do the same thing; they provide a central place from
where you can search and install Linux software with ease. The presence of a
GUI is important though, for you to go through the installation process of
another software. If you do not have a GUI, you will have to rely on
command line interface to do the installations.
What users need to know is that it is very easy to install a software on any
Linux machine. New computer users will also find this very easy and less
time-consuming. The operating system has been designedin order to give
computer users an easy time on everything that they do, and this is just one of
them. After the installation of the operating system, you can start installing
any app that you will need in the use of your machine or device.
C. HOW TO CONFIGURE LINUX
After you have decided what to run at a specific time (schedule), you have to
place it in a place that makes it easier for your daemon to discover it for
reading. Even though there are a few places to place it, the user crontab is the
most common. The crontab is the file that holds a schedule of jobs on cron.
Each user has their own file located at var/spool/cron/crontab; the file
should not be edited directly. To edit, use the crontab command. Here is the
command that you require:
crontab –e
The above command calls up the text editor. You can use the text editor to
input your job schedule. Each job should be on a new line. If you would like
to view your crontab without editing it, use the command below:
crontab -l
Below is the command to erase the crontab
crontab –r
If you are a user with all the privileges of an admin, here is how you edit
another user
crontab -u <user> -e
root@debian95 ~#
reboot
A few seconds later a graphical login screen will be visible (see image
below). Log in to the system with the regular user named user as created
earlier. Type in user, press Enter and type in the password for the user. Then,
press Enter again to confirm and log in.
The desktop comes with a number of default elements: an upper navigation
bar, a lower navigation bar and desktop icons.
user@debian95: ~$
su
Password:
You may remember from the previous steps that only an administrative user
can install, update or remove software on a Debian system. The su command
abbreviates switch user and changes your current role. Used without an
additional name, the role changes to the administrative root user. At the
password prompt type in the password for the administrative user and press
Enter.
As an administrative user, install the packages: firefox-esr, gnome-terminal,
xscreenserver and vlc as follows:
After the installation of the four packages, you can switch back to your role
as a regular user. Press Ctrl+D to quit the admin part, and press Ctrl+D again
to close xterm.
The installation of Firefox has the following effects:
The very thought of using command line scares a lot of people, and they have
no desire to do so. However, since you are reading this section, let’s assume
that you want to learn about command line, and begin with some basic
commands. One great thing about working with command line is that you can
work with a range of different Linux distributions, and always be able to do
things the same way, with command line. Another reason that people like
using command line is the pure power it gives them, although it is a little
more complex to learn than graphical user interfaces.
Open up your command line software, which is also knows as your system’s
shell. This is called Terminal in Ubuntu, and you can find your shell with a
quick system search. The keyboard shortcut to access Terminal is Ctrl + Alt +
T, and this shortcut is the same for many versions of Linux.
If this is becoming too complex for you to understand, don’t worry. You can
always go back to using the graphical interface when you become stuck, and
keep practicing with the command line in your own time.
What is a Terminal?
To be precise, a terminal is simply the outside. Inside a terminal runs a
command line interpreter that is called a shell.
Debian Linux supports a long list of terminal software. This includes the
Aterm, as well as the GNOME terminal, the Kterm, the Mate Terminal, the
Rxvt, the Xterm and the Xvt. These different implementations of terminal
software vary in terms of stability, support for character sets, design, colors
and fonts, as well as the possibility to apply background images or work with
transparency
In this book we will use the GNOME terminal because of its stability,
simplicity and adjustability. In order to increase and decrease the size of the
content that is displayed inside the terminal window; use the two-key
combinations CTRL+ and CTRL-.
CHAPTER 5: ESSENTIAL COMMANDS
A. INTRO TO FILE AND DIRECTORIES
1. SHELL FEATURES
Simply speaking, a shell is a sophisticated command-line interpreter. In a
loop the shell reads characters, modifies them under certain conditions, and
executes the result.
Under certain conditions, between reading from the command-line and the
execution of the actual result, the shell has to interpret special characters that
are part of your input.
Available Shells
Your Linux system allows the usage of various shells. Each shell is available
as a separate software package through the Debian package manager,
Aptitude, we installed earlier.
Unless otherwise stated the examples in this document are based on the
Bourne Again Shell (bash). At the time of writing this document this is the
default shell on Debian.
Everything is a file
The first thing that we need to know is that everything is a file. For example a
text file is a file, your keyboard is a file, a directory is a file and even a
monitor is a file.
Linux is an Extensionless System
A file extension is usually a set of 2 – 4 characters subsequent to the end of a
file, which determines the type of file it is.
cd ‘My Photos’
pwd
/home/mike/Docs/My Photos
Escape Characters
You can also define an item with a space in it by using an escape character,
also known as a backslash ( \ ). The backslash nullifies the meaning of the
character directly following it.
cd Happyday\ Pictures
pwd
/home/mike/Docs/My Photos
You can see above that the space between ‘Happyday’ and ‘Pictures,’ which
would normally have a special meaning (separating into unique command
line arguments). Thanks to the backslash, the special meaning is ignored in
the argument.
If Tab Completion is used before the space in a director name, the terminal
will automatically remove the special function of any spaces in the name.
Hidden Files and Directories
The mechanism to specify whether a file or directory is hidden is very elegant
in Linux. By beginning a file or directory’s name with a ‘.’ (full stop), it will
be interpreted as hidden - it doesn’t even require any sort of special command
or action. There are several reasons for a file or directory to be hidden. For
example, a user’s configuration files (stored in the home directory) are
generally hidden in order to declutter the space for the user’s everyday tasks.
In order to make a file or directory hidden, create or rename it with its name
beginning with a ‘.’. In the same fashion, you can rename a hidden file
without the ‘.’ in order to make it unhidden. It is possible to modify it with
the command line option -a in order to show the hidden files and directories.
Is Docs
3. DIRECTORY OPERATIONS
In Linux, there is a directory called The Root Directory. It serves as the
main directory and as programmers and system administrators would refer to
it, it is the directory of all directories.
4. FILE VIEWING
With vi, we can edit files. It’s possible to use it to view files, but there are
other commands that do so much more conveniently. The first, cat, means
concatenate. The main purpose of this command is to join files together, but
can be used in a more basic form to simply view files.
cat
If you run cat, an individual command line argument file will display the
contents of the file on the screen, as well as a prompt.
Run without a command line argument, cat will do nothing. When a file isn’t
specified, it will read from STDIN which is the keyboard, by default. By
typing something and following it with space, cat will mirror your input
onscreen. To cancel, use +c, the universal cancellation signal in Linux.
Generally, anytime you make a mistake and need to get out of it, pressing +c
will get you out of it.
cat myfirstfile
here you will see
whatever content you
entered in your file
This command is most useful when you have a small file. Larger files,
however, will have their content fill the entire screen and only the last page of
it will be accessible. For these files, another command is more well suited:
less
The command less lets you move around within a fill with the arrow keys on
the keyboard. Spacebar will move you forward an entire page, and b will
move you back. When finished, q will quit the command.
Go ahead and use these command to take a look at the file you just created.
There are many commands that can be used to create, edit, or delete files, but
there are four that are used more frequently than all the others. These are
rm/rmdir, mkdir, cp, mv.
6. FILE PROPERTIES
Navigating a File in Vi
Now we can return to our created file and add more content to it. Using insert
mode, the arrow keys will move the cursor around through the file. Add two
more paragraphs of content, then return to edit mode using the esc key.
The following commands will allow you to move around within a file. Go
ahead and try them out.
Arrow keys - Move the cursor.
j,k,h,l – These keyshort letters will manipulate the cursor down, up, left, and
right (essentially the same function as the arrow keys.)
^ (caret) - Places the cursor at the start of the current line.
$ - Places the cursor at the end of the current line.
nG - Places your cursor on the nth line (for example, 5G will move you to the
5th line.)
G - Places your cursor on the last line.
w - Places your cursor at the beginning of the next word.
nw - Places your cursor n words forward (for example, 2w will move the
cursor two words forward).
b - Places your cursor at the beginning of the previous word.
nb - Places your cursor back n words.
{ - Moves your cursor back one paragraph.
} - Moves your cursor forward one paragraph.
Turning on line numbers can help make navigating a file much easier. To do
so, type ‘:set nu’ while in edit mode.
Deleting Content
Clearly, there are plenty of ways to move around within a file in vi. Most of
them allow for preceding with a number in order to move a specific distance.
Deletion works in much the same way as movement - indeed, many delete
commands allow for movement commands to be incorporated as a too to
indicate what should be deleted.
Next we will look at several of the ways we can delete content within vi.
x - Deletes one character.
nx - Deletes n characters.
dd - Deletes the current line.
dn - d, with a movement command afterwards. Will delete up to where the
movement command would have taken.
Undoing
7. FILE LOCATION
Also, directories are definitely a special type of file. It can be correct to say
that a path is a way to find a particular location in the system and the location
is a file.
Case Sensitivity
Many people who are new to learning Linux struggle with one specific
problem - while many other systems, such as Windows, don’t pay attention to
the case of a character in file reference, Linux does. Thanks to this feature,
it’s possible to have multiple files or directors than have the same name, but
letters in different cases.
Is Docs
MYFILE1.txt Myfile1.txt myfile1.TXT
…
file Docs/myfile1.txt
Docs/myfile1.txt: ERROR: cannot open ‘fil1.txt’ (No such file or directory)
In Linux, all of these are interpreted as completely separate files.
It’s important to be aware of case sensitivity while working with command
line options. For example, in the command line the two options ’s’ and ’S’
perform completely different actions - it’s common to read an option in upper
case, enter it in lower case, and then wonder why your input doesn’t return
the expected output.
Name Spaces
While it is possible to incorporate spaces in perfectly valid file and directory
names, it’s important to be careful with them. Spaces in a command line
signify separate items - that’s how we can know what a program name is and
identify each argument in the command line. For example, if the goal were to
move into a director called ‘My Photos,’ the following command would not
work properly:
Is Docs
Now, you need to install the program. You do this by executing the command
“make install.” This will take you to an install wizard that will guide you
through the process of installing the program to run on your computer.
Compiling your own source code. If you are keen on writing your own code
to use with Linux, great! The steps involved in compiling your own source
code are remarkably similar to compiling third-party source code.
First, you need to use your text editor to write out the actual code. This book
won’t get into any kind of detail about how to write code for Linux, but later
books in this series will. After you type out the code for your program, you
need to use a compiler to compile it. The compiler that you use will depend
on the programming language that you use (more on that in later books in this
series). You should be able to find a free compiler as a Linux-based
application that you can either download or use online.
Once you compile your code, you want to use a sandbox to execute it. This
step will prevent long-term damage to your entire system should there be a
flaw in your code. As with a compiler, you should be able to find a Linux-
compatible sandbox that is available for free. If there are any problems with
your program, like if it doesn’t execute as you had hoped it would or some of
the code is defective, go back and re-write the code until the program runs in
a satisfactory way. Each time you change the code, you will need to re-
compile it. This process makes sure that the human-readable language that
you use to write the code is able to be interpreted by the machine that
executes it.
Once you are finished writing and compiling the code, you need to save the
file to a directory. After that, you follow the exact same steps as when you
compiled the source code from a third party.
B. OUTPUT AND TEXT PROCESSING
The result of the above redirected input will show up on the screen, which is
also labeled the standard output. However, just as with the standard input,
the standard output can be redirected and it is usually redirected to a
particular file. This is accomplished using the “>” symbol as follows:
[me@mylinux me]$ ls > name_list.txt
The ls command in this example will be successfully executed as usual,
however, the output of this command will not appear on the display as is
expected, and instead it will be redirected to the file name_list.txt.
It is important to note that every time the above command is carried out, it
will overwrite the original name_list.txtfile and create a whole new file.
However, if you would like to keep adding to the file rather than overwriting
it from the beginning every time, the symbol “>>” should be used as in the
example below:
[me@mylinux me]$ ls >> name_list.txt
When this command is run, it will add the new results to the end of the file,
making it larger and longer every time it is carried out. If you do attempt to
carry out this command and the target file has not been created, Linux will do
that for you.
There are situations where the standard input and the standard output need to
be redirected. Unlike many other command line programs though, the order
in which you write down these commands in Linux does not matter, as long
as the characters used to redirect (the “<” and “>”) the input and output are in
the command line AFTER the options or arguments that they are redirecting
then the action will be carried out.
If we were to revert to the standard input command [me@mylinux me]$ sort
< file_list.txt and change it so that it also has a redirected standard output, the
result may resemble something like this:
[me@mylinux me]$ sort < file_list.txt> sorted_file_list.txt
In this case, the sort command will be executed, and the result shall be saved
to the sorted_file_list.txt text file.
C. USERS AND GROUPS
These commands deal with a variety of actions in order to manage the users
and groups of your Linux system. Unless explicitly stated, these commands
can be run as a regular user.
whoami
This command returns your current user ID as follows:
$
whoami
user
$
The single columns for who start with the login name of the user. The output
is followed by the name of the terminal, where “console” represents a login
terminal, and “pts/1” abbreviates the first pseudo terminal session. The last
two columns contain the login time and the host the user comes from, in
brackets (see image below).
The single columns for w contain the login name of the user (titled LOGIN),
the name of the terminal (titled TTY), the name of the host the user comes
from (titled FROM), the login time (titled LOGIN@), the activity (idle time
and CPU usage titled IDLE, JCPU, and PCPU) as well as the last command
the user executed (titled WHAT) (see image below).
id and groups
The id command outputs the user and group information of the current user
(see image below). From left to right the columns show the user ID
(uid=1000(user)), the group id (gid=1000(group)) and the name of the groups
the user is a member of.
In order to list the names of all the groups the user belongs to, you can also
invoke the groups command (see image below). The output is a space-
separated list of the group names.
passwd
As shown below, type in the current password first, press Enter, type in the
new password, press Enter to confirm, retype the new password and press
Enter to confirm, again.
chfn
This command is also from the Debian “passwd” package and changes the
user information that is stored on your system in the file /etc/passwd. During
the installation of your Debian system the basic setup was already done. In
order to modify this information you can run chfn without further parameters
in interactive mode, or with one or more of the following options to adapt
only a specific value:
$ chfn -h
135
Password:
$
chsh
This command (also from the Debian “passwd” package) changes the entry
for the shell that you use to log into your Linux system. Again, this
information is stored in the file /etc/passwd. Which shells are allowed to be
used are limited by the entries in the configuration file /etc/shells.
chsh works similar to the chfn command. Invoked without further options an
interactive method is used (see image below).
chsh accepts the option -s (short for --shell) in order to set the shell in non-
interactive mode. The following example shows the according command line
call:
$ chsh -s
/bin/bash
$
In order to modify the shell for a different user other than yourself, invoke
the chsh command with the username as a parameter. Note that only the
administrative user can do this for a different user. The next example shows
how to do that for the user “felix”.
# chsh felix
Changing the login shell for felix
Enter the new value, or press ENTER for the new
value
Login shell [/bin/bash]:
#
su and sudo
In order to change your role from one user to another, you utilize the su
command. su abbreviates “switch user”. Invoked without further options you
change to the root user as follows:
$ su
Password:
#
Working as the administrative root user comes with great responsibility and
presumes that you know exactly what you are doing. To work as a different
user than root, invoke the su command with the desired username as follows:
$ su
felix
Password:
$
The su command changes the current role permanently. In order to run only a
single command as an administrative user, use the sudo command. This
requires the Debian “sudo” package to be installed and the additional user to
be added to the configuration file /etc/sudoers using the visudo command.
This step will be explained in further detail later on.
adduser
The command adduser creates new user accounts. The image below shows
the information that is required. This includes a new entry in the file
/etc/passwd as well as the creation of a new group, plus home directory.
Furthermore, prepared data from the directory /etc/skel is copied into the
previously created home directory. Afterward, the account information is
modified using the chsh command.
Having set up the new user, the entry in the file /etc/passwd looks as follows:
Deleting user accounts and modifying user accounts is done with the help of
the two commands deluser and usermod. The usage of these commands will
be explained in further detail later on.
D. PROCESS MANAGEMENT
1. BACKUPS AND REMOTE STORAGE
These days the very best thing to trust when selecting a server is a Linux
Storage Server. Linux is the most effective operating system for all
computers including servers.
These Servers are the best because they offer top security because it's very
hard to infiltrate them, even for seasoned cyber criminals.
Whenever you work on the web, you want safety and the greatest method to
have a safe business on the web is with Linux.
An additional great thing about Linux is its speed. Systems similar to Ubuntu
Storage Server have shown to be the quickest within the industry. As you can
see, selecting such servers will provide you with the newest speeds and
security.
You increase your quality whenever you tackle speed and security which will
mean much more customers for your company.
The Protection used by Linux Storage Server is unable to be cracked; it's
even malware proof simply because the device is so well designed that files
fail to access other parts of the PC or servers without permission from the
system manager.
In the event, you work on the web you would like to have your files safely
kept from any damage. You can only achieve that with a Linux Server.
You can have your server at home, or you can rent a server from another
company. When choosing a company to provide hosting you should make
sure that it has Linux Network Storage Server because only that way you can
rest assure to have all your files safe from harm. The Linux modern systems
are always being updated so that you don't need to worry about anything.
When you work with the internet, you want to be always able to deliver; that
isn't easy when you have tacky systems running your files. Every time you
rent a server on the internet make sure it has Linux Storage Server or you can
be under great risks.
2. VIEWING PROCESS
The primary purposes for this demand is the name that has been achieved by
the Linux operating system. Now, let us find how this operating system has
become the top most among dedicated systems:
Better control: The best thing about this alternative is that it provides better
control to the users as compared to other alternatives available in the market.
The server is offered with many applications that can be used free of cost to
access the source code. Also, installation of additional applications is also
possible. Manual installation of applications is needed as it provides the
facility of automatic application installation.
Better security: Users are saying that Linux provides better security as
compared to Windows dedicated server. The reason is that as it uses open
source technology, where others can view the code written by the
programmer, he will be highly careful about making mistakes. Furthermore,
attacks on systems are not done through the source code and so it can provide
better security to the users.
You will be asked for your user name, which you selected during the
installation process. After this, you will need to enter your password, to prove
that you are in fact the owner of this user name. The login screens will
usually have some other items, like the system’s name, a clock, and options
to restart or shut down your computer.
It is extremely common nowadays that a person includes an internet site. It
may be a small business enterprise website, a hobby blog or perhaps a forum.
Though, diverse web sites get the different thing; each internet site has one
common will need, an internet hosting provider.
Web hosting could be the podium on which the internet site is positioned so
that it could be visible to the total globe through World Wide Web.
In making positive that your website resides with suitable website hosting
service, you will find several points which can be had to be looked at. The
initial point you'll need to pick is the hosting server kind. Website hosting
server would be the computers and they also need working a good operating
system to take care of applications and services.
Registering with any Linux web hosting organization consumes software for
profitable management of the web site.
And last and not the least, make confident the service provider give just about
all basic features just like firewall, virus protection, servers load balance,
safety and so on anytime pick Linux hosting providers.
You will also find some extra features offered like extra FTP creation,
MYSQL database, add-on domains, Sub domains solutions and several other
services.
4. HOST INFORMATION
Two main reseller hosting organizations that rule the industry, as we say, will
be Linux reseller web hosting and Windows reseller. Each has their signal
good and bad points. Therefore, think cautiously before selecting your choice
of reseller hosting package.
Your choice of reseller web host might provide you with a choice to upload
documents on whether Linux system or perhaps Windows server. This option
may be provided to you determined by your individual needs since both
platforms are superb in overall performance.
Linux offers a number of advantages to making use of its software to the
server system such as:
It can be an open source technological innovation, which is its key advantage
throughout its opponents. Consequently you, as a client, do not pay any extra
licensing charges to get the software.
Should you aren't pleased with Linux reseller hosting computer software and
desire to convert to Windows, this platform offers you this capability. It is
essential to publish your current documents to your Windows site,
effortlessly and seamlessly.
Whatsmore, the site is scalable enough to get altered to match your changing
needs. This helps it be the ideal alternative for developing online
organizations.
Due to the fact the Linux reseller hosting choice is totally free and an open
source technological innovation, it can be extremely cost effective. The only
fee a user will need to pay is for distribution that is laid down by the owner or
the provider. However, this is a little expense and could be paid for by any
consumer.
Customers will discover that Linux system is a lot more appropriate in its
different scripting languages when compared with any other platform. It's
numerous languages for example Perl, MySQL, and PHP. Linux can supply
these languages if a specific site wants them.
Not simply is a compatibility of this reseller hosting program dependable, but
it is also very successful.
Being a Linux reseller web hosting client, you'll also have the advantage of
utilizing some kinds of databases such as MySQL, mSQL, and PostgreSQL.
They may be successfully used to communicate effectively with any site for
speedy information access.
This kind of databases is created in a relational manner to ensure that they
perform effectively jointly to obtain the finest out of their overall
performance when working with every other and the site.
The Linux reseller hosting choice offers far greater stability and also
protection to its buyers in comparison with any other competing server
programs.
Being open source software, it's stabler when compared with others, and it
has, as a result, become a server system of option for professionals
throughout the world.
5. HOST LOCATION
Are you searching Linux Cloud Hosting Servers then it is the better
appropriate solution if you wish to get your web site or perhaps e-commerce
website to get more efficient and also ensure excellent overall performance?
Linux Cloud Hosting Servers affords the clients with additional
reconfigurability and also modifications can also de bone fragments
according to their particular qualification. This hard drive server provided for
you enhances your sites overall performance plus delivers a lot more
management on the processing assets offered.
Linux server software makes use of the most recent technological know-how
that allows every person to successfully work their very own type involving
Linux and also delivering these using superior overall performance, tougher
reconfigurability and also superior supply routes.
100 % Uptime is a confirmed this means your blog will be working
successfully continuously with virtually no lagging. Regarding making
certain your blog is usually about back-up server Auto-failover function is
present.
Regarding ensuring utmost stability state-of-the-art, DDOS Safety is
provided with Linux server web hosting service. Geographically repetitive
DNS and also clientele are forwarded to 8 transit companies.
Linux Shared Web Hosting sustains the most recent and reliable web hosting
variations similar to Fedora 7, CentOS 7, Ubuntu age 14. 04 LTS and also
Debian 7. 8. The two server and also PC features involving OS are provided
towards the clients. These pre-installed hosts are instantaneously deployed
which allows clients to work with these in their particular web hosting
service offer.
Committed help workers are present that can present specialized alternatives
if you're facing any problem together with your web site. Any common and
also wide understanding bottom can be provided towards the clientele to
guide these using easy requests.
Customers are provided using personal hard drives that have identical
creating to order as being a physical server. Linux web hosting service
software allows your hosts to plug towards the web by using gigabit uplinks
involving Internap's carrier.
Newest section variations are supplied so that clients might have entire
management. Internap's
The standard VPS web hosting service is now no more some preferred choice
because the carrier's networks slice up the specific hosts for them to easily
share these relating to the clientele.
VPS companies employ container technological know-how to segregate this
numerous end user on a single discussed Linux type which usually reduces
this operation and also productivity.
6. NETWORK CONNECTIONS
uname
uname abbreviates the term “UNIX name”. The command displays system
information such as the exact name and version of the Linux kernel and the
hostname of your computer.
The image below shows the call of the uname command with the parameter -
a (short for --all). The output contains the name of the operating system
(Linux), the hostname (debian95), the kernel version and its build date (4.9.8-
7-amd64 #1 SMP Debian 4.9.110-1 (2018-07-05)) as well as the architecture
of the system (x86_64).
uptime
This command shows how long the system is running. It displays the current
time (07:36:47) followed by the uptime in hours (21:56), the number of
logged in users (1 user) and the average load (load average: 0.47, 0.43, 0.29)
for the last 1, 5 and 15 minutes.
In order to see the uptime in a nicer way, use the option -p (short for --
pretty). The image below displays a more human-readable version of the
information. The system is up 22 hours and 3 minutes.
ip
The ip command (along with the two keywords address show) displays the
current network configuration. The image below shows the loopback
interface (lo) and the ethernet interface (enp0s3). The ethernet interface is
configured with the IP address 10.0.2.15.
ping
ping sends ICMP network packets to the given IP address or hostname, and
displays the turnaround time. The image below demonstrates this for the host
http://www.google.com.
E. NETWORK AND SYSTEM INFORMATION
If you are going to start using Linux, one of the first things that you will need
is a good selection of software. In fact, many people stick with operating
systems they hate, simply because they are hesitant to give up their favorite
applications. All of the software listed below is completely free, and free to
distribute to your friends or family. That should help to convince you that
using Linux is a great idea.
You can actually run Windows software in Linux, using a program called
Wine. However, you will basically be making your computer pretend to be
using Windows. If you would prefer to use dedicated, and often more
reliable, methods — you are going to need some great Linux software.
1. NETWORK CONNECTIONS
If you are used to staying in touch with people on your computer, it’s
important to keep that functionality when you swap over to Linux. Here are
some good IM applications that you can try:
2. WEB BROWSING
If you are using a computer these days, you probably need to be online, in
order to be productive. Luckily, you have plenty of choices for Linux web
browsers. You can even use the most popular browsers in Linux, so you
won’t have to settle for something else.
Here are some great Linux web browsers that you can try:
● Firefox. This is one of the most popular web browsers for Linux users.
There are faster options out there, as well as newer ones, but Firefox is
considered one of the best.
● Chrome. You will need to download this from Google, as it won’t be
in the software repositories. However, you can use Chromium instead, if you
insist on using the repositories. This is the number one web browser at the
moment, and you will glad to know that Google fully supports Chrome for
Linux.
● In-built browsers. Whatever version of Linux you choose, it will
almost definitely come with a web browser, and that might even be Firefox or
Chromium. If you are not fussy about what you use, and just need to check
websites every now-and-then, you might be happy to use a default browser.
3. EMAILS
If you need your computer for work, you will probably want a good email
client. Windows users will probably be familiar with Outlook, but there are
some good alternatives for Linux.
6. GRAPHICS
One of the most widely used tools in the business world is Microsoft Office.
Not long ago, if you were to apply for an office job without any knowledge
of MS Office, you just might be laughed out of the room. This might still be
the case in many companies. However, the days when MS Office was the
one-and-only office suit are in the past.
Here are some great alternatives for Microsoft Office that run on Linux:
Host Resolutions
One thing you have to keep in mind about this is that you should use the
syntax gethostname() so the standard library could make the right call. This
also happens when you’re trying to look for the name of a certain part of the
program, and when you want to use it for larger applications. It’s almost the
same as python as you could code it this way
Linux Sockets
What you have to understand about Linux is that it is an Open System
Interconnect (OSI) Internet Model which means that it works in sockets (). In
order to establish connections, you need to make use of listening sockets so
that the host could make calls—or in other words, connections.
IO Network Models
In order to get peer information, you have to make sure that you return both
TCP and IP information. This way, you could be sure that both server and
client are connected to the network. You could also use the getpeername()
socket so that when information is available, it could easily be captured and
saved.
To accept information, let the socket LinuxAcceptor::accept() be prevalent
in the network. This way, you could differentiate actions coming from the
server and the client.
Linux and its Sockets
You also have to understand that you can code Linux in C mainly because
they both involve the use of sockets. the socket works like a bridge that binds
the client to the port, and is also responsible for sending the right kinds of
requests to the server while waiting for it to respond. Finally, sending and
receiving of data is done.
At the same time, the Linux Socket is also able to create a socket for the
server that would then bind itself to the port. During that stage, you can begin
listening to client traffic as it builds up. You could also wait for the client at
that point, and finally, see the sending and receiving of data to happen. Its
other functions are the following:
socket_description. This allows the description of both the client and the
server will show up onscreen.
write buffer. This describes the data that needs to be sent.
write buffer length. In order to write the buffer length, you’ll have to see the
string’s output.
client_socket. The socket description will also show on top.
address. This is used for the connect function so that address_len would be
on top.
address_len. If the second parameter is null, this would appear onscreen.
return. This helps return description of both the client and the socket. This
also lets interaction become easy between the client and the server.
server_socket. This is the description of the socket that’s located on top.
backlog. This is the amount of requests that have not yet been dealt with.
You could also put personal comments every once in a while—but definitely
not all the time!
CHAPTER 9: QNA FOR BEGINNERS
QUESTIONS
QUIZ
1. What is Reading Mode?
2. What is Reading List?
3. What is Increased download protection?
ANSWERS
1. It is another new addition to Microsoft Edge which was taken from more
modern browsers like Firefox and Safari. This option, available at the top of
the screen at all times will allow you to take any article you are reading and
separate it out from the website it is a part of which means you leave all of
the ads and other filler out of the equation. You will know the page you are
on can be seen in Reading Mode if the book icon animates and starts flipping
its pages. The settings menu allows you to modify the way Reading Mode
looks with a variety of sizes and settings to suit your current needs.
2. Despite the similar name, the Reading List feature has nothing to do with
Reading Mode, instead it functions similarly to a Favorite’s list allowing you
to pare down your Favorite’s into even more specific categories. Adding a
site to your Reading List is done from the same star icon as adding an item to
your Favorites but will show a thumbnail of the page when saved. To view
your Reading List, you click on the button next to the star icon in the top
right of the page. Clicking on this icon will display all of your reading list
items as thumbnails while choosing one will display the same icon but larger
at the top of the page. These pages can also be configured to appear on the
New Tab page along with your most frequently visited sites.
3. The downloads page is much the same as those found in other modern
browsers, it shows the files you have download and lets you interact with
them. What sets Microsoft Edge apart however is that when you begin
downloading a file it will tell you if that file is rarely downloaded or
potentially harmful to your computer.
4. While you are using Microsoft Edge, at any point you can select a portion
of text and right click or hold down on it to find the option to ask Cortana for
more information on the topic. This will open a sidebar with information on
the selected topic generally from Wikipedia. While browsing Cortana may
also make you aware of Windows Apps that relate to the site you are
viewing, provide directions and menus for restaurants whose site you are
viewing and provide coupons for products depending on the website.
5. While viewing a website in Microsoft Edge you now have the option to
make notes on a webpage and then share the results online. To do this you
click on the pen-marking-up-paper icon which will cause the upper part of
the browser to turn purple and add additional options including a pen to write
notes, an eraser, a highlighter a tool for writing more structured notes in
boxes and a cropping tool. These tools all work with either a mouse or a
touch input. Once you have finished making notations you can then save your
work and share it everywhere from Pinterest to Microsoft OneNote. If you
share the results through OneNote you will also have the option to give others
the opportunity to edit what you have done adding another level of
interactivity to group projects undertaken online.
6. As of January 2016 Microsoft Edge does not yet support extensions which
means common browsing tools such as ad blockers or password managers
will not yet work. Microsoft has promised that extensions are coming though
and a select group of extensions has been confirmed for an upcoming
Windows Insider build.
7. Additional common features not yet found in Microsoft Edge as of January
2016 are the abilities to some window or video from certain streaming sites
including Vimeo full screen. You will not be able to right-click an image to
perform some functions including making an image your desktop. Finally,
you cannot open a group of favorited websites all at once with only a single
click. The amount you use these features will no doubt affect your decision
when choosing whether or not to switch browsers.
8. This will be the version of Windows 10 that most people will use. It boasts
the fewest features and the cheapest cost. This version of Windows will run
on personal computers and laptops
9. This version of Windows 10 will be used by technical users and small
businesses and will contain more features than the Home version.
10. This version of Windows 10 will be used by large corporations and will
have features that reflect this fact.
11. This version of Windows 10 will be prorated for schools and contain
additional educational software.
What is Windows 10 Mobile? This version of Windows 10 will function
similarly to Windows 10 Home though it will have a mobile specific
interface. Windows 10 Mobile will be available on Lumina phones to start
with plans for additional options in the works.
12. This version of Windows 10 will be similar to Windows 10 mobile but
created with business use in mind.
13. IOT stands for internet of things and this version of Windows 10 is
designed to run on industrial equipment such as ATMs or cash registers.
14. When you first boot up the Windows 10 OS after successfully installing it
one of the first things you will notice is the new Start menu. Unlike Windows
8, which did away with the commonly known start menu (before public
outcry brought the button back at least) for a full screen version. Windows 10
learned from the mistakes of the past and brings back a more familiar start
menu which at the same time still takes a few cues from Windows 8.
The new start menu will bring up a modified version of the traditional
expanded menu. It will provide a list of commonly used applications
(programs are called applications now) which sit above the old standards of
settings, file explorer and an option to turn off the device. User’s will have
the option of storing their ten most used applications on the start menu for
easy access. The Start menu also features a search function that works much
the same as before except that now it is also connected to Bing so your search
will show websites as well as content stored locally.
15. The big push for Windows 10 is to unify all of the disparate Windows
platforms and Tablet Mode is a big part of this. Available under settings, this
option will switch the standard Start menu into a full screen version
reminiscent of Windows 8. This mode will turn on automatically when it is
running on a tablet that disconnects from a dock. When this happens the Start
Menu becomes full screen and transforms into the main way to interact with
your device. The same is true for the Windows Store, the Applications Menu
and the Settings Menu. While you will not be able to access the desktop
directly in this mode you can still access the desktop folder.
16. The Cortana virtual assistant is one example of the Windows Phone
interface bleeding into the primary OS. This feature allows users to ask their
OS questions the same way they would when using their smartphones.
Cortana is immediately available when you log in to Windows 10, to ask it a
question, simply click on the search icon in the lower left corner of the screen
and type a question to hear an answer or if you have a microphone connected
to your device you can click on the microphone option.
17. The Windows Store survived the transition to Windows 10 and
applications downloaded through the service will now feature the ability to be
resized along with the standard suite of minimization, maximization and quit
options traditional programs enjoyed. Applications purchased in the
Windows Store will be available across all the Windows 10 devices the user
connects to.
18. In previous versions of Windows, the programs you had open on multiple
monitors showed up on every taskbar making it sometimes difficult to find
what you need. The taskbar now includes an option to filter the apps that each
taskbar shows.
19. Yes, you read that correctly, after more than two decades the command
prompt is getting added functionality. You will now be able to copy and paste
data into the command prompt using the keyboard shortcuts.
20. Perhaps one of the most useful features to automatically move between
devices running Windows 10, the Calendar Application can pull data from
multiple accounts to succinctly sum everything up in one place. The calendar
will pull information from your Windows Live account as well as you
Windows 10 Mail account as well. Both applications are more responsive and
easier to use while at the same time cutting the fat found in earlier versions.
Both applications support their Google equivalents if you prefer and resize
themselves depending on the version of the platform they are operating on.
CHAPTER 10: TIPS AND TRICKS
Linux is the best Operating System So Far
Even though Linux has been in the market for a long time, offering a better
deal than most operating systems, a lot of people are still in the dark as to
why they should actually trade the operating system they have been using
over time for Linux. The question you should be asking yourself now is this:
is the operating system that you have been using all along good enough in all
ways? Are there some errors that you wish were improved? Is it working for
you just fine? If you were to answer these questions honestly, youwould
realize that indeed you have not been getting a good deal from your choice of
operating system.
Linux is here to help in ways that other operating systems have failed in order
to ensure that computer users are using their computers with minimal or no
problems at all.
Some of the problems that you have probably been facing with other
operating systems are viruses, malwares, costly computer repairs, slow
downs, computer crashes or even licensing fees. You will agree that these are
real problems that can stress a computer user so much. If you want nothing to
do with such issues in the future, Linux is the operating system to go for!
With Linux, you do not have to live constantly with the fear of losing your
data as a result of virus invasion or computer crash. You do not have to worry
about taking your computer for a cleanup yearly for it to work well for you.
This is a great relief for so many people considering how useful computers
have become in our lives lately. We are dependent on computers for
practically so many things in our lives and with a problem-free computer, you
can achieve a lot all the time.
Why Linux?
a) Zero cost of entry. Linux is absolutelyfree. You can install Linux on as
many computers as you have without paying anything for it. There is no
server or software licensing as in the case of other operating systems.
b) Easy installation. This is a very easy to install operating system. Newbies
will not have a hard time installing it as well. Installing a full server with
database server involves a few clicks and only a few commands, which is
very easy and straightforward.
c) It is the most reliable operating system. It will never fail you! You will
have no problems on your computer, and your data is safe as long as you are
using Linux. This is a stress-free operating system for any computer and
device user all over the world.
d) As a system administrator, you will have a great time using Linux. You
will face zero issues with servers. In fact, once you install the system, you
will forget all about it because no problem will ever come up. Even if one of
the servers will require restarting or reconfiguring or even upgrading, the rest
of the servers will not be affected. This is how easy working with Linux will
be for you.
e) Zero troubles for as long as you will use Linux is a guarantee. Many
people will attest to using Linux for so many years without experiencing even
random computer slowdowns or having to battle with viruses and malware.
These will be problems of the past once you start using Linux.
1. The freedom for the user to run the program for whatever
purpose they may have.
2. The freedom to the user to distribute the program to help
out another computer user.
3. The freedom for the user to learn everything about the
program and to even change it, if he so wishes, so that it can
serve him better.
4. The freedom to distribute the copies of the user’s modified
program to any user that he wishes to share it with.
This is an operating system that is created by the people and for the people. It
is a system that will give you all the privileges and freedom to enjoy working
on your computer with no issues at all.
Linux vs Windows
Note: Even if it is said that Linux is safe from virus and malware, it is
important for users to take necessary safety precautions just to be safe. If you
are a system administrator, do not relax and wait for the invasion to happen.
Put safety measures in place to prevent future regrets.
CONCLUSION
Linux operating system is the most dependable, secure, and reliable platforms
for the servers as well as desktops. It is an operating system that is gaining so
much popularity lately because of the great benefits it has for users. This is a
system that is likely to give you a stress-free time as you work on your
computer. Computer crashes, for instance, are a thing of the past if you are
using Linux.
What you get all the timeis a trouble-free desktop, servers that are always up
and minimum support requests, which is what many computer users and
system administrators need and deserve.
There is a wide range of Linux versions to choose from. The number of
Linux distributions does not stand at what is mentioned here. The number is
steadily growing as the developers try to improve on the distributions that
have already been released. What you are assured of is that you will get a
distribution that will meet all your needs from the distributions that are
already in the market.
Linux is easy to customize, ensuring that whenever you are using the system,
you are able to create an interface that completely meets your needs.
It is time to switch to Linux if you are still using operating systems that are
constantly giving you problems. This is a system for all people; both new
users and expert computer users.
JAVA
The Practical Beginner’s Guide to
Learn Java Programming in One
Day Step-by-Step
Steve Tudor
Text Copyright ©
All rights reserved. No part of this guide may be reproduced in any form
without permission in writing from the publisher except in the case of brief
quotations embodied in critical articles or reviews.
Legal & Disclaimer
The information contained in this book and its contents is not designed to
replace or take the place of any form of medical or professional advice; and is
not meant to replace the need for independent medical, financial, legal or
other professional advice or services, as may be required. The content and
information in this book has been provided for educational and entertainment
purposes only.
The content and information contained in this book has been compiled from
sources deemed reliable, and it is accurate to the best of the Author's
knowledge, information and belief. However, the Author cannot guarantee its
accuracy and validity and cannot be held liable for any errors and/or
omissions. Further, changes are periodically made to this book as and when
needed. Where appropriate and/or necessary, you must consult a professional
(including but not limited to your doctor, attorney, financial advisor or such
other professional advisor) before using any of the suggested remedies,
techniques, or information in this book.
Upon using the contents and information contained in this book, you agree to
hold harmless the Author from and against any damages, costs, and expenses,
including any legal fees potentially resulting from the application of any of
the information provided by this book. This disclaimer applies to any loss,
damages or injury caused by the use and application, whether directly or
indirectly, of any advice or information presented, whether for breach of
contract, tort, negligence, personal injury, criminal intent, or under any other
cause of action.
You agree to accept all risks of using the information presented inside this
book.
You agree that by continuing to read this book, where appropriate and/or
necessary, you shall consult a professional (including but not limited to your
doctor, attorney, or financial advisor or such other advisor as needed) before
using any of the suggested remedies, techniques, or information in this book.
INTRODUCTION
Java is a general purpose object oriented programming language. It follows
“write once, run anywhere concept” which means Java code once compiled
on one machine need not be re-compiled anywhere else and can potentially
run off the shelf. This is possible because Java is designed to be a platform
independent language.
In 1995, the first stable version of Java was released; originally developed by
a Canadian computer scientist James Goslin while working at Sun
Microsystems. Sun Microsystems was acquired by Oracle Corporation in
January 2010. Hence all Java trademarks are owned by Oracle Corporation
at the time of writing this book.
Why Java?
Java is one of the most popular programming languages today with ever
increasing demand in the IT industry. It is extremely popular and sometimes
the most obvious choice for developing web applications and web services.
There is a good chance that an average computer user comes in touch with
technologies offered by or implemented using Java. In fact, some of the most
common applications that we use on a day-to-day basis such as Gmail,
ThinkFree Office, Vuze, etc. are developed using Java either in part or
completely.
Using Java, we can develop desktop applications, web applications, video
games, mobile applications, etc. In fact, Android application development is
primarily done using Java as it is the official android application development
language alongside Kotlin.
In order to learn Java, no prior programming experience is necessary but is
advisable. Having the basic knowledge of C/C++ will help a great deal in
learning Java. Having said that, you should be comfortable with using your
system and shall have some experience in using Command Prompt on
Windows and Terminal on Linux/MAC. If you are not comfortable with
using Command Prompt/Terminal, it is a good idea to learn your way around
these tools before beginning Java development.
Java Application Types
Although the Java framework keeps advancing, Java application types
Desktop applications:
Desktop applications are designed for Windows, Linux and MAC. Can be a
console based application that runs from a Command Prompt/Terminal or can
have a GUI. These are also known as standalone applications.
Web applications/Web services:
Web applications/services are server side applications. Users normally
interact with these applications using a browser.
Mobile/Embedded applications:
These are the applications that are meant for mobile or embedded devices.
Chapter 1 : GETTING READY
While Java is an exciting language, it is easy to get lost in the maze. This is
because to create programs using the language, you need to install a few
computer peripherals and programs. This is before you can write a single
code. The tool (software) also Interface development interface (IDE) we need
to write our code is NETBEANS, which is the most popular IDE for writing
programs in Java. Here is the kicker; while it is easy to navigate to the
NETBEANS URL and download the program, things are never that easy. For
NETBEANS to operate (load up) on your system, you need to install some
necessary Java files and components. First, you need the Java Virtual
Machine.
Java Virtual Machine
We have already stated that Java is independent from any platform and will
run on any modern operating system; this component is the reason why Java
does not care what OS you are running. Java Virtual Machine is the program
that interprets/processes your code correctly. The program is one of the
mandatory programs you must install before you can create any Java code or
program. You can download the program from the relevant website.
P.s. Across the web, there are many sources of Java related programs. I
suggest you only download all your files from the official Sun Microsystems
website, Java’s parent company.
Once you are on the website, you can proceed to download the Java Virtual
machine also known as JRE (Java Runtime Environment). Additionally,
while on the website, you can check whether your computer is running a
version of JRE by clicking on the relevant “do I have Java?” link. The
resulting search result will tell you the version of JRE running on your
computer, if any.
If you do not have the program installed, install it and restart your computer.
Next is the Java Software development Kit
Java Software Development Kit
After installing the JRE, we are not yet ready to write our first code. At this
point, all we have done is installing the support software needed to run Java
programs on your computer. You need a tool to write and test code, the
Software Development kit, which you can also download from the Sun
Microsystems official website. I suggest that you download the Java SE
(standard edition) and additionally, the JDK 6 that you will find on the Java
SE page. When you navigate to the JDK 6 page, you might get confused
because there are many options. Depending on the IDE you are using, you
can select the relevant option. In our case, we are using NETBEANS so you
should locate the following JDK 6 Update X with NetBeans 6.x.
Click on download and head over to the next page to select a download file
relevant to your operating system. Download and install the file. It is
important to note that the file is a compressed file of over 130 bytes so you
should ensure your internet connection is working while you perform the
download, otherwise the file might corrupt halfway through the download. So
far, we have done everything right. We have downloaded and installed the
necessary environments and software needed to write your first code.
However, before we launch the applications we have installed, we need to
understand the inner working of the world of Java.
Introduction to JDK and NetBeans
In Java, you write your code on a text editor. However, in NetBeans, there is
a special area designated for writing your code. The code you write at this
.
point is “the source code” and you save it with the file extension .java After
you create the source code, you have to turn it into Java Byte Code by
running it through the JaVac program; we call this process “compiling”. The
JaVac program then creates a .class extension file if there are no errors in the
computing process. This (.class) file is the file you run in the Java Virtual
Machine.
Any program you run on NetBeans will run on the output window that you
can find at the bottom of your screen directly underneath your code. This
design is logical because, with the output window readily available, you do
not have to call up the console window or the terminal because in NetBeans,
the output window plays the role of the console.
In NetBeans, you can run a program in a number of ways with the easiest
being, pressing the F6 key on your keyword. You can also use the menus
found at the top of NetBeans to run the program. In the menus, locate the
menu Run and execute the run main project option.
Here is the above explanation in steps
Figure 3
After renaming, the class created will bear the name “First_Project”. Notice
that the project class name has a capital “F” at the start and a capital “P”.
Additionally, the package name has the name “first_Project’ with a lower
case “f” and “p”.
The Project Location text box will appear and offer you the option of
changing the default save location. If you would prefer to save the file on any
other location other than the default area, you can do it here. Additionally, the
NetBeans program will also create default folder containing your project
name in the same default location you opt for. Clicking on the finish button
will prompt NetBeans to work in the background and create the necessary
files for use. When it is through, the system will return you to the IDE where
you can see and locate all your projects. If by any chance the project area
found in the top left corner is not visible, you should navigate to the
window>project tab on the menu bar
Figure 4
You can expand your project by pressing the +symbol, after which, your
project will look something similar to the figure below.
Figure 5
You should then click the + on the source package to expand it and peek at
your project name. We are doing this to see our Java file source code. This is
shown in the figure below.
Figure 6
The source code (the same source code) should appear on the right in the text
area and will bear the name First_Project.java. Sometimes, the code window
will not display. This is not something to be overly concerned about, simply
click and press enter on the First_Project.java available in your project
window to call up the code window; after this, you can start working on your
code. Here is a sample image of the coding window. The @author you part is
where your name as an author will appear.
Figure 7
You should note that the class bears the name First_Project.
How so you wonder. After all, this is actually the same name as that of your
java source file available on your project window, First_Project.java. There is
a simple explanation for this. The complier demands of it. Once you run a
program, the class name and the source file must match for the compiler to
work. What does this mean? It means that if your .java file bears the name
first_Project while the class bears the name First_Project, you will receive a
compile error simply because the letter class do not match, i.e. the first one is
lower class while the second one is upper class.
Remember that our whole project bears the name first project as a working
experiment; you can name your package any other name such as
anyprogram the name package does not necessarily have to bear the same
name as the java source file or the class found in the source file. The only two
that must match are the name of the class and the java source file.
We have now looked at the basics of creating a java source code within the
Java environment. Let us move on swiftly.
Basic structure of a java program
After we have created a new project in the NetBeans program, you may
notice that some of the code is grey and contains many asterisks and slashes
like in the figure below.
The Structure Of Java Code And How To Run Programs
In the figure, you should notice the package name comes first. Additionally,
you should note that a semicolon is what ends the line. The semicolon is
important and if you omit it, the program will not compile.
package first_Project;
Next is the class name
}
Ideally, you should think of the class as a code segment. However, Java
dictates that you tell it where the code segments start and end. You can
achieve this by using curly brackets. You can use the left curly bracket at the
start of a code, and use the right curly bracket to end the code {this is an
example of a curly code segment} you should however note that anything
that goes inside the left and right curly is part of the said code segment.
Additionally, anything inside both the left and right curly for the class is in
fact, a code segment. Here is what I mean:
(
public static void main String[ ] args ){
}
More important than anything else is the word “main”. Why? Because each
time any Java program boots up, it first looks for the method bearing the
name ‘main’. Simply put, a method is a piece of code. The program then
executes codes within the curly as part of the main. There are possibilities
that you will get an error message within the Java program if your code does
not have a main method. However, since this is the main entry point for your
program, there is little chance you will omit it.
The public part of the code (the blue part) simply means that the method is
viewable outside that class. On the other hand, static means that the creation
of a new object is not necessary while void means that, there is not returnable
value and the command gets on with it.
Command line arguments are the parts between the round brackets of the
main. Except for the technical bits, you should not concern yourself with this.
You should only strive to remember that our class is First_Project, which
contains the method main and that both the class and the main use their own
set of curly brackets. You should also remember that a huge part of your code
is part of the class First_Project.
How to download and install Java on Linux, Windows and
Mac.
Check out the figure below.
Figure 10
In the NetBeans tool bar, you will notice a “green play” arrow; you can use
this to run a program.
Figure 11
You can also run a program by navigating to your projects window. This is
especially effective in ensuring that the correct source code is running. To do
this, you need to click on your java source file contained in the project
window and then right click for options. Execute the run command. See
figure below.
Figure 12
If you use any of the program execution methods above on our code so far,
you should get something similar to figure13 below on the output window
Figure 13
In figure 13 above, you can see that the first line is the run command. The
second is our code “My First Project.” If there is something you are not sure
of and would like to run the code again, you can simply press the “two almost
fast-forward green arrows” visible on figure 13 above.
Chapter 2: JAVA BASICS
Java tokens
Java tokens are the values that are smaller than other integers. These numbers
are going to fall between the value of -32768 and 32767. The code that I have
been using is not going to work for shorts, instead I am going to need to use
the short function so that I can make sure that the values are going to fall
between the set limitations.
Large values are going to be stored inside of a double value along with
floating point values. A double does not have to be used if I can use a floating
point. As I am storing a floating variable. I am going to need to put a letter at
the end of my value amount. This value should be f because it is a floating
point number.
Keywords
In Java, the Boolean type refers to false or true values. Java finds out if it is
true or false using the reserved keywords. Therefore, an expression Boolean
type will assume one of these values. An example to demonstrate include:
There are a few things to note about this program. First, the println(),
displays a boolean value. Secondly, the boolean values control the flow of an
if statement. You don’t need to go the long way in writing the boolean type
this way: if (b == true)
The result shown by the operator such as < is boolean. It is one of the reasons
why we have the expression 11 > 8 showing the value true. In addition, the
other pair of parentheses near the 11 > 8 is important since plus comes before
the >.
Identifiers
The top layer of the diagram above is for the identifier or name. This top
layer is the name you give to a class. The name should specifically identify
and also describe the type of object as seen or experienced by the user. In
simple terms, the name or identifier should identify the class.
Operators
Java has an extensive list of operator environment. If you are wondering what
an operator is, you can look at it as a symbol which conveys a specific
message to the compiler to carry out a logical or mathematical operation. In
Java, you will interact with four classes of operators. The four classes
include:
Logical operator
Bitwise operator
Relational operator
Arithmetic operator
Like other computer languages, Java has a defined list of additional operators
to take care of certain specific scenarios.
When it comes to learning JAVA programming language, or any
programming language for that matter, there are five basic concepts you must
understand before you get started. These five basic concepts include:
1. Variables
2. Data Structures
3. Control Structures
4. Syntax
5. Tools
Each of these concepts will be thoroughly explained on a beginner’s level to
ensure that they are understood.
Separators
They are not suitable for high-level abstraction: note that a lot of these
programs make use of low-level constructs which are primarily used for low-
level abstraction. The usual approach with these programming languages is
that they focus on the machine – how to make a computer do something
rather than how these functions can help solve the issues of a user. These
languages deal with the minute details, which is already beyond the scope of
high-level abstraction, which is the more common approach that we see
today. In low-level abstraction, data structures and algorithms are taken
separately whereas these are taken as a whole in high-level abstraction.
Literals
When it comes to literals in Java, we mean the fixed values which appear in
the form in which human beings can read. We can say the number 200 is a
literal. Most of the time, literals can be constants. Literals are important in a
program. In fact, most Java programs use literals. Some of the programs we
have already discussed in this book use literals.
Literals in Java can fall on various primitive data types. The manner in which
every literal is shown is determined by its type. Like it was mentioned some
time back, we enclose character constants in single quotes such as ‘c’ and
‘%’.
We define literals in integers without involving the fractional part. For
instance, 12 and -30 are integer literals. A floating point literal should contain
the decimal point plus the fractional part. 12.389 is a floating literal. Java
further permits for one to apply the scientific notation for the floating point
literals. Integer literals contain int value and anyone can initialize them with a
variable of short, byte, and char.
Comments
When this occurs, we call the grey’s comments. In the running stages of the
program, the grey’s (comments) are moot. This is to mean that you can use
the comment feature to state or explain what the code you are creating wants
to achieve. You can achieve this by typing two slashes and then the comment.
Here is a sample.
//Place your single line comment here
You can have more than one comment line by doing either of the following:
//We are going to
//spread the comments into two
Or
/*
This comment spreads over two lines
*/
If you look at the comment above, you will notice that it starts with /* but
ends with */
Additionally, if you look at the previous image (figure 8) you will notice that
there are comments that begin with a single forward slash and two asterisks
(/**) but end with one asterisks and one forwards slash; this is called a
Javadoc comment.
Chapter 3 : VARIABLES
what are variables
A variable, on the other hand, is an "object" that contains a specific data type
and its assigned or received value. It is called a variable because the value
contained can change according to how it is used in the code, how the coder
can declare its value, or even how the user of the program chooses to interact
with it. A variable, in short, is a storage unit for a data type. Having access to
variables allow programmers to conveniently label and call stored values at
hand.
Types of variables in Java
Java requires the programmer to use declaration statements, lines of code
used to declare variables and define them by specifying the particular data
type and name. Java has a specific way of treating variables, by defining
variables as containers that contains a certain type and value of information,
unlike some languages such as python, which only requires a declaration of a
variable, and the variable can dynamically change its type; Java variables are
static, which retain their type once declared.
Int number = 20;
Boolean completed = true;
String hello = “Hello World!”;
The syntax in declaring is seen in the previous examples, with the type of the
variable coming first, then the name of the variable, then the value. Note as
well that the declaration statement can be composed of multiple declarations
in one line, as in the following example:
Int number = 20, Boolean completed = true, string hello = “Hello World!”;
Java variables can be declared without any value at the start; in cases such as
these, Java chooses to declare these variables with a particular default value,
for example:
Byte a;
Short num;
Boolean answer;
Will result in the values 0, 0, and false, respectively. A more complete list of
default values is as follows: the byte, short, int, and long data types will all
result in a default value of 0, while the float and double data types will have a
default 0.0 value, the char data type will result in ‘u\0000’ value, a string or
any other object will have a null default value, and all Booleans will begin
with a false default value.
In Java, variables are static when declared, meaning that the programmer
must define the data type that the variable will be containing. To illustrate, if
we wish to use a variable num to store a number, we would first have to
declare the variable: "int num", before we can assign a value, such as "num
= 10".
The process above is usually known as and referred to as an "assignment
statement", where a value is assigned to the variable as declared by the
programmer. However, one prominent thing about how Java, and in fact how
most programming languages, works is that in the assignment statement, such
as in our example of num = 10, the actual value stored is the one on the right
side of the equals sign, the value of 10, and num is just the "marker" to call
that stored value. This is why there are many Java programmers that tend to
prefer the jargon of "getting" a value rather than "assigning", though for the
most part, they may be employed interchangeably, and outside of some rare
scenario, function mostly the same way.
Note, however, that once values have been assigned to variables, functions
need to be carried out in order for the data inside that variable to change its
data type.
Naming a variable
Creating variables is an easy task, especially given how Java programmers
tend to create and name them after the data type or the purpose of what the
variable will store. However, there are a few rules when it comes to naming
these variables, else Java will not recognize it and an error message will
result. The main restrictions around variable names are that it should not
begin with a special character such as an underscore or a number. However,
variable names can consist of characters such as letters and numbers, and
even an underscore, provided that the underscore is not placed at the start. No
other characters may be used, such as the # or even $, as these special
characters have different uses in Java, and thus will not be recognized in a
variable name.
While those are the major rules, here are some tips when it comes to naming
variables. The variable name should be descriptive, as in longer codes it may
be difficult to recall just what "x" is for. Having a variable name such as
"count" or "output" is much easier to recall as compared to having a generic
"x" or "y" and will help in avoiding confusion. In addition to being
descriptive, variables will also be easier to use if their names are kept fairly
short. While having a variable name such as
banking_information_account_records is very descriptive, typing it
repeatedly as needed in the program will get exhausting, and having longer
variable names increase the chances of typographical errors, which will lead
to bugs in the code, resulting in a run - time error or the code not working as
intended, or working, but introducing bugs along the way. Note as well that it
has always been a practice for Java variables to be written in all lower – case
letters, and while there is no restriction on capitalization, keeping things in
lowercase simplifies things, as a missed capitalization may result in the
variable not being recognized, as Java reads an upper – case letter as an
entirely different character versus a lower – case letter.
Java primitive types
Method Naming Conventions
We shall revisit the naming conventions in Java since you will be using
member methods. Methods in Java programming perform operations, they
also receive any argument provided by a caller, and it can also return a result
of an operation to a caller. Here’s the syntax for declaring a method:
[Access Control Modifier] Return Type methodName ([set of parameters]) {
// body of the method
......
}
Here are a few rules to remember when you make the names for the methods
that you will write. Method names are always verbs or more specifically verb
phrases (which means you can use multiple words to name them). The first
word of the method name should all be in lower case letters while the rest of
the words should follow a camel case format. Here is an example:
writeMethodNamesThisWay( )
Now, you should remember that verbs are used for method names, and they
indicate an action while nouns are used for variable names, and they denote a
certain attribute.
Following the syntax for declaring a method and following the name
conventions for this Java construct, here’s a sample code that can be used to
compute the area of a circle.
A constructor will also implicitly return void – that simply means it doesn’t
have a return type. You can’t put a return statement inside the body of a
constructor since it will be flagged by compilers as an error. The only way
you can invoke a constructor is via the use of the “new” statement. We have
already given you several ways how you can invoke constructors in the
samples above.
Can constructors be overloaded too? Yes, they can. Constructors behave like
methods too so that means you can overload a constructor just the same way
you overload a method. Here are a few examples on how you can overload a
constructor. We use the Employee class and overload it using different
parameters.
Employee( )
Employee(int r)
Employee(int r, String b)
+ represents addition
- represents subtraction
* represents multiplication
/ represents division
% represents modulus
++ represents increment
-- represents decrement
Operators such as +, -, *, and / all perform the same function just like the rest
of other languages.
We have seen that JavaScript has the ability to work with numbers. Hence it
also has the ability to work with the operators that can be used with the
number data type. Let’s look at each of the operators in more detail.
Arithmetic Operators
These are operators that are used to work with numbers. The most common
operators are shown below, followed by an example of how it can be applied.
With this program, the output is as follows:
JavaScript Program
The first value is 5
The second value is 10
Addition operator = 15
Subtraction operator = 5
Multiply operator = 50
Division operator = 2
Increment operator = 6
Decrement operator = 5
Modulus operator = 5
Assignment operators
These are operators that are used to determine the value of conditions based
on the value of the operands. The relational operators possible in JavaScript
are given below.
If a condition evaluates to true, then a value of 1 is returned, otherwise a
value of 0 is returned.
With this program, the output is as follows:
JavaScript Program
The first value is 5
The second value is 10
Are the numbers equal = false
Are the numbers not equal = true
Is x less than y = true
Is x greater than y = false
Is x greater than or equal y = false
Is x less than or equal y = true
Logical Operators
These are operators that are used to determine the value of conditions based
on the value of the operands, where the operands are Boolean values. The
logical operators possible in JavaScript are given below.
With this program, the output is as follows:
JavaScript Program
The first value is true
The second value is true
The third value is false
x AND y = true
y AND z = false
z AND x = false
z AND z = false
The table below shows the logical operators based on the value of the
operands for the OR operator.
With this program, the output is as follows:
JavaScript Program
The first value is true
The second value is true
The third value is false
x OR y = true
y OR z = true
z OR x = true
z OR z = false
The following table shows the logical operators based on the value of the
operands for the NOT operator.
Assignment Operators
These are operators that are used to make assignment operations easier. The
assignment operators possible in JavaScript are given below.
Now let’s look at how we can implement these operators in further detail.
With this program, the output is as follows:
JavaScript Program
The first value is 5
The second value is 6
The value of i+j is 11
The value of i+=j is 11
The value of i-=j is 5
The value of i*=j is 30
The value of i/=j is 5
The value of i%=j is 5
Bitwise Operators
These are operators that are used to make bit operations on operands.
With this program, the output is as follows:
JavaScript Program
The first value is 5
The second value is 6
The value of x AND y is 4
The value of x OR y is 7
The value of NOT x is -6
The value of x XOR y is 3
The value Zero fill left shift is 10
The value Signed right shift is 2
The value Zero fill right shift is 2
Chapter 5 : ARRAYS AND STRING
What are strings
A string is a sequence of characters and can also be known as an array of
characters
In order declare a string in JAVA, you just use the keyword ‘string’
You then name your string whatever you would like
Then you place an equal sign after that
Then in double quotes, place whatever string you want to assign and print it
just the same as all the others:
String sample = “Welcome Ron ”;
System.out.println(sample)
String Methods
In the above example, there are two variables message and s of String type.
The statement message = s + “Ron”; will append the string “World” to the
contents of s and save it in message. Hence, message will now hold
“Welcome Ron”.
Arrays
An array is similar to a variable but it can store more than one value at a time
– the only condition being that even though you can store more than one
value in an array, it has to be the same type of values
For example, you would be able to store 10 integers in an array, but if you
wanted to store 5 integers and 5 doubles, you would not be able to do it
This is one way of declaring an array: int [] RonArray = {4, 62,1,54,3};
Another way is: int myinarray2[] = {4,62,1,54,3} This way is fine but it is not
the preferred way of declaring an array
There are three more ways of declaring arrays
1. int[] RonArray = new int[3];
2. int[] RonArray = {1,2,3};
3. int[] RonArray = new int []{1,2,3};
array methods
The section int [] RonArray indicates that the array is of the primitive
variable int declared with the name or reference RonArray. The square
brackets [] indicate that it is a reference to an array. The section new int[7]
indicates that a new array object is created. The number between the square
brackets means that the length of the array is equal to 7. The index of the
elements of RonArray consists of the numbers 0, 1, 2, 3, 4, 5 and 6. There are
seven elements totally. To find out the element for example at index 2, we
use the name of the array, and between square brackets the index of the
element: RonArray[2]. In our example, all the seven elements are equal to 0,
because they are not initialized. If an int type variable is not initialized its
value is by default equal to 0.
The program of example 1 writes seven zeros to the standard output:
0000000
The following code changes the value of the fourth element in the array to 11.
Remember that the first element index is 0.
intArray [3] = 11
Try to import the package java.util.Arrays of the Java standard API, to learn
how to sort the elements of an array.
Primitive types
Primitive data types are data types that Java has already defined for you. This
means that you can’t use them as names for variables, classes, etc. There are
only eight primitive data types defined in Java:
Making Arrays
You can make an exhibit by utilizing the new operator with the
accompanying statement:
RonArray = new datatype[sizeofarray];
The above declaration does two things:
● It makes an exhibit with the help of the new operator in the following
manner:
new datatype[arraysize];
● It relegates the reference of the recently made array to the variable
RonArray.
Proclaiming a array variable, making an exhibit, and doling out the reference
of the show to the variable can be consolidated in one declaration, as
appeared:
datatype[] RonArray = new datatype[sizeofarray];
On the other hand, you can also make clusters in the following manner:
datatype[] RonArray = {val0, val1, ..., valk};
The components of the array are gotten to through the record. Array lists are
0-based; that is, they begin from 0 to go up to RonArray.length-1.
Sample Implementation:
The declaration shown below declares an array, RonArray, makes a cluster of
10 components of double type and doles out its reference to RonArray:
double[] RonArray = new double[10];
Handling Arrays
Chapter 6 : INTERACTIVE
How to displaying output
The floating type represents fractional numbers. The floating types exist in
two types, the double and float. The double represents the double precision
numbers while the float represents the single precision numbers.
The double is applied frequently since functions of mathematics use double
value. For instance, sqrt() will output a double. You can check its application
in the code below. In this example, sqrt() has been applied to calculate the
longest side of a triangle when the length of the other sides has been
provided.
We need to notice in the example above that sqrt() belongs to the Math
class. But, notice the way the sqrt() has been used: first, it has been preceded
by the Math name. Now, for sqrt(), it is similar.
Converters
If you have programmed in another language, you might be thinking that
characters in Java are 8. No! Java has Unicode. What a Unicode does is to
define a set of characters which represents characters existing in the human
languages. The example below demonstrates:
Char th;
th = ‘Y’;
Still, if you want to display a char value by applying the println() statement.
This example will show you how to do it:
You should be able to note that the last else has not been associated with
if(j<20), but associated with the if(i==10).
IF … ELSE
If you don’t want to use two IF statements, there is another way -and IF …
ELSE statement.
So, we have two choices in this code – the user is either 18 or younger, or
older than 18. Change your code so it matches what is above and try it. You
should now see that the first message is printed out. Change the user variable
value to 20 and then run the code again. You should see the message that is
between the curly brackets for ELSE displayed in the Output window.
IF … ELSE IF
The first IF statement will test for the first condition, then we have the ELSE
IF, followed by parentheses, in between which goes condition two. If there is
anything that the first two conditions do not catch, it will be caught by the
last ELSE. Again, we have sectioned the code using curly brackets and each
IF, Else IF or ELSE has its own set. If you miss out any of these curly
brackets, you will get an error message.
Before you try out any more code, you must first learn about a few more
conditional operators. So far, you have used these ones:
&& - AND
|| - OR
== - HAS A VALUE OF
! - NOT
The first one, a pair of ampersand symbols, is used for testing two or more
conditions at once.
We are checking to see if a user is older than the age of 18 but younger than
the age of 40 – remember, we are checking what is in the variable called user.
The first condition, “greater than 18”; the second condition, “less than 40”.
Between those two conditions, we have the AND operator so the entire line is
saying else if user is greater than 18 AND user is less than 40.
Now run the program and test it again; before it runs you should already be
able to guess what is going to print. The user variable has a value of 21 so the
message that is between the else if curly brackets will show in the output
window.
Nested IF Statements
Look at where the curly brackets are – get one set in the wrong place or miss
one out and the code will not run. Nested IF statements might be a little
tricky but, really, all you are doing is narrowing the choices down.
Boolean Values
Instead of using int, double or string, you would simply type in boolean
(lower case b) and, after the variable name, you assign a TRUE or FALSE
value. Notice that we use a single equal sign as the assignment operator. If
you wanted to see if a variable “has a value of”, you would need to use a pair
of equals signs.
This time, we have used the NOT operator in front of the variable called user.
The NOT operator is indicated by the use of an exclamation mark, just one,
and it will be placed in front of the variable that you are trying to test. This
operator tests for negation, which means that it is testing for the opposite of
the actual value.
Switch Statements
Another way of controlling flow is to use a switch statement. This provides
you with the option of testing for a range of values for the variables and can
be used in place of complicated, long IF … ELSE statements.
Start with the word “switch” and then a set of parentheses. The variable you
are checking is placed between the switch parentheses and is followed by a
set of curly brackets. The rest of the switch statement goes in between the
curly brackets.
Chapter 8 : LOOPS IN JAVA
Looping statements allow your program to do something repeatedly for a
fixed number of times. There are two types of looping statements:
} while(condition);
The difference between the while and do-while statements is that the do-
while statement is guaranteed to execute the code inside at least once, while
the while statement has a chance of not executing the code inside at all.
2. for statements
for statements are more compact than while statements and is best used in
codes that have rather short conditions for iteration. Here’s the basic template
for the for statement:
for(initialize variable, e.g., ab = 0; condition, e.g., ab < 10; iterate variable,
e.g., ab++)
{
//do whatever is inside this block as long as the condition specified still
holds
}
Branching statements
There are three commands used for branching:
Congratulations! You now know how to store data, do stuff to it, and let your
program make decisions. You should now be able to create simple programs,
like a program that adds two numbers, and other operations. In the final
chapter we shall talk about the essential Java classes every Java programmer
should know. That chapter should wrap-up everything you’ve learned so far
and give you the power to learn new Java classes all by yourself.
.
Chapter 9: CLASSES AND OBJECTS IN JAVA
To become a professional Java programmer, you must understand the concept
of classes in Java. The class is the main part of any Java program. In other
words, it is the basis on which the whole Java language is created, and one
reason for this is that the class holds the features of an object.
Inside a class, you will find data defined as well as the code which executes
the data. The code exists in the methods. This chapter will take you through a
brief understanding of the classes, methods, and objects in Java. It is crucial
that you have a basic foundation of the above features so that you can know
how to write complicated Java programs.
The fundamentals of Class
Since the start of this book, we have been using Java class. You should have
noticed that every Java program has a class. Although we have been using
Java classes, the classes were simple and we did not take advantage of the
many features which a class comes with. Soon you will discover that the Java
class is even more efficient than what we have used previously in the
different programs.
So, let’s start by looking at the basics of a class in Java. We can look at a
class as a blueprint which determines the object properties. It defines in detail
the program data and code. And so, a class is like a template which describes
how you can create an object. It is vital to be elaborate about a class; it is a
logical abstraction. Methods and variable of a class are referred to as
members.
So far, we have used classes which come with a single main() method. Soon
you will learn how to build other methods, but I want you to know that the
basic style of a class is not the way the main() method is defined.
We only need the main() method in case our class as it is the beginning point
of our program. In addition, certain types of Java applications don’t need the
main() method.
Definition of a class
To reveal the concept of Java classes, we shall create a class which will store
information about vehicles. The class is called Vehicle. This class will have
information such as the number of passengers, the capacity of the fuel, as
well as the average fuel consumption. In this class, we have three instance
variables defined: fuel cap, passengers, and mpg. You should be keen to
realize that the class Vehicle is without a method. At the moment, we
consider it a data class.
Don’t forget that class declaration involves only specifying the type
description. No actual object is created. Therefore, the previous example will
not enforce the objects of type vehicle to become active.
This statement helps one create an object which belongs to the Vehicle class.
Vehicle minisalon = new Vehicle(); // we have created a variable object
called minisalon
When this statement is executed, minisalon becomes an instance of the class
Vehicle. Now, it will be said to have a physical reality. To access any
member of a class, the dot operator helps you achieve that:
Object.Member
Take, for instance, we want our minisalon to hold the value 12. This is how
it is done:
minisalon.fuelcap = 12;
Overall, the dot operator allows you to access the methods and instance
variables. You can take a look at this entire program which uses the Vehicle
class:
If you want to run this program, you need to run the file with the name
Vehicle.Demo.java. The main method is found in that class. This program
will display:
By looking at the above code snippet, you might reason that both objects
point to separate objects, however, that is not true. In this code, both car1 and
car2 point to the same object. Something I would like you to learn here is that
even though we have car1 and car2 pointing to the same object. They aren’t
related.
Methods
As we had said before, methods are members of the classes. At the moment,
our Vehicle class has data, but no methods. While having a class which
contains data alone is valid, the majority of the classes will have methods.
Methods act upon the data which has been defined in the class, and most of
the time it offers access to the data.
A method can carry at least one statement. A fully written Java code will
contain a method which acts only on one particular task. Every method must
be given a name. The name of the method helps one use the method in the
code. You can choose to give your method whichever name you want, but
note that the main() method is meant for the method which will start your
program execution. Another important point is that you should never use Java
keywords as part of your method name. The syntax for Java methods
includes:
We now want to review this program by starting with the method range().
Here is the first line:
Void range() {
What happens here is that we have declared a method whose name is range,
and it has no parameter. The body of the method has the
System.out.println(“……”); construct which will display the range of the
vehicle after performing a few calculations. The method range() closes when
it encounters the closing curly brace. This leads to the main program control
to switch to the original caller. Well, let’s review the code starting from the
main method:
Minivan.range();
What is happening here is that the range() method is called by using the
object variable minivan. Calling a program causes the program control to
migrate to the method. And so, if the method execution comes to an end,
control is relayed to the caller, and the program execution resumes from the
following code. If we consider the above example, the method range here is
going to display all the variation of vehicles defined by the minivan, similar
to a call done by sportscar. Whenever you call range(), it will output the
range listed by the object.
There is one particular thing you should discover about the method range().
Some of the instance variables have been addressed directly using the .
operator.
Returning to a method
Generally, we have only two conditions which result in a method returning a
value. First, the closing curly brace interacts with the method—this is clear in
the method range(). The second condition for a method to return happens
when a return statement gets executed. Don’t forget that there are two types
of return: the void method and the other one which returns values. We shall
look at the first form here:
When the return statement is executed, the program control will get back to
the caller by jumping all the rest of the code in a method. Consider the
following example:
In this case, the for loop will execute from 0–5 because when it reaches 5, the
method is enforced to return a value. You can still develop many return
statements in one Java method, especially when you have two pathways.
Returning a Value
While it is rare for a void method to return a value, there are specific methods
which return a value. The potential for the method to have a return is an
important property of a method. You have perhaps seen an example in the
square root function to find the square root. Return value is important in
programming to show a given result of a calculation like in the sqrt()
function.
Sometimes, the return value proves the success or failure of a given method.
The syntax used for a method with a return value is:
return value;
Chapter 10 : ENCAPSULATIONS IN JAVA
Java encapsulation
The entire code can be thought of a capsule, and you can only communicate
through the messages. Hence the name encapsulation.
Few notes on Encapsulation in Java :
Abstraction
Abstraction simply refers to the process of hiding unnecessary details of an
object and only showing the ones that are relevant. Encapsulation on the
other hand simply means the binding of the states and the methods of an
object together.
This binding eventually creates something called a class (we’ll cover that in a
little bit). Finally, message passing refers to the ability of objects to interact
with other objects.
High – level programming languages, on the other hand, have a much higher
level of abstraction, meaning that code goes through a program called a
compiler, which acts as the computer’s translator, before the computer is able
to use it. This level of abstraction is usually to the point where the
programming language already has syntax similar to English, a global
language. The compiler assumes the role of the translator between the high –
level language and the machine. This allows the programmer to write their
program in a more natural manner, as it allows for the coder to use more
"natural" language, and the higher – level language allows for some functions
to be automated, making life much easier for the coder. The trade – off here
however is that the code has to go through a compiler, which will take
lengthier for the program to run and execute, and the computer will often use
more memory as compared to a lower – level language. Amongst these high
– level languages are the more frequently – known ones, such as Python,
C++, and our topic for today, Java.
Chapter 11: POLYMORPHISM IN JAVA
Static polymorphism
There are two kinds of members that are possible inside a class. One is the
instance member and the other static member.
Instance members bind to the each instance of a class we create and have its
own copy in memory. So change of a member in once object doesn’t change
the value of the same member in another object.
On the other side, static members bind to the class and shared by each
instance of a class. So when we modify the value of static members in one
object, it will get reflected in all other objects. Moreover static members are
available once the class got loaded into memory, whereas instance members
are available only after we create an object of the class.
dynamic polymorphism
Resolving or interpreting the behavior at run time is called dynamic
polymorphism. We already see static polymorphism when we are discussing
about “method overloading”. Now, here we discuss about the dynamic or
runtime polymorphism.
Inheritance and composition
Inheritance is nothing by deriving the characteristics from one entity to
other. So we can derive properties of one class to other by using the
technique inheritance. We can inherit both the methods and fields from a
class to other (of-course there is a restriction with respect to access specifiers,
and will discuss later in this chapter).
The class from which properties are derived is called base class, super class
or parent class. The class which inherits the properties from other class is
called derived class, sub class or extended class.
Why do I need Inheritance?
Let us consider a scenario in a bank. A bank operate many kind of accounts,
say savings account, current account, salary account and many more. In each
case (in case of every account), bank stores the account holder details like,
name, address, contact details etcetera. Suppose a person has 3 different
types of accounts. Now, do I need to repeat all the data again and again?
A big NO. This is the scenario where we could go for inheritance. Just
aggregate all the properties that are common to all type of entities into a
single class. Now derive each of the specialized entity out of the aggregate
entity so that each derive entity inherits the properties of the base entity.
Chapter 12: EXAMPLES WITH JAVA
Assuming that the reader is not a total newbie to programming, and has been
introduced to the world of programming using C or another procedural –
heavy language, the next logical question would be: why even use object –
oriented programming? Well, one of its main advantages is that in the long
run, it saves time.
How to build a small game with Java
Procedural programming is usually much quicker and more straightforward
in simpler algorithms and programs; rather than having to construct and
define a class, and create an object based on that class, all the programmer
really has to do is to simply declare the necessary variables and write the
functions, and create the algorithm in order to solve the problem that they
need the code to address.
However, when it comes to more complex programs, needing more complex
solutions, this is where object – oriented programming begins to shine, and
this is where it starts to show its strength. In a lot of programs, there will be
times that there will be a number of “objects” or data clusters that have to be
grouped together, and that the programmer will be treating in a certain way.
This is what “classes” are meant to address. Instead of declaring a new set of
variables per data cluster, they can simply draw on a pre – made “class” and
create a new “object”. Let’s see how this would work in practice.
Each piece also has different methods of moving, depending on what piece
they are. If a programmer were to code a chess game in procedural fashion,
then they would have to manually describe each and every piece, all sixteen
pawns, four bishops and four knights, four rooks, two queens, and two kings.
In addition, they will have to write the functions that allow each piece to
move in its own separate way. However, if the programmer makes use of
object - oriented programming, instead of having to code sixteen pawns, four
bishops, four knights, four rooks, two queens, two kings, they simply have to
code six classes: one class to describe each piece on the board. The
programmer can now simply include the movement functions within each
class, and have the attributes describe their position: whether they’re white
king’s pawn, or black queen’s pawn, these are all things that can be inserted
through the “attributes” portion of the “pawn” class. Instead of thirty – two
clusters of code, the programmer only has to do six. Now it’s much easier,
much shorter, and also much more elegant.
Chapter 13: Most searched beginner’s questions
Installing Java
Given that Java is free, it can easily be downloaded from the Java website,
and it will be quite easy to install, with basic instructions that can easily be
followed, depending on what operating system the user is running. Here we
will cover the three major operating systems, Windows, Linux, and Mac.
Installing Java on Windows
Before installing Java, check the version of Windows that the computer is
running, in order to see whether or not it is compatible with the latest Java
version. Generally, Windows platforms as far back as Windows XP are still
supported, though the support for these older Windows versions is being
slowly phased out.
The next step is to disable the Windows firewall. This step is in order to
prevent any issues with installing Java, as there are often times when firewall
settings disable any automatic or online installation, so in order to avoid these
issues, it would be best to simply disable the firewall. However, this step may
leave your computer vulnerable, so remember to turn it on immediately after
installation of Java, and make sure not to open any suspicious files or visit
any suspicious websites while the firewall is turned off.
Once the user has verified whether Java is compatible with their Windows
system, and has disabled or limited the firewall, it is time to proceed to the
installation process. Navigate to the manual download page for Windows in
the Java website and choose the applicable Windows OS option.
Once this is done, an installer should come up, and the user should press the
“Run” option, which will automatically allow the installer to begin the
installation process. If the user wishes to defer installation to a later date, or
simply wants to download it for use on another device, they can simply
“Save” the installer file rather than Running it. The Java installation window
should then pop up, and this will allow the user to choose what folder they
wish Java to be installed in; for convenience, the default folder in C: should
suffice for most users, unless they have a special need. The installer may
offer to install additional programs other than Java; know that these are
unnecessary in order to use Java, so if the user refuses to install them, this
will not hamper their use of Java. After a few minutes, the Java program
should then be installed, and in some cases the user will have to restart their
device. Once the device has been restarted, the user may wish to go back to
the Java website through this link: https://java.com/en/download/installed.jsp
in order to verify whether or not the installation was completed properly.
Once verified, congratulations! The Java software package has been installed
and should be ready to use.
Installing Java on Linux
Before installing Java, check the version of Linux that the computer is
running, in order to see whether or not it is compatible with the latest Java
version. Generally, most Linux packages are supported, but Java runs a 32 –
bit version for a lot of these platforms, such as Oracle Linux or SUSE Linux.
The next step is to ensure that the user is installing as a user with root access.
This will allow Java to be fully installed with the necessary permissions. In
case the user is not one with root access, then they may have to edit the
destination folder of their Java installation in order to be able to properly
install it, as they may not have the required permissions to install it in the
default folder.
Once the user has verified whether Java is compatible with their Linux
system, as well as checked whether or not they have the appropriate
permissions in order to install the Java Runtime Environment, or JRE, then
they can navigate to the Java home page and choose the compatible version
to their software package.
Once this is done, an installer should come up, and the user should press the
“Run” option, which will automatically allow the installer to begin the
installation process. If the user wishes to defer installation to a later date, or
simply wants to download it for use on another device, they can simply
“Save” the installer file rather than Running it.
The installer may offer to install additional programs other than Java; know
that these are unnecessary in order to use Java, so if the user refuses to install
them, this will not hamper their use of Java. After a few minutes, the Java
program should then be installed, and in some cases the user will have to
restart their device. Once the device has been restarted, the user may wish to
go back to the Java website through this link:
https://java.com/en/download/installed.jsp in order to verify whether or not
the installation was completed properly. Once verified, congratulations! The
Java software package has been installed and should be ready to use.
Installing Java on Mac
Before installing Java, check the version of Mac that the computer is running,
in order to see whether or not it is compatible with the latest Java version.
Generally, Java runs with most macOS versions, but in order to be safe,
ensure that your Mac is running the latest macOS version in order to avoid
support or compatibility issues.
Once the user has verified whether Java is compatible with their mac system,
it is time to proceed to the installation process. Navigate to the manual
download page for Mac in the Java website and choose the applicable Mac
OS option.
Once this is done, the file jre-8u65-macosx-x64.pkg file should have been
downloaded, and the user should press the “Run” option, which will
automatically allow the installer to begin the installation process. If the user
wishes to defer installation to a later date, or simply wants to download it for
use on another device, they can simply “Save” the installer file rather than
Running it. The Java installation wizard should then pop up, and this will
allow the user to choose what folder they wish Java to be installed in; for
convenience, the default folder in C: should suffice for most users, unless
they have a special need. The installer may offer to install additional
programs other than Java; know that these are unnecessary in order to use
Java, so if the user refuses to install them, this will not hamper their use of
Java. After a few minutes, the Java program should then be installed, and in
some cases the user will have to restart their device.
Once the device has been restarted, the user may wish to go back to the Java
website through this link: https://java.com/en/download/installed.jsp in order
to verify whether or not the installation was completed properly. Once
verified, congratulations! The Java software package has been installed and
should be ready to use.
Chapter 14: Tips and tricks
How has java become so successful? Java is such a widespread language for
many reasons, and it owes a lot around the key principles it was designed
around. One of the first principles of Java is its ease of use. The fundamentals
of the Java programming language were adapted from C ++, another
extremely popular higher – level programming language. However, though C
++ and its predecessors, C and C # are powerful languages, it tends to be
rather complex in terms of syntax, and is not fully adapted for some of the
purposes of Java, notably for internet technology integration. Java thus was
able to base itself on C ++, and build on this powerful language’s
fundamentals in order to provide a language that is also similarly powerful,
but easier to use and better – suited for some specialized users. Java is also a
very reliable programming language, intentionally build in order to reduce
and even eliminate the possibilities of fatal errors that arise from programmer
errors. This is why Java heavily relies on object – oriented programming
principles, which allows the data and the manipulation of data to be packaged
together, making Java more robust and reliable, as well as much more
modular, allowing for code packages to be switched out and adapted as
needed.
In addition to the previous qualities of ease of use and reliability, given
Java’s nature of initially being designed for mobile devices, it was designed
to be able to provide a higher level of security and safety for its
programming, as it was initially meant for mobile devices, which by their
nature are meant to exchange data over networks, making data security of the
utmost priority. Due to this, Java has become one of the most secure
programming languages widely available today, making it a highly attractive
option to those who wish to write programs that are less vulnerable to
exploits. Also, though Java was initially intended for mobile devices, Java
has developed into a relatively platform – independent programming
language, something that works to its advantage, as programs written in Java
tend to work no matter what machine is running the program. Java was
written as a language that would be portable and work cross – platform,
meaning that it doesn’t matter what operating system the machine has, what
hardware the machine is running, or what device it’s running on. This has led
to its adaptability and its widespread use around the world. Due to these core
principles prioritized by the Sun Microsystems team that developed Java:
Ease of Use, Reliability, Safety, Cross – platform adaptability, Java became
and still remains one of the most popular and most widely used programming
languages today.
Why Java?
Of course, one of the key reasons to use Java is its focus on Object – oriented
programming. Object – oriented programming, or “OOP” is a type of
programming language model which allows the program’s code to be
organized around data, rather than functions and logic, which is known as
procedural programming. These “data clusters” are organized into things
called “objects”, hence the moniker of “object – oriented programming”.
These objects are created by something called “classes”, understood here in
the traditional sense of how classes are: types of objects, allowing the
programmer to “classify” them according to two major criteria: attributes and
methods. The attributes of a class are the raw data that will create the object:
these are its descriptors, such as the values that it possesses, and other
relevant data that will make up the object. The second criterion is the
“method” of the object. This “method” is the behavior, or the logical
sequences contained within the class, describing how it interacts or can be
interacted with natively.
In order to make this clearer, say that there is a class “Human”. This “class”
will have attributes such as height, weight, gender, race. The “human” class
can also have methods such as “run”, “walk”, “talk”. These theoretical
components make up the “human” class, a blueprint for an object. Now that
the class has been defined, the programmer, if they so wish, can create an
object using the “human” class as a blueprint. They can invoke the class
“Human” and “populate” its attributes, giving it a specific height, weight,
gender, and race. In addition, the object already has built – in functions such
as “run”, “walk”, and “talk”, so upon the creation of an object, let’s say
named “Mike” from the “Human” class, it already contains the functions to
run, walk, and talk, without need for the programmer to code those specific
functions again, as they are already “inherent” in the created object.
In a nutshell, that is what Object - oriented programming is meant to be: a
way of programming that allows the programmer to draw on pre – defined
classes so that it will be easier to describe them and use their internal, or built
– in functions in order to operate them.
Assuming that the reader is not a total newbie to programming, and has been
introduced to the world of programming using C or another procedural –
heavy language, the next logical question would be: why even use object –
oriented programming? Well, one of its main advantages is that in the long
run, it saves time.
Procedural programming is usually much quicker and more straightforward
in simpler algorithms and programs; rather than having to construct and
define a class, and create an object based on that class, all the programmer
really has to do is to simply declare the necessary variables and write the
functions, and create the algorithm in order to solve the problem that they
need the code to address.
However, when it comes to more complex programs, needing more complex
solutions, this is where object – oriented programming begins to shine, and
this is where it starts to show its strength. In a lot of programs, there will be
times that there will be a number of “objects” or data clusters that have to be
grouped together, and that the programmer will be treating in a certain way.
This is what “classes” are meant to address. Instead of declaring a new set of
variables per data cluster, they can simply draw on a pre – made “class” and
create a new “object”. Let’s see how this would work in practice.
If a programmer were to code a chess game in procedural fashion, then they
would have to manually describe each and every piece, all sixteen pawns,
four bishops and four knights, four rooks, two queens, and two kings. In
addition, they will have to write the functions that allow each piece to move
in its own separate way. However, if the programmer makes use of object -
oriented programming, instead of having to code sixteen pawns, four bishops,
four knights, four rooks, two queens, two kings, they simply have to code six
classes: one class to describe each piece on the board. The programmer can
now simply include the movement functions within each class, and have the
attributes describe their position: whether they’re white king’s pawn, or black
queen’s pawn, these are all things that can be inserted through the “attributes”
portion of the “pawn” class. Instead of thirty – two clusters of code, the
programmer only has to do six. Now it’s much easier, much shorter, and also
much more elegant.
Chapter 15: WORKBOOK
1. What is Local Variables?
2. What is Instance Variables?
3. What is Class Variables?
4. What are Constructors?
5. What are Objects?
Answers
1. local variables only function within a method. Once all the lines in that
method have been executed the local variables in it get discarded. They can’t
be used elsewhere in your source code or even in your entire program.
2. instance variables are the variables that can be found within a class but are
found outside of a method. Note that methods that are inside the class can use
instance variables in that class.
3. these are variables that are also inside a class and also outside any method
within that class. The big difference is that class variables are created using
the static keyword.
4. This is another important topic in Java OOP. A constructor in Java is a
specialized method that you will use to initialize an object. But what if you
forget to write a constructor? If that happens, then the compiler will create a
constructor for you.
5. Think of objects as bundles of data—a more powerful variable as it were.
Now, other than bundles of data (remember, variables only hold or contain
data) objects in Java also contain the actual instructions that create some sort
of behavior—in other words they contain methods.
Conclusion
This book has taken you through the core fundamentals of Java to help you
develop the right foundation to explore deeper concepts in Java. It is
important for you to understand the various data types in Java: the variables,
strings, and arrays. In addition, mastering the method, classes, and
inheritance is crucial. Remember. Java is an object-oriented language. This
means that having a deep understanding of the topic of classes, methods, and
inheritance is fundamental.
Java is a very powerful language, it powers the majority of enterprises and
organizations. It is one of the best languages for developers when they want
to implement internet-based applications. Furthermore, software devices
which must cross communicate over a given network are developed with the
help of Java. Many devices today use Java. This shows how Java is an
important computer programming language. While this book has tried to
present you with the basics skills of programming in Java, it is highly
important to emphasize that it is just a starting point. Java goes beyond the
elements which determine the language. For you to become an excellent Java
programmer, you need to take time to read deep and master the concepts in
Java. Luckily, this book helps you develop the right knowledge to expand
more on other areas of Java. Therefore, the next step for you to take after
reading this book is to look for a comprehensive Java textbook to read.
PYTHON PROGRAMMING
Steve Tudor
Text Copyright ©
All rights reserved. No part of this guide may be reproduced in any form
without permission in writing from the publisher except in the case of brief
quotations embodied in critical articles or reviews.
Legal & Disclaimer
The information contained in this book and its contents is not designed to
replace or take the place of any form of medical or professional advice; and is
not meant to replace the need for independent medical, financial, legal or
other professional advice or services, as may be required. The content and
information in this book has been provided for educational and entertainment
purposes only.
The content and information contained in this book has been compiled from
sources deemed reliable, and it is accurate to the best of the Author's
knowledge, information and belief. However, the Author cannot guarantee its
accuracy and validity and cannot be held liable for any errors and/or
omissions. Further, changes are periodically made to this book as and when
needed. Where appropriate and/or necessary, you must consult a professional
(including but not limited to your doctor, attorney, financial advisor or such
other professional advisor) before using any of the suggested remedies,
techniques, or information in this book.
Upon using the contents and information contained in this book, you agree to
hold harmless the Author from and against any damages, costs, and expenses,
including any legal fees potentially resulting from the application of any of
the information provided by this book. This disclaimer applies to any loss,
damages or injury caused by the use and application, whether directly or
indirectly, of any advice or information presented, whether for breach of
contract, tort, negligence, personal injury, criminal intent, or under any other
cause of action.
You agree to accept all risks of using the information presented inside this
book.
You agree that by continuing to read this book, where appropriate and/or
necessary, you shall consult a professional (including but not limited to your
doctor, attorney, or financial advisor or such other advisor as needed) before
using any of the suggested remedies, techniques, or information in this book.
CHAPTER 1. WHAT IS PYTHON
Python is basically an incredibly useful and powerful language. It’s present
essentially everywhere. Everything from the scripting side of video games (or
the video games themselves) to intensive server-side web applications to the
plethora of deep and responsive desktop applications that have been built
with it.
When should you use Python? The answer depends upon exactly what you’re
going to do. But since you’re a beginner, I say you should learn anyway.
• Python 0.9.0:
Following the release of the first version in the 29th of February, 1991, there
were seven other updates made to the early version 0.9.0. These updates took
varying tags under the 0.9.0 version and were spread out over nearly three
years (1991 to 1993). The first version update came in the form of Python
0.9.1, which was released in the same month of February 1991 as its
predecessor. The next update came in the autumn period of the release year,
under the label Python 0.9.2. By Christmas Eve of the same year (1991)
python published its third update to the earliest version under the label
Python 0.9.4. By January of the succeeding year, the 2nd precisely, a gift
update under the label Python 0.9.5 was released. By the 6th of April, 1992, a
sixth update followed named, Python 0.9.6. It wasn't until the next year,
1993, that a seventh update was released under the tag Python 0.9.8. The
eighth and final update to the earliest version came five months after the
seventh, on the 29th of July, 1993, and was dubbed python 0.9.9.
These updates marked the first generation of python development before it
transcended into the next version label.
• Python 1.0
After the last update to Python 0.9.0, a new version, Python 1.0, was released
in January of the following year. 1994 marked the addition of key new
features to the Python programming language. Functional programming tools
such as map, reduce, filter, and lambda were part of the new features of the
version 1 release. Van Rossum mentioned that the obtainment of map,
lambda, reduce and filter was made possible by a LISP hacker who missed
them and submitted patches that worked. Van Rossum's contract with CWI
came to an end with the release of the first update version 1.2 on the 10th of
April, 1995. In the same year, Van Rossum went on to join CNRI
(Corporation for National Research Initiatives) in Reston, Virginia, United
States, where he continued to work on Python and published different version
updates.
Nearly six months following the first version update, version 1.3 was released
on the 12th of October, 1995. The third update, version 1.4, came almost a
year later in October of 1996. By then, Python had developed numerous
added features. Some of the typical new features included an inbuilt support
system for complex numbers and keyword arguments which, although
inspired by Modula-3, shared a bit of a likeness to the keyword arguments of
Common Lisp. Another included feature was a simple form hiding data
through name mangling, although it could be easily bypassed.
It was during his days at CNRI that Van Rossum began the CP4E (Computer
Programming for Everybody) program which was aimed at making more
people get easy access to programming by engaging in simple literacy of
programming languages. Python was a pivotal element to van Rossum's
campaign, and owing to its concentration on clean forms of syntax; Python
was an already suitable programming language. Also, since the goals of ABC
and CP4E were quite similar, there was no hassle putting Python to use. The
program was pitched to and funded by DARPA, although it did become
inactive in 2007 after running for eight years. However, Python still tries to
be relatively easy to learn by not being too arcane in its semantics and syntax,
although no priority is made of reaching out to non-programmers again.
The year 2000 marked another significant step in the development of Python
when the python core development team switched to a new platform —
BeOpen.com where a new group, BeOpen PythonLabs team was formed. At
the request of CNRI, a new version update 1.6 was released on the 5th of
September, succeeding the fourth version update (Python 1.5) on the
December of 1997. This update marked the complete cycle of development
for the programming language at CNRI because the development team left
shortly afterward. This change affected the timelines of release for the new
version Python 2.0 and the version 1.6 update; causing them to clash. It was
only a question of time before Van Rossum, and his crew of PythonLabs
developers switched to Digital Creations, with Python 2.0 as the only version
ever released by BeOpen.com.
With the version 1.6 release caught between a switch of platforms, it didn't
take long for CNRI to include a license in the version release of Python 1.6.
The license contained in the release was quite more prolonged than the
previously used CWI license, and it featured a clause mentioning that the
license was under the protection of the laws applicable to the State of
Virginia. This intervention sparked a legal feud which led The Free Software
Foundation into a debate regarding the "choice-of-law" clause being
incongruous with that if the GNU General Public License. At this point, there
was a call to negotiations between FSF, CNRI, and BeOoen regarding
changing to Python's free software license which would serve to make it
compatible with GPL. The negotiation process resulted in the release of
another version update under the name of Python 1.6.1. This new version was
no different from its predecessor in any way asides a few new bug fixes and
the newly added GPL-compatible license.
• Python 2.0:
After the many legal dramas surrounding the release of the second-generation
Python 1.0 which corroborated into the release of an unplanned update
(version 1.6.1), Python was keen to put all behind and forge ahead. So, in
October of 2000, Python 2.0 was released. The new release featured new
additions such as list comprehensions which were obtained from other
functional programming languages Haskell and SETL. The syntax of this
latest version was akin to that found in Haskell, but different in that Haskell
used punctuation characters while Python stuck to alphabetic keywords.
Python 2.0 also featured a garbage collection system which was able to
collect close reference cycles. A version update (Python 2.1) quickly
followed the release of Python 2.0, as did Python 1.6.1. However, due to the
legal issue over licensing, Python renamed the license on the new release to
Python Software Foundation License. As such, every new specification, code
or documentation added from the release of version update 2.1 was owned
and protected by the PSF (Python Software Foundation) which was a
nonprofit organization created in the year 2001. The organization was
designed similarly to the Apache Software Foundation. The release of version
2.1 came with changes made to the language specifications, allowing support
of nested scopes such as other statically scoped languages. However, this
feature was, by default, not in use and unrequired until the release of the next
update, version 2.2 on the 21st of December, 2001.
Python 2.2 came with a significant innovation of its own in the form of a
unification of all Python's types and classes. The unification process merged
the types coded in C and the classes coded in Python into a single hierarchy.
The unification process caused Python's object model to remain totally and
continuously object-oriented. Another significant innovation was the addition
of generators as inspired by Icon. Two years after the release of version 2.2,
version 2.3 was published in July of 2003. It was nearly another two years
before version 2.4 was released on the 30th of November in 2004. Version
2.5 came less than a year after Python 2.4, in September of 2006. This
version introduced a "with" statement containing a code block in a context
manager; as in obtaining a lock before running the code block and releasing
the lock after that or opening and closing a file. The block of code made for
behavior similar to RAII (Resource Acquisition Is Initialization) and swapped
the typical "try" or "finally" idiom.
The release of version 2.6 on the 1st of October, 2008 was strategically
scheduled such that it coincided with the release of Python 3.0. Asides the
proximity in release date, version 2.6 also had some new features like the
"warnings" mode which outlined the use of elements which had been omitted
from Python 3.0. Subsequently, in July of 2010, another update to Python 2.0
was released in the version of python 2.7. The new version updates shared
features and coincided in release with version 3.1 — the first version update
of python 3. At this time, Python drew an end to the release of Parallel 2.x
and 3.x, making python 2.7 the last version update of the 2.x series. Python
went public in 2014, November precisely, to announce to its username that
the availability of python 2.7 would stretch until 2020. However, users were
advised to switch to python 3 in their earliest convenience.
• Python 3.0:
The fourth generation of Python, Python 3.0, otherwise known as Py3K and
python 3000, was published on the 3rd of December 2008. This version was
designed to fix the fundamental flaws in the design system of the scripting
language. A new version number had to be made to implement the required
changes which could not be run while keeping the stock compatibility of the
2.x series that was by this time redundant. The guiding rule for the creation of
python 3 was to limit the duplication of features by taking out old formats of
processing stuff. Otherwise, Python three still followed the philosophy with
which the previous versions were made. Albeit, as Python had evolved to
accumulate new but redundant ways of programming alike tasks, python 3.0
was emphatically targeted at quelling duplicative modules and constructs in
keeping with the philosophy of making one "and
preferably only one" apparent way of doing things. Regardless of these
changes, though, version 3.0 maintained a multi-paradigm language, even
though it didn't share compatibility with its predecessor.
The lack of compatibility meant Python 2.0 codes were unable to be run on
python 3.0 without proper modifications. The dynamic typing used in Python
as well as the intention to change the semantics of specific methods of
dictionaries, for instance, made a perfect mechanical conversion from the 2.x
series to version 3.0 very challenging. A tool, name of 2to3, was created to
handle the parts of translation which could be automatically done. It carried
out its tasks quite successfully, even though an early review stated that the
tool was incapable of handling certain aspects of the conversion process.
Proceeding the release of version 3.0, projects that required compatible with
both the 2.x and 3.x series were advised to be given a singular base for the
2.x series. The 3.x series platform, on the other hand, was to produce releases
via the 2to3 tool.
For a long time, editing the Python 3.0 codes were forbidden because they
required being run on the 2.x series. However, now, it is no longer necessary.
The reason being that in 2012, the recommended method was to create a
single code base which could run under the 2.x and 3.x series through
compatibility modules. Between the December of 2008 and July 2019, 8
version updates have been published under the python 3.x series. The current
version as at the 8th of July 2019 is the Python 3.7.4. Within this timeframe,
many updates have been made to the programming language, involving the
addition of new features mentioned below:
In contemporary times, version releases in the version 3.x series have all been
equipped with added, substantial new features; and every ongoing
development on Python is being done in line with the 3.x series.
5. Select the user options that you require and press “NEXT”.
Your screen will display the hard drive where your python
will be located.
Your python has been installed in your computer and is now ready to use.
Find it in drive C, or wherever you have saved it.
There can be glitches along the way, but there are options which are
presented in this article. If you follow it well, there is no reason that you
cannot perform this task.
For Mac
To download Python on Mac, you can follow a similar procedure, but this
time, you will have to access the “Python.mpkg” file, to run the installer.
For Linux
For Linux, Python 2 and 3 may have been installed by default. Hence, check
first your operating system. You can check if your device has already a
Python program, by accessing your command prompt and entering this:
python—version, or python3—version.
If Python is not installed in your Linux, the result “command not found” will
be displayed. You may want to download both Python 2.7.12 and any of the
versions of Python 3 for your Linux. This is due to the fact that Linux can
have more compatibility with Python 3.
For windows users, now that you have downloaded the program, you’re
ready to start.
And yes, congratulations! You can now begin working and having fun with
your Python programming system.
If you don’t want to know all the other information about Python and you’re
raring to go, you can follow these next steps.
First open the Python file you have saved in your computer.
Click on Python as show below. In some versions, you just click
‘python’for the shell to appear.
You may opt to use a Python shell through idle. If you do, this is how
it would appear:
In the Python 3.5.2 version, the text colors are: function (purple), string
(green) and the result (blue). (The string is composed of the words inside the
bracket (“Welcome to My Corner”), while the function is the command word
outside the bracket (print).
Take note that the image above is from the Python 2.7.12 version.
You have to use indentation for your Python statements/codes. The standard
Python code uses four spaces. The indentations are used in place of braces or
blocks.
In some programming languages, you usually use semi-colons at the end of
the commands–in python, you don’t need to add semi-colons at the end of the
whole statement.
In Python, semi-colons are used in separating variables inside the brackets.
For version 3, click on your downloaded Python program and save the file in
your computer. Then Click on IDLE (Integrated DeveLopment
Environment), your shell will appear. You can now start using your
Python.It’s preferable to use idle, so that your codes can be interpreted
directly by idle.
You may have noticed that there are various entries to the contents of each of
the files that you have opened. You can click and open all of them, as you
progress in learning more about your Python programming.
Python is a programming language that has been studied by students for
several days or months. Thus, what’s presented in this book are the basics for
beginners.
CHAPTER 2. BASIC OF PYTHON
Python can be used as an active translator or transcriber by interaction
through the web. It can also be employed to formulate lessons. In interaction,
though, there is one serious concern: that is, it is impossible to keep a copy of
what transpired. On the other hand, using lessons allows you to keep a record
of the work done. In the interactive translator, you are allowed to open only
one display page, while in lessons, you can open as many as you need.
Variables
Python uses information that are not constant, these are used to keep the data.
When using these, be sure to put descriptions. These data could be names,
age, addresses, gender and other similar material.
Outputs and Inputs
Any computer program requires interfacing between itself and the person
using it. The user encodes and that is input, and the output is printing what
has been encoded.
Mathematics
Numbers are the common language in computer programs including Python.
Mathematical operations are used by Python as you will learn later on. Most
of its language are represented by mathematical equations and symbols.
Loop
You need to understand the term loop in python. It is a symbol used to
represent repeated word/s or sentence/s in python programming. Anything
that is being repeatedly used can employ a loop.
Python categories
It is important to be acquainted with the types of python product categories
for easy reference and understanding. Python categories are symbolized by
A, B, C that signifies the shifts in language. Examples are 3.3.1 to 3.3.2. This
means there are minor changes, but when it employs something like 2.xx to
3.xx it means there are major changes.
Cutting
This is a critical component of python which is used to copy the desired part
of a data. It is a method of making programs simple by concentrating on
items from a gamut of data. When you do that, you are actually removing
components that are not relevant to the program.
Modules
Generating Python source codes can be tedious,if you don’t know how to
derive your codes.
Program developers have now an application that converts your Python 2
codes to Python version 3 codes from AST.
You can create your own code as discussed in the chapters, and it’s easy to
append strings to a list to create a code, but it won’t hurt you, if you know
how to generate Python source codes. One way of doing this is to use context
managers.
These are the most basic elements in python, there are more but with the ones
presented, one can already start using python and learn the others, as you go
on in your programming.
CHAPTER 3. FULL INSTRUCTIONS ON HOW
TO CODE
We have touched on this first topic already, but we will expand and reiterate
here. First up is naming conventions.
Comments
Here are some best practices for your comments that will help other readers
understand you easier:
Avoid pointers
We didn't even touch on them in this document, and we are only
going to tell you they exist to tell you not to use them unless you're an
advanced user. They are the most likely ‘tool’ to cause the crazy, bad kinds
of problems from happening in your coding, and are notoriously tough for a
beginner to use properly. So avoid them until you are sure you know what
you are doing.
Embrace self-improvement
Understand from day 1 that as a fledgling coder that you will grow
and improve over time. Use each challenge you come across to try writing
new sketches as an opportunity to grow and hone your skills.
Reach out to the community for help and advice!
There are some really fantastic people in our big community of
hobbyists that are willing to help you learn and grow as an enthusiast. This is
a great way to meet friends and learn so many new ways to do things you
may not have thought about previously.
Write both brackets or both braces at the start then fill in the
date in-between
When writing functions, loops or anything with brackets and braces,
this trick helps to ensure that you will be closing all of your brackets and
braces, preventing unexpected results.
Make sure the for loop variables are clear on what they
represent
Having a variable of x can work, but it really offers nothing to the
person reading your code for them to understand exactly what that variable is
for.
CHAPTER 4. HOW TO MAKE PREDICTIONS
WITH ALGORITHM
How are you feeling at this stage? Have you encountered any errors? Are you
feeling as if you have gained some new knowledge?
Hopefully, things are going smoothly and you are grasping the concepts well
at this point. Let’s take a look at how to make predictions with algorithms in
Python and what it means.
Your aggregated data tells a tale that is certainly complex. To withdraw the
insights, you are going to need an extremely accurate design which is
predictive. This might not be the best step as a beginner; nonetheless, it is
here for reference to the entire picture of Python capabilities.
Predictive analysis is being modeled after major mathematical models to
predict a conference or result. These designs forecast the desired outcome at
some future time based on modifications placed into data inputs. Using a
repetitive procedure, you create the models by choosing a training
information set where you will proceed to test and further validate the
information. After you examine it to ascertain its reliability and accuracy in
predicting forecasts, play around with different methods until you find one
that is comfortable for you. The important thing is that you choose one that
you can understand, learn and apply without much effort.
To give you an idea of some good examples of such a method, you can try a
time-series reversal model for predicting low and even high levels of flight
traffic or fuel. Of course, this is certainly predicting based on a linear
approach to speed compared to upload and continuing to be extremely
beneficial in real-world estimation models for conjecture.
IMPLEMENTATION OF PYTHON
Although this might be seen as a new thing, implementation of Python refers
to the environment and the program that facilitates the execution of your
program within the Python language, and it is represented with CPython.
Depending on the type of the CPython you are using, such environment
enables you to execute different kinds of the codes and statements you are
handling within the program.
In programming, implementation includes everything to enable you to work
on your program and complete it successfully on time. Unlike in other
programming languages, implementation helps the programmers to get more
things done in Python. The Python enables you to work on your program
with many different programming languages like Java and C++, and this
makes it appealing and straightforward.
Apart from CPython, you can use implementations such as Brython,
CLPython, HotPy, IronPython, Jython, PyMite, and PyPy in Python to carry
out the specific thing with the Python language. For the beginners, Python is
the most suitable for them because it is not confusing like the other
programming languages.
STANDARD DATA
Python programming language is suitable for those who are looking for the
programming language that will enable them to work on their project using
many different data successfully. These data are used to define various
operations which the programmers can use to do multiple things when
coding. There are five types of data in Python, and these include Numbers,
Dictionary, Tuple, List, and String. These data types are essential in
programming. You can use any of them to increase the function and the
speed of the Python.
Additionally, number data types stores the numerical values and are created
as objects after assigning a value to them. Numerical values exist in four
types, namely; assigned integers, complex numbers, float point, and long
integers shown as octal or hexadecimal. As a programmer, you should use
these types of numerical values correctly to ensure that there is no error when
running the program. Although Python allows a programmer to use the
lowercase mainly when dealing with the long type of number, it is good to
use uppercase when working with the letter as it eliminates any confusion the
programmer can experience in reading the program.
Because Python is a programming tool that helps individuals to use and read
it with ease, it is the best method one should start with when he/she enters
programming professional. It is easy to use and read as it has syntax, which
allows programmers to express their concepts without necessarily creating a
coding page. Generally, Python is the best language for you due to its
usability and readability. We are sure that after reading this book, you can
now create a program with Python programming language.
CHAPTER 6. INTERMEDIATE AND
ADVANCED DATA TYPES
In Python, every value is assigned a specified datatype. Since every aspect of
Python consists of an object, data types are in fact classes, and variables are
instances or objects of these classes. Python has several data types used in its
operations. Listed below are some of the basic, important ones.
PYTHON NUMBERS:
Python numbers is a category constituted by floating-point numbers and
integers as well as complex numbers. They are usually defined as int
(integer), float (floating number), and complex (complex numbers) class in
Python. To determine the class a value or variable belongs in the type()
function is used, and to find out if an object belongs in a specific class, the
isinstance() function is used.
In python numbers, the length of integers is boundless and can only be
limited by the amount of available memory. Also, a floating-point number
can maintain accuracy up to 15 decimal places. The presence of a decimal
point shows the distinction between an integer and floating points. For
example, 1 and 1.0 are the same in basic maths, but in Python, the former (1)
is an integer, and the latter (1.0) is a floating number. Complex numbers are
usually written in the following format, x + y; where x constitutes the real
part of the equation, and the imaginary part is denoted by y.
PYTHON LIST:
A list refers to an ordered sequence of items. In python programming, list is
one of the widely used datatypes owing to its relative flexibility. The items
contained in a list do not have to share similarities in type to be on the list.
Also, the process of declaring a list is quite easy. Items which are separated
using commas and are contained within brackets []. The slicing operator [] is
used in extracting a specific range of items or a single item from a list. In
Python, index begins from the number 0. Lists can be mutable, meaning the
value of the elements in a list is capable of being changed.
PYTHON TUPLE:
In Python, a tuple refers to an ordered sequence of items similar to list. The
distinction, however, is that unlike lists, tuples are immutable. That is, once
they have been created, the elements of a tuple cannot be changed or
modified. Tuples are mainly used in place of lists to write-protect data as they
are much faster and are incapable of changing dynamically. Tuples are
defined with parentheses () where the items within are separated using
commas. Moreover, even though a slicing operator [] can also be used to
extract items, the values cannot be changed.
PYTHON SET
A set is a collection of special items which are not in any particular order. It
is defined by values contained within braces {} and separated using commas.
Like sets in basic mathematics, operations can be carried out on python sets
such as the intersection and union of two sets.
Every set has a unique value, and since they are unordered, they do not
require indexing. In this vein, the slicing operator [] cannot be used on sets.
PYTHON DICTIONARY
Like sets, python dictionary is a collection of key-value pairs in an unordered
state. Dictionaries are used when there are vast volumes of data. Dictionaries
are optimized to retrieve data. To do this, the key to retrieve a specific value
must be known. In python programming, dictionaries exist as items being
paired in the format key:value and contained within braces {}.
Moreover, the pair must not necessarily be of the same type. That is, key and
value can be different types. In the pair, the key is used to retrieve a
respective value, but it doesn’t work vice versa.
def function_name(parameters):
‘’’docstring’’’
statement(s)
• How functions are called in Python:
Once a function has been defined in Python, it is capable of being called from
another function, a program, or the python prompt even. Calling a function is
done by entering a function name with a proper parameter.
1. Docstring:
The docstring is the first string which comes after the function header. The
docstring is short for documentation string and is used in explaining what a
function does briefly. Although it is an optional part of a function, the
documentation process is a good practice in programming. So, unless you
have got an excellent memory which can recall what you had for breakfast on
your first birthday, you should document your code at all times. In the
example shown below, the docstring is used directly beneath the function
header.
>>> greet(“Amos”)
Hello, Amos. Good morning!
Triple quotation marks are typically used when writing docstrings so they can
extend to several lines. Such a string is inputted as the __doc__ attribute of
the function. Take the example below.
You can run the following lines of code in a Python shell and see what it
outputs:
1. >>> print(greet.__doc__)
2. This function greets to
3. the person passed into the
4. name parameter
The purpose of the return statement is to go back to the location from which
it was called after exiting a function.
• Syntax of return:
This statement is able to hold expressions which have been evaluated and
have their values returned. A function will return the Noneobject if the
statement is without an expression, or its return statement is itself absent in
the function. For instance:
1. >>> print(greet('Amos'))
2. Hello, Amos. Good morning!
3. None
In this case, the returned value is None.
CHAPTER 8. PYTHON FILE MANAGEMENT
File is a named memory location that is used to store and access data. Python
manages file through a file object.
There are 4 basic file operations in Python:
1) opening a file
2) reading from a file
3) writing to a file
4) closing a file
Opening a File
The open() function creates a file object or handle that can be used to call
other methods. You will use this function to open the file for reading,
writing, or both.
syntax:
file object=open(filename [, access_mode][, buffering])
f = open("diary.txt")
f = open("diary.txt",'w')
Writing to a File
Before you can start writing to a file, you have to open the file with a file
object:
>>> notes = open("myfile.txt", "w")
To start writing to a file, you will use the write method on the file object:
notes.close()
Reading a File
Use the readlines() method on the file object to read each text line from the
file. Create a variable that will store the text lines read:
Type the variable name on the Python prompt to access the contents of the
file:
>>> lines
['A file can be used to store important data. Files are objects that you can use
in your program.']
Write the following lines with a new line character (\n) at the end of each
line:
37
>>>message.close()
To read the file using the readline method and the while loop:
# Open the linefile.txt on read only mode:
message = open('newfile.txt')
print(textline)
textline = message.readline()
message.close()
When you run the above program, you will see the following line-by-line
output on the Python shell:
This file stores important messages.
Attendance is a must.
message = open('newfile.txt')
for x in iter(message):
print(x)
message.close()
For example, to append data to newfile.txt, open the file and assign it to a
new file handle:
>>> messages.close()
Multipurpose
It is like the Swiss Army Knife, which would be used for many purposes.
Python is not just a thing that deals with discipline but supports all sources of
data like data from SQL or MongoDB. API of Python, which is called
PySpark, is used to distribute computing. It has an inbuilt feature of service
provision for natural language processing NLTK.
• Python also has many applications in the provision of services for
internet protocol like XML, LSON, and HTML.
At this point, it will probably be easier if you take a look at how you can
work with making classes and how to make sure that they do exactly what
you would like. We will now have a look at an example of how this code will
work and the different theories that have been going on with it. In this
example, we will use ‘book’ as the name of the class and then it will have the
properties of ‘size’ and ‘type.’
CHAPTER 10. REAL WORLD EXAMPLES OF
PYTHON
One might argue that the era of Python was just 2017 when it witnessed some
great rise in the popularity and growth across the world. The recent However,
according to statistics and data, the recent rise in the growth of Python could
not be ignored.
However, why do you think it will keep on attaining the rise in the expansion
and in size? To answer the question, we dive into the market data and the
scale of Python adoption and acquisition by corporations and companies
around the world.
SO the reason behind the popularity of Python is one and simple. It will be as
popular and widely used five years from now as it was five years ago. This is
a big statement and to prove this, we need to see in detail what makes Python
so special for these developers and programmers.
Years ago, when Python came into the market, people believed it would be
dead within months of inception. In face when Larry Wall who is also the
founder and brain behind programing language Perl was delivering his third
annual state of Pearl Opinion said that there are some programming
languages out there in the market that are C++, Java, Perl, Visual Basics,
Javascript and in the last Python. Back then, the leading language for
programming was C++ and Perl was on the third number in the market.
Python had very low demand and was not included among the PLs that could
grow.
However, in the years to follow, Python grew with tremendous speed and
outshined Perl as well. According to Stack Overflow, the visitor volume to
question and enquire about Python increased more rapidly than Perl.
Following are the reasons behind the rise and super demand for Python
among developers.
Data Science
This is one of the most adored languages among data scientists, unlike R and
C++. SO the current era is the era of big data, and since Python supports large
sets of libraries, internet, and prototypes, Python is the best and fully suited
language for the operations. PyMySQL, PyBrain, and NumPy are the reason
why is Python so extensively demanded. In addition, integrations and
programming are the things a programmer has to deal in everyday life, and
this is the reason behind the huge demand for Python as well because it
provides easy integration even of existing apps or sites to other programming
languages. This makes it future-oriented and scalable.
Machine Learning
In the industry these days, artificial intelligence and machine learning have
created a huge buzz with every industry investing in the areas to maximize
their revenue and cut costs. This is not really possible without the induction
of Python. It is actually an interpreted language, and its use makes it
elucidated enough to be interpreted by machines and to be understood by the
hardware. The growth of ML has been on the rise in the last few years, and I
think this is also one of the reasons why Python has witnessed a surge in its
demand.
Automation
software development applications are SCons, which is for build control,
Roundup, and Trace, which are for bug tracking and project management.
For IDE integrated development environments, Roster is used.
• The most important stuff related to Python is that it provides special
applications for education.
• We all know that the gaming industry is evolving with great potential
and ability to create replicated amount of revenue. The applications of Python
for gaming is very safe to use and have been pretty much and widely used.
PyGame and PyKyra are bi-development frameworks for games. There is
also a variety of 3D rendering options in the libraries.
• Moreover, we have applications which interest the developers to a huge
extent and are used widely. We have applications that are console-based,
applications for robotics, machine learning and web scraping and scripting
and whatnot.
These are the main reason why Python is the best fit in the industry from the
point of view of a developer.
It instructs your computer to print “hello, thanks for contacting us”. In fact,
the Python interpreter ignores all the comments. As a programmer, however,
you should not leave a comment after every line. You can put in a comment
when you need to explain something. Since long comments are not supported
by Python, it is important to use short and descriptive comments to avoid
them going across the lines.
TRIPLE QUOTES
After reading and understanding both the single and double quotes, it is now
a time to look at the triple quotes. The triple quotes are used to define the
literal that spans many lines. You can use three singles, double, or single
when defining an authentic.
Strings
Although a string is seen as a complicated thing to many beginners, it is a
term used by the programmers when referring to a sequence of characters and
works just like a list. A string contains more functionality which is specific
than a list. You will find it challenging to format the strings when writing out
the code because some messages will not be fixed easily due to its
functionality. String formatting is the only way to go away within such a
situation.
ESCAPE SEQUENCES
They are used to donate special characters which are hard to type on the
keyboard or those that can be reserved to avoid confusion that may occur in
programming.
OPERATOR PRECEDENCE
It will help you to track what you are doing in Python. In fact, it makes things
easy when ordering the operation to receive the right information. So, take
enough time to understand how the operator precedence works to avoid
confusion.
Variables
Variables refer to the labels donated somewhere in the computer memory to
store something like holding values and numbers. In the programming typed
statistically, the variables have predetermined values. However, Python
enables you to use one variable to store many different types. For example, in
the calculator, variables are like memory function to hold values which can
be retrieved in case you need them later. The variables can only be erased if
you store them in the newer value. You will have to name the variable and
ensure it has an integer value.
Moreover, the programmer can define a variable in Python by providing the
label value. For instance, a programmer can name a variable count and even
make it an integer of one, and this can be written as; count=1. It allows you to
assign the same name to the variable, and in fact, the Python interpreter
cannot read through the information if you are trying to access values in the
undefined variable. It will display a message showing syntax error. Also,
Python provides you with the opportunity of defining different variables in
one line even though this not a good according to our experience.
Global variables refer to the variables defined in the primary file body. These
variables are visible throughout the file and also in the file that imports
specific data. As such, these variables cause a long-term impact which you
may notice when working on your program. This is the reason why it is not
good to use global variables in the Python program. We advise programmers
to add stuff into the global namespace only if they plan to use them
internationally. A local variable is a variable defined within another variable.
You can access local variables from the region they are assigned. Also, the
variables are available in the specific parts of the program.
MODIFYING VALUES
For many programming languages, it is easy for an individual to define a
particular variable whose values have been set. The values which cannot be
modified or changed, in the programming language, are called constants.
Although this kind of restrictions is not allowed in Python, there are used to
ensure some variables are marked indicating that no one should change those
values. You must write the name in capital letters, separated with
underscores. A good example is shown below.
NUMBER_OF_HOURS_IN_A_DAY=24
It is not mandatory to put the correct number at the end. Since Python
programming does not keep tracking and has no rules for inserting the correct
value at the end, you are free and allowed to say, for example, that they are
25 hours in a day. However, it is important to put the correct value for other
coders to use in case they want.
Modifying values is essential in your string as it allows a programmer to
change the maximum number in the future. Therefore, understanding the
working of the string in the program contributes a lot to the success of your
program. One has to learn and know where to store the values, the rules
governing each value, and how to make them perform well in a specific area.
Computer systems do not contend with mere possibility. They contend with
actual numbers (with decimal points included). It is quite possibly an option,
however, that you may not notice any recognizable options on your display
screen inside. It takes place to be as part of the fact actually store and
analyzed as a series and combinations of zeros (o) and ones (1).
This conversion process recognizable to the number takes place to be a part
of fact called encoding. The reverse process takes place to be as part of the
fact called decoding. ASCII and Unicode frequently tend to be more of the
favored among users and especially beginners, as it relates to Python strings,
which tend to take place in a hidden bit of Unicode that remains recognizable.
Unicode was originally coded to include all things considered and bring
consistency as a major aspect of encoding. You can take in additional about
Unicode from here.
QUIZ
1. Why do you think multi-line statements are necessary we can simply write
a single line, and the program statement will run just fine?
2. List the variable scope types?
3. Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
ANSWERS
1. Multi-line statements can help improve formatting/readability of the entire
program. Remember, when writing a program always assume that it is other
people who will use and maintain it without your input.
Modules will be optimized but only in the event that they are available with
the version of Python that you are using.
cProfile is going to be what is going to be used in Python 3.4.
Importation
In the C version of Python, you are going to notice the name of the modules
that you use are going to begin with the letter c so that it can be set aside as
being written in a different language.
When you are importing this file, you are not going to use the c for the import
process.
The reason that you are going to forget the c is because you are going to be
using the original Python version. The code will be converted to C in the
program.
Example
Import cName as Name
Except Import error for this file.
Import Name
Examples
Python 2.x is going to carry out commands in C over a thousand times faster
than if you were to use a different method.
In Python 2.x you are also going to add a c to the string function.
Python 3 is going to replace that c with an io
A cprofile in Python is going to have overhead added to it and that is why it
is going to be the one that is recommended for you to use.
If you are using a version of Python that is 3.3 or higher the celementtree is
going to be the same as the element tree. Element tree ends up being about
twenty times faster and is going to consume less memory than other methods
that you have to choose from. As mentioned, if you have version 3.3 then it is
going to be done by the program automatically since it is a faster method of
keeping the program going.
Smaller loops should be used with a generated expression or through the use
of list comprehension.
Comprehension can be also make for loops go faster so that you do not have
to worry about making a mistake.
The files that are in the directory is usually going to be used for making sure
that all the rules for the loop that you are making are being followed. If
conditions are going to make the search through the directory more narrow so
that it goes faster.
Expressions that have been generated can be used with a multitude of lists as
long as you use the zip function.
Data type
To figure which data type you should use, you are going to need to look at
the application and determine how it is going to run with each data type.
In comparing two lists to see if there is anything similar between the two of
them, you are going to have to go through each element individually, but this
is going to take up too much of your time and you may end up forgetting
what you are trying to do.
Instead of going through the list you are going to use a function that is going
to go through the list for you and find what each list has in common.
This method should only be used on smaller lists. There is another method
that you can use for lists that have more entries so that it is more efficient and
less time consuming.
A set is going to help speed up the process when you are using it as a
function.
A dictionary is not going to be recommended when you are using a set since
sets are mutable, but a tuple is going to be the perfect choice for you.
Dictionaries that have to be used are going to convert your objects into the
tuple or list so that you can do the proper operation so that it can be converted
back to the form that it should be in for the program.
Methods such as this are going to be faster than attempting to duplicate the
string.
Other
Logging and database access is going to be handled by a decorator.
There is no function that has been placed into Python as of yet that is going to
enable you to make a list smaller as you work on it. However, you can use a
recursive function which is going to do the same thing, but it is going to do it
when you have finished creating your list.
A GUI button has been placed in Python that was originally based off of the
TcI’s Tk. This is going to give you access to things that are in Python 4 and
Python 3 that you do not have access to in other versions of Python.
Thanks to Python, there is a way that you can switch the place of two
numbers that are all in one line.
Example
Z, t = 15, 5
Print ( z, t)
Z, t – t, z
Print (z, t)
First ( 15, 5)
Second ( 5, 15)
This function actually makes a new tuple while the previous one is left
unreferenced.
Comparison operators
Comparison operators can be aggregated so that you can chain the two
operators together.
Example
Z=5
Result = 2 < z < 25
Print (result)
Example
Z = 15 if ( t == 5) else 50
Example
When the number of parameters has been set, ternary operators can be used
to evaluate the smaller numbers that are in the expression
Example
Def small( d, r, g) :
Return d if d <= r and d <= g else (r if r <= d and r <= g else g)
Print(small(2, 5, 2))
Print(small(6, 3, 3))
Print(small( 3, 3, 4))
Print(small(9, 8, 7))
Output
2,3,4,5,6,7,8,9
Multi-line strings
Example
#you are going to choose one from the statements that are listed where the
placement_id is 6
#you are going to choose one from the statements that are listed where the
placement_id is 6
So, to correct this, the string is going to be split up and there are going to be
parentheses that will enclose the entire code.
Example
#you are going to select from the multiple rows available where the
placement_id is < 6 and selected by number.
The number of variables that are in your list should never go past the number
of elements that are in your list
Example
Listest = [ 5, 8 2 ]
Z, u, I = listest
Print ( z, u, I )
Interactive operators
The underscore is going to take the place of the expression that you are
wanting to test so that you are not testing the actual expression and
potentially messing up your code.
Example
3+5
Print _
8
Set comprehension and dictionaries are going to work just like list
comprehension does.
Example
Print (settest)
Print( dicttest)
When you are using < : > there is going to be a difference from just the
regular commas.
Code that is run in Python 3 is going to replace the xrange with just the
normal word of range.
We are happy that you have made up your mind to start the journey of
mastering Python. One of the most common questions that new learners want
to know is how to learn a given language.
Well, the first step in becoming a master in Python programming is to ensure
that you know how to learn. Knowing how to learn is a vital skill in computer
programming.
So why is it important for you to know how to learn? Simply put: language
changes, new libraries are created, and new tools are released. Thus, if you
know how to learn, it will be important to help you remain at par with these
changes and become a successful developer.
This chapter will provide you with tips that will help you kick start your
journey of becoming a master in python programming.
If you find it hard to come up with a python practice project to work on, you
can get started with the following:
Simple calculator.
Steve Tudor
Text Copyright ©
All rights reserved. No part of this guide may be reproduced in any form
without permission in writing from the publisher except in the case of brief
quotations embodied in critical articles or reviews.
Legal & Disclaimer
The information contained in this book and its contents is not designed to
replace or take the place of any form of medical or professional advice; and is
not meant to replace the need for independent medical, financial, legal or
other professional advice or services, as may be required. The content and
information in this book has been provided for educational and entertainment
purposes only.
The content and information contained in this book has been compiled from
sources deemed reliable, and it is accurate to the best of the Author's
knowledge, information and belief. However, the Author cannot guarantee its
accuracy and validity and cannot be held liable for any errors and/or
omissions. Further, changes are periodically made to this book as and when
needed. Where appropriate and/or necessary, you must consult a professional
(including but not limited to your doctor, attorney, financial advisor or such
other professional advisor) before using any of the suggested remedies,
techniques, or information in this book.
Upon using the contents and information contained in this book, you agree to
hold harmless the Author from and against any damages, costs, and expenses,
including any legal fees potentially resulting from the application of any of
the information provided by this book. This disclaimer applies to any loss,
damages or injury caused by the use and application, whether directly or
indirectly, of any advice or information presented, whether for breach of
contract, tort, negligence, personal injury, criminal intent, or under any other
cause of action.
You agree to accept all risks of using the information presented inside this
book.
You agree that by continuing to read this book, where appropriate and/or
necessary, you shall consult a professional (including but not limited to your
doctor, attorney, or financial advisor or such other advisor as needed) before
using any of the suggested remedies, techniques, or information in this book.
Introduction
Most people are scared of learning a new coding language. They know that it
would open a lot of doors for what they would be able to do with their
computers, but they worry that coding itself is too hard for them to learn how
to work with. If you do not take the proper time to learn a new programming
language, the whole process of programming could be difficult. But when it
comes to finding a good language that will help you write almost any code
that you would like, then it is time to take a look at the C# programming
language. This chapter will take you through some of the basics that come
with using the C# coding language so that you can start using it yourself.
What is special about C#?
The first thing that you might want to look into when it comes to a coding
language is to understand why C# is so special and why you would even want
to learn how to use this particular programming language.
There are many different coding languages out there to choose from, and they
all work differently.
But you will find that there are a ton of benefits that come with using the C#
program, and we will explore some of them inside this guidebook. Even
though you are just a beginner, this is a great coding language to work with
and will allow you to design so many programs of your own.
While there are many different options available if you want to get started
with coding, none are as great to work with like C#. Some of the benefits of
going with C# rather than some of the other programming languages include:
As a beginner, there are a lot of parts of the code that won’t be easy for you
to learn. You will learn them as you go, but the library that you can use with
C# is a great resource that will be of great help to you. You can place these
functions into the code without a lot of hassle being involved. You can even
use them to make some changes to the code, so it works the way that you
want.
Easy to learn
C# is widely considered as one of the easiest programming languages you
can learn how to work with. While there are a few parts that are more
complicated than some other coding languages, this is not a difficult one, and
you’ll start recognizing different parts of the code pretty quickly as you
continue to use it.
}
}
Now you can access the command prompt and type:
csc FirstProgram.cs
After you issue this command, the compiler for C# will process this file and
then create an .exe file in the same location as your code. For example, if you
saved the original file on the desktop, you should see a new program come up
called ‘FirstProgram.ee.’ right in the same place. If there is an error in the
code that you wrote, you will see an error message come up.
Now you can run this application by entering ‘FirstProgram.exe’ into the
command prompt. If everything was done correctly, you should see that the
command prompt will display the message: ‘Using C# is fun’.
Analyzing the program
Now that you have written out the program that you want to use, it is time to
take a look at the different parts of the code and what they all mean. The code
above is pretty simple to work with, and you will find that it will include a
variety of the different components that you need to write out a decent code
inside of C#. Some of the parts that you should look for include the
following:
Converting an “s” type to “t” type allows you to treat “s” as “t” while running
your program. Sometimes, this process requires the programmer to validate
the type conversion. Check the examples below:
Explicit Conversion
Use this conversion if there’s a chance of information loss. For instance,
you’ll experience information loss while converting floating-point values to
integer values (i.e. the fractional section will disappear). You might also lose
some data while converting a wide-range type to a narrow-range type (e.g.
long-to-int conversion, double-to-float conversion, etc.).
To complete this process, you need to use the “type” operator. Check the
examples below:
class Example
System.Console.WriteLine(yourDouble);
System.Console.WriteLine(yourLong);
yourDouble = 2e9d;
System.Console.WriteLine(yourDouble);
}
If compiled and executed correctly, that program will give you these results:
Implicit Conversion
You can only perform this conversion if data loss is impossible. This
conversion is referred to as implicit because it doesn’t require any operator.
The C# compiler will perform implicit conversion whenever you assign
narrow-range values to variables that have a wide-range.
String Conversion
C# allows you to convert any data type to “string”. The compiler will
perform this conversion process automatically if you will use “+” and at least
one non-string argument. Here, the non-string argument will become a string
and the “+” operator will produce a new value.
Chapter 3 Arrays and Loops
I solemnly promise not to bore you straight out the gate in this chapter with a
long discussion on abstract logic. However, it’s important for me to make the
case that all of this is highly important in the pursuit of a stronger grasp on
programming. A lot of programming books will try to teach you the
essentials, but they’ll fail to teach you the underlying concepts that actually
explain why something works the way that it works. This means that in
effect, your learning will be incomplete. You may have absolutely no idea
why something works in the way that it does.
This is the last place that you want to be when it comes to logic, though.
Logic and programming go so intrinsically hand-in-hand. Back in my time in
undergrad, I would constantly see people confused about why something
worked in one way or another, or why a program didn’t work even though
they were so sure their logic was sound.
When I would go to review their logic, though, their program would be
wrong in some glaring way, at least from a logical standpoint. Because of
this, I’ve really come around to the opinion that logic and the underlying
concepts behind programming are some of the most important things that you
can grasp.
Let’s start our discussion of arrays with a simple question. What would you
do if you needed to connect several variables together in some way? As in,
what if you needed to access a bunch of variables from the same location?
The simple answer is that you couldn’t, at least not with what you know now.
This is an issue, and allow me to show you why.
If you had to start take inventory of a bunch of items in your program, then
you may find yourself doing something like this:
int item1 = 3;
int item2 = 2;
int item3 = 6;
int item4 = 5;
As you can see, this would get unwieldy after a while. This is not even to
mention the fact that you’re creating so many extraneous variables that you
really don’t need. What could you do instead of creating all of these
variables?
The ideal solution would be if you had one singular variable called item,
from which you could access all of these values stored with in. Well,
fortunate for you, you can do exactly that.
The concept of storing a bunch of variables together is known as an array,
and they are a central concept to computer programming. Let me explain how
they work.
Remember how we talked about how computers store values in what are
essentially little boxes in the computer’s memory that you can reference
through the use of a variable (or by directly referring to the given location in
memory, but that’s for a more advanced language than this one)? Well, arrays
allow you to actually set a bunch of boxes aside and declare them all to
contain related data. So what does this mean?
Well, for one, it tells the computer that this specific location in memory is
related, meaning that when you want to move through this data, it actually
goes faster since the computer doesn’t have to randomly pull information
from different places in memory. Understand that computers don’t store
values in a rational way, especially not in RAM, and when you’re trying to
pull information from RAM there’s always a pretty decent chance that the
computer will have the values scattered all over the place. When all of the
boxes are there together and the computer knows they’re related, it’s easier
for the computer to move from box to box efficiently.
However, on top of this, what this essentially means is that to the computer,
these things are related. That is, all of these boxes connect in one way or
another. You’ve already told the computer how big of something is going to
be in these boxes, how many boxes it needs to set aside, and a variety of
other information.
Arrays then offer the optimal way to store related information. For the record,
this doesn’t have specifically to do with control flow but it is an extremely
important lesson that we needed to cover in this book and it does fit in well to
the overall lesson of control flow, so we’re going to cover it here.
Let’s go back to the inventory example. Let’s say that we wanted to create an
array of integer values that could hold as many as 10 items. To do this, we
would do the following:
int[] item = new int[10];
This initializes an array with 10 spaces.
You can then start adding values to the array by referencing indices. An
index of an array is a specific location within the array, or in other words, a
specific one of the boxes which was set aside. When you initialize an array
like we did above, which you can refer to as a soft initialization, all of the
values are zero from the get-go and essentially waiting to be filled in.
To understand how to refer to an index of an array, you have to understand
how computers understand them. Computers don’t count things starting
from 1 like we do. They actually start at 0. This means that if you want to
refer to the first index in an array, you would refer to the one at index 0. If
you want to refer to the third index in an array, you would refer to the one at
index 2, and so on and so forth.
}
The while loop, since it is has such a unique and simple construction, finds
much of its utility in its usage as a game loop. While this can refer to games,
it doesn’t specifically and only refer to games.
Rather, the game loop refers to the idea of creating a variable such as running
or hasWon which you can set to true or false at the start of a variable. The
loop will be then set so that it runs for as long as that condition remains true.
As a result, the loop will keep running over and over and won’t stop until
something happens which changes this variable to be set to false.
This is useful when you have numerous exit conditions for the loop, but it
also is useful in a general way when a more sophisticated loop condition may
be tricky or too exacting. With this, you’re able to set the exit condition under
things like if statements and so forth to ensure that the loop runs until you’re
absolutely certain that you don’t want it to run.
Let’s test out the functionality of a while loop by creating a loop that will
count from 1 all the way up to 10. The way that we’d do this is pretty simple.
int i = 1;
while (i < 10) {
Console.WriteLine(i);
i++;
}
Console.WriteLine(i);
If you were to run and test this loop, you can see that it would run 9 times.
Each time, it would print the current value of the integer i, then it would
iterate i up by 1. On the 9th run, it iterates 9 up to 10. At this point, the loop
exits since i is no longer less than 10. This leaves our i set to 10, and we
verify this when we leave the loop by counting the last number.
As is quite clear, while loops are certainly not the most difficult thing that
you’ve ever encountered. The logic behind them is actually rather intuitive
and the chances are low that you’re going to be particularly at a loss for
understanding here. With all of that said, it’s time that we move on to the
next loop.
The next loop that we need to cover is the do while loop. Do while loops are
on the surface very similar to while loops, but there is one major distinction.
Do while loops will always run a certain block of code at least once, even if
the condition for the loop isn’t true. However, if the condition for the loop is
true, then the loop will continue running until the condition isn’t met.
In order to better illustrate what I mean by this, here is the syntax for a do
while loop with appropriate notes tucked inside:
do {
// This code runs at least once.
// But it will keep running if...
} while (condition); // ... this condition is met, and will run until it
isn’t.
Because do while loops aren’t terribly difficult, we’re going to skip the
example here and move straight on to for loops.
For loops serve a diametrically different purpose than while loops do, and
this purpose is actually readily apparent in the implementations of for loops
in some languages. For example, while Python follows the basic structure and
philosophy of the for loop from C and C-style languages, it massively differs
in the way that it implements it.
The for loop serves its purpose best as an iterative loop. This means that you
should most ideally use the for loop whenever you need to work your way
through a given set of data. Hopefully, the reason that we spent so long
talking about arrays is becoming more and more clear now.
For loops essentially work by allowing you to define a starting variable. This
variable is the one which is going to be iterating through the data, and on
every instance of the function, it will iterate by a given step. You also will
define the range of the loop. This is the domain for which the loop will
execute. It’s pretty much synonymous with the conditional statement of while
loops, but it functions here as a definition of the range of possible iterator
variables i over the course of the given domain. Basically, this tell the for
loop for how long the statement will execute and over what particular set of
data. Lastly, you define the iterative step, which pretty much just says the
size of the steps that the iterator variable needs to increase or decrease by.
These aren’t just incremental and decremental operators, they are anything
that can be performed in a systematic and repetitive way and that will change
i each time. However, in these terms, there is no doubt indeed that the
incremental and decremental operators are the most common ones that you
will see.
Let’s go back to our definition of the array item for a moment. Create a
new project called Chapter3. In the main function of that project, go ahead
and type the following:
int item[] = {3, 5, 7, 1, 2, 8, 3, 5, 4, 1};
Now, let’s say that using a for loop, we wanted to iterate through every item
in this list, printing each number out one at a time. We can do this very
easily. Firstly, we need to look at the syntax of the for loop:
for (iterator variable initializer, set to lower bound; condition set to
upper bound; iterative step) {
// code goes here
}
So, for this specific program, we recognize that the array starts at 0, so we
must set the lower bound to 0. The upper bound is the size of the array,
because we can’t go bigger than the array obviously. We can access the size
of the array using the .Length property in relation to the array. Lastly, we
want the iterative step to be 1, so we’re just going to go ahead and put i++
here. Putting these into the terms used in the creation of the for loop, we get
the following:
for (int i = 0; i < item.Length; i++)
{
// code goes here
}
Now, we just need to print out the value of every item within the array. We
can do this by accessing the current index using the i variable:
for (int i = 0; i < item.Length; i++)
{
Console.WriteLine(item[i]);
}
With all of that done, you’ve now defined a for loop. You can go ahead and
try running and testing this program. Everything should go off without any
real issues and all of the values should print out.
With that, we’ve covered the second major beast of control flow. We now are
going to move on to one of the last major things that we’re going to cover in
this book: writing functions in C#.
Chapter 4 Operators
In this chapter, you will understand how you can make your program achieve
complex tasks—all with the help of Operators! Conditions and operations are
the heart of every programming language. These are the things that make
your program capable of computing and evaluating inputs and variables.
Operators
There are several types of operators that you can use in C:
1. Assignment Operators
2. Arithmetic Operator
3. Relational Operators
4. Logical Operators
5. Miscellaneous Operators
Assignment Operators
Assignment Operators are used to assign variables their values. Here are
some of the basic assignment operators:
Operator Description
= Basic assignment. Use this to assign any value to a variable.
A= B + C
Use the codes below to demonstrate how these operators are used:
#include<stdio.h>
int main()
{
int a = 3;
int b = 9;
int c ;
c = a + b;
printf ("c is the sum of a and b. The value of c is %d\n", c);
c+=a;
printf ("c is the sum of c and a. The new value of c is %d\n",
c);
c-=a;
printf ("c is the difference of c and a. The new value of c is
%d\n", c);
c*=b;
printf ("c is the product of c and b. The new value of c is
%d\n", c);
c/=a;
printf ("c is the quotient of c and a. The new value of c is
%d\n", c);
return 0;
}
Here’s the output:
Figure 1: Assignment Operators Exercise
Arithmetic Operators
Arithmetic Operators allow you to perform formulas with variables. Here are
some of the basic arithmetic operators. Let’s use the values: a = 3 and b = 9.
Operator Description
+ Add the values
a + b = 12
- Perform subtraction
b–a=6
* Perform multiplication
a*b = 27
/ Perform division
b/a = 3
% Modulus – show the remainder after division
b/a = 0
++ Add one
a++=4
-- Subtract one
b--=8
To see how this works, we will use the if statement. For now, copy and paste
the code below on CodeChef.
#include<stdio.h>
int main()
{
int a = 3;
int b = 9;
if (a==b) {
printf ("Values a and b are equal \n");
}
if (a!=b) {
printf ("Values a and b are not equal \n");
}
if (a>b) {
printf ("a is greater than b \n");
}
if (a<b) {
printf ("b is greater than a \n");
}
if (a>=3) {
printf ("a is greater than or equal to 3 \n");
}
if (a<=3) {
printf ("a is less than or equal to 3 \n");
}
return 0;
}
Did you get the same output messages?
Figure 3: Relational Operator Exercise
Logical Operators
Next, let’s get to logical operators. These operators test and compare the
output of a statement or condition. The test will either return a True or False
value. Let’s use the same values: a = 3 and b = 9 and add these values: c = 2,
d=a-1
Operator Description
|| OR operator . The condition becomes true when the logical
state of any of the operands is true.
((a ==b) || (c ==d)) evaluates to TRUE
&& AND operator. This returns true when all of the operands
evaluate to true.
((a ==b) && (c ==d)) evaluates to FALSE
! NOT operator. It’s used to reverse the result of the condition.
If the condition below evaluates it to True, using the NOT
operator will reverse it to False.
!((a ==b) && (c ==d)) evaluates to TRUE
Operator Description
sizeof Checks for the variable size – reflects the size of storage for
the variable type
?: Ternary operator: outputs value a if condition is true, otherwise
b will be shown
Here’s a short code to show how ternary operators and sizeof work:
#include <stdio.h>
int main() {
int first = 4;
char second='x';
int a;
int b;
printf("This is the size of the first variable = %d\n",
sizeof(first) );
printf("This is the size of the second variable = %d\n",
sizeof(second) );
a = 3;
b = (a == 3) ? 100: 200;
printf( "Therefore, the value of b is %d\n", b );
b = (a == 11) ? 200: 300;
printf( "Therefore, the value of b is %d\n", b );
}
Add other variable types to see what is the storage size:
Figure 5: Miscellaneous Operators Output
Values
Values basically pass arguments to the various copies in your function, where
you have to make changes in the parameters. For this, the swap() function is
necessary. For example:
In this chapter, we covered Logic, Keywords and Operators. In the next
chapter, you will learn all that you need to know about loops and loop break
statements.
Chapter 5 Classes
A class can be seen as a blueprint for an object. Objects in the real world
have characteristics like shape, color and functionalities. For example, X6 is
an object of car type. A car has characteristics like color, speed, interior,
shape etc. This means that any company that creates an object with the above
characteristics will be of type car. This means that the Car is a class while
each object, that is, a physical car, will be an object of type Car.
In object oriented programming (not forgetting that C# is an object oriented
programming language) a class has fields, properties, methods, events etc. A
class should define the types of data and the functionality that the objects
should have.
With a class, you can create your own custom types by grouping variables of
other types together as well as methods and events.
In C#, we use the class keyword to define a class. Here is a simple example
of this:
public class TestClass
{
public string field1 = string.Empty;
public TestClass()
{
}
public void TestMethod(int param1, string param2)
{
Console.WriteLine("The first parameter is {0}, and second
parameter is {1}",
param1, param2);
}
public int AutoImplementedPropertyTest { get; set; }
private int propertyVar;
public int PropertyTest
{
get { return propertyVar; }
set { propertyVar = value; }
}
}
The public keyword before the class is an Access Specifier, specifying how
the class will be accessed. By being public, it means that it will be accessible
by all other classes within the same project. We have given the class the
name TestClass .
We have also defined a field in the class named field1 . Below this, we have
created a constructor for the class. Note that the constructor takes the same
name as the class itself, hence the constructor’s name is TestClass() . Inside
this class, we have also defined a method named TestMethod() , and this
method takes in two parameters, param1 and param2 , with the former
being an integer and the latter being a string.
Here is another example demonstrating how to declare and use a class:
using System;
namespace CubeApplication {
class Cube {
public double length; // Length of the cube
public double breadth; // Breadth of the cube
public double height; // Height of the cube
}
class Cubetester {
static void Main(string[] args) {
Cube Cube1 = new Cube(); // Declare
Cube1 of type Cube
Cube Cube2 = new Cube(); // Declare
Cube2 of type Cube
double volume = 0.0; // Store the cube volume here
// cube 1 specification
Cube1.height = 4.0;
Cube1.length = 5.0;
Cube1.breadth = 8.0;
// cube 2 specification
Cube2.height = 8.0;
Cube2.length = 12.0;
Cube2.breadth = 14.0;
// volume of cube 1
volume = Cube1.height * Cube1.length * Cube1.breadth;
Console.WriteLine("Volume of Cube1 : {0}", volume);
// volume of cube 2
volume = Cube2.height * Cube2.length * Cube2.breadth;
Console.WriteLine("Volume of Cube2 : {0}", volume);
Console.ReadKey();
}
}
}
The code will return the following result:
Encapsulatıon and Member Functıons
A member function for a class is simply a function with a definition or
prototype within the definition of the class in the same way as any other
function. Such a function can operate on any object of the class in which it is
a member, and it can access all the class members for the object.
Member functions are simply the attributes of the object (from a design
perspective) and they are defined as private so as to implement the concept
of encapsulation. We can only access such variables using pubic member
functions. Let us demonstrate how we can set and access the various
members of a class in C#:
using System;
namespace CubeApplication {
class Cube {
private double length; // Length of a cube
private double breadth; // Breadth of a cube
private double height; // Height of a cube
public void setLength( double len ) {
length = len;
}
public void setBreadth( double brea ) {
breadth = brea;
}
public void setHeight( double heig ) {
height = heig;
}
public double getVolume() {
return length * breadth * height;
}
}
class Cubetester {
static void Main(string[] args) {
}
Since no conditional statement is present in for loop, the condition is
assumed to be always true by the compiler. As a result, the loop becomes
infinite. This loop can be terminated using an external interrupt (Ctrl +
C).
Chapter 8 Application of Graphical User Interface
In this chapter, we are going to transform our programs from just texts to a
graphical interface which will look more appealing and interesting as
compared to a line full of codes. In this section, the programmer is free to
create images of various shapes as much as they can desire. The creation of
interface requires well planning and use of intelligence to be able to express
and output appealing products to the end line of the user.
The importance of graphics is that it is able to compress tasks and visualize a
massive amount of written codes into an appealing work of art. In other
words, the graphical interface makes work easier for the end user to interact
with a program and understand the working concept of the whole program in
a very short period of time. The picture below is a snippet of the early works
of a graphic interface;
Some of the programs that enable the programmer to achieve such high
graphical properties include; CAD- Computer Aided Design and CAM-
Computer Aided Manufacturing. In this topic we are going to discuss how to
incorporate the hardware and software part of graphics in C# programming
language to achieve complex programs
Graphical software
In this study, we are going to focus on the software part of setting of pixels
until a clear image is achieved. We are going to have a deeper understanding
of functions from the graphic library that helps in controlling the settings and
clearance of the graphical pixels.
In C# programming language, the graphic library that is involved in graphical
software is very powerful. The extensive graphic library can be used to create
complex figures, shapes, images and very clear pictures. Some of the
complex operations that can be achieved in C# programming language
include the drawing of geometric figures and shapes, creation of scrolling
interfaces, creation of buttons and also menus that pull down.
We are going to get into further studies on how to create C# graphics using
Visual Studio program.
Begin with a Windows Form App project. A window called “Form 1”will
appear on the screen. This is done by the IDE of the C# programming
language. It is done automatically but the learner must know that there were a
lot of codes that were generated before the automatic creation of the form.
The form appears as shown below;
If the student is interested to see the lines of codes that were used to generate
the form he or she can click on the <> buttons in the windows form. The
following lines of code should appear;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GraphicsProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
Secondly, we want to draw a basic line in the form created above and see the
lines of codes that are used to generate the lines in graphical form. We will
draw the simple line from point A (21, 21) to point B (101,101). The diagram
below shows the illustration;
The line of code that is used to generate the graphic is as shown below;
public Form1()
{ //This is the form on which drawing will appear
InitializeComponent(); // initialization of the form
this.Text = "C# Graphics";
Graphics drawingCanvas = CreateGraphics();
Show();
Pen BlackPen = new Pen(Color.Black, 2);
drawingCanvas.DrawLine
(BlackPen, 21, 21, 101, 101);
}
Understanding our code
The first line of the statement of the code calls the initialization of the
element function. The function is used to automatically generate the form.
The second line of statement displays the texts that will appear on the title bar
of the window. The third line of statement produces the platform where the
line is drawn or the background surface of the form. The line of the statement
containing “Show ();” enables the form to be shown on the screen.
“Pen BlackPen = new Pen(Color.Black, 2);”is the piece of code that creates
the pen that will paint the line on the form.
Practical Exercise
i) public Form1()
Show();
drawingCanvas.DrawARectangle
Show();
drawingCanvas.DrawEllipse
}
iii) public Form1()
Show();
drawingCanvas.DrawEllipse
Show();
drawingCanvas.DrawString
\\ \ character
\? ? character
\b Backspace
\a Alert or bell
\n Newline
\f Form feed
\t Horizontal tab
\r Carriage return
\v Vertical tab
2. “HelloWorld”
3. “Hello
4. World”.
Chapter 11 Command Line Arguments
In C programming, it is perfectly possible to accept and to have command
line arguments. These arguments are typically provided after the program
name in the operating systems of the command line. Some of these operating
systems include Linux and DOS. Command line arguments are then passed
on to the created program from your operating system.
To utilize these command line arguments in the created program, you need to
completely understand the entire declaration for the main function first. This
main function should previously have no arguments to begin with.
Interestingly, the main function can simultaneously accept two types of
arguments. The first one would be the number of the command line
arguments. The second one would be the entire list of every command line
argument included in the program.
The main argument’s full declaration somehow appears like this:
int main ( int argc, char *argv[] )
For this code, argc is considered as the argument count. The argument count
is the given number of command line arguments passed on to the created
program. The command line is the origin for this argument. The line
argument includes the program’s name as well.
The array of the pointers for the character is regarded as the listing of every
argument. On the other hand, argv[0] will be the program’s name. For the
declaration above, it is an empty string in case the name is not yet available.
After this, every number of the element in the declaration that is less than the
argc string will be considered as one of the command line arguments.
You may handle the command line arguments using main() as your function
argument. If you combine it with other commands, argc will be considered as
the number of passed arguments. On the other hand, argv[] will be the
pointed array. This means that argv[] will point the each of the passed
argument to the created program.
You may use each of the argv elements in the same way that you will use a
string. Also, you may utilize argv and treat it as a type of two- dimensional
kind of array. In any case, the argv[argc] will be considered a null pointer.
The following is an example that can help you check if there are any supplied
arguments from the program’s command line. Based on what you observed,
you can take the necessary action.
#include <stdio.h> [B5]
if(argc == 2){
printf("The supplied argument is %s\n", argv[1]);
}
else if(argc>2){
printf("Too many supplied arguments.\n");
}
else{
printf("Only one expected argument.\n");
}
}
If you try compiling and executing the code above using a single argument
with spaces enclosed within single quotation marks or double quotation
marks, it can produce this result:
{
printf ( “%c”, x );
}
fclose ( file );
}
}
}
The program above is relatively short. However, it has effectively
incorporated the full version of the main declaration. It even performed one
useful function. First, it checks to fully ensure that the program user
successfully included the second argument. Theoretically, this will be the file
name. The program will then perform another check to verify if the file is
valid. This is done by opening the file in question. This is considered a
standard operation type. If the operation eventually leads to the opening of
the file, then fopen’s return value will have a valid FILE*; as the output. In
case the opposite is true, that will be 0. In this case, 0 is considered as the
NULL pointer.
After this, you just have to execute a loop. The loop will be used to help you
print out one character, for instance. The code is somewhat self-explanatory.
However, it has some comments included in it. You will have little trouble
deciphering how the operation works if you look at it carefully.
Typecasting
Typecasting is considered a way to change one variable from one type of date
to another, different kind of data. It is a method of making one variable into
one type, like the int variable, to another different type of variable, like the
char. This is done for a single operation. For instance, if you are thinking of
storing one ‘long’ value to a kind of simple integer, all you have to do is to
type cast the string ‘long’ into ‘int’.
You may even convert your values from one kind to another by explicitly
utilizing the cast operator.
(type_name) expression
This example will show you that the cast operator can cause division of an
integer variable by another one. It will be performed as a kind of floating
point operation.
#include <stdio.h> [B7]
int main() {
int sum = 20, count = 4;
double mean;
mean = (double)sum/count;
printf("Value of mean: %f\n", mean);
return 0;
}
If you compile and execute the code given above, it will produce this result:
Value of mean : 5.00000
Take note that your cast operator should have precedence over the division.
Therefore, the value of sum command should first be converted to type
double. Finally, it should be divided by count. This will eventually yield a
double value.
Some type conversions may be implicit. You may automatically perform this
function yourself if you prefer. An alternative would be to explicitly specify
this by using the cast operator. Using your cast operator when type
conversions are needed is actually considered a good practice, as far as
programming is concerned.
If you want to typecast a program or an operation, you have to place the
variable type, that you prefer the actual variable to, act within the inside
parentheses. These should be placed directly in front of your actual preferred
variable. For instance, (char)a will create the ‘a’ function as char.
Here is an example of typecasting “in action”:
#include <stdio.h>
int main()
{
/* The (char) is considered a typecast. This instructs the computer to
interpret the number 65 as a type of character and not merely as a
number. This will provide the character with an output for the equivalent
for the number 65 (In the case of ASCII, this will be the letter A). Take
note that the %c found below will be considered as the format code of
printing just one character.
*/
printf( “%c\n”. (char) 65 );
getchar ();
}
One of the main uses of typecasting is highlighted if you prefer to use some
ASCII characters. For instance, in case you want to come up with your own
chart of all the 128 ASCII characters, you need to use the typecast function.
This will permit you to print out all the integers as the character equivalent.
#include <stdio.h>
int main()
{
for ( int x = 0; x < 128; x++ ) {
/* Note the function of int type for x to provide output and use
* of (char) tohelp typecast x to a character that outputs
* ASCII characters that correspond to current number
*/
printf( “%d = %c\n”, x, (char)x );
}
getchar();
}
If you look closely, you will notice something really strange. If you pass the
x value to printf to pass off as a char, in theory, it is expected that the
intended value will be treated as a type of character when you write the
format string as %c. Because the char variety is considered a relatively small
integer, adding the typecast will not actually add any form of value to it!
Therefore, the typecast will come in handy if you want to force the right kind
of mathematical operation, and have it take place in the program successfully.
It will eventually turn out that in C and other types of programming
languages, the final output of the integer divisions is also itself treated as
another integer. For example, a value of ¼ turns to 0 because this is
considered less than a whole number. The process of dividing integers
eventually ignores the remaining value.
On the other hand, the division between the floating- point numbers and even
between the floating- point number and the integer is enough to make the
result show up as a type of floating point number. Therefore, if you are
planning to execute a type of fancy division that you do not want to have
truncated values, you will need to cast one of your variables into a floating-
point kind. For example, (float)¼ will come out as a .25, as per normal
expectation.
It is usually reasonable for you to store two different values in the integers. If
you are tracking patients with heart problems, you can have a specific
function that will help you compute for the age of each patient in years. You
may also include the specific number of instances that they came in for
complaints, like heart pain. One type of operation that you may want to
execute is the frequency of visits that a patient had with their physician,
because of angina or heart pain. For this particular situation, the program will
look something like this:
/* function will return age in years */
int age = getAge();
/* function will return number of visits */
int angina_visits = getVisits();
float visits_per_year = angina_visits / age;
The only problem is when you run the created program, the visits_per_year
string will give an output of zero. This will take place unless the patient with
the heart problem had a really large number of clinic visits for the duration of
the entire year. One way to help you resolve this problem is by casting one of
the given values that will be divided. This will then be treated as a kind of
floating point number. In turn, it will cause you to treat this expression like it
were really bound to be a floating- point number:
float visits_per_year = angina_visits / (float)age;
/* or */
float visits_per_year = (float)angina_visits / age;
Using this sequence will eventually bring in the right values. These values
will be stored in the visits_per_year string. Aside from the example shown
above, you may even come up with other similar programs to resolve the
problem.
Integer Promotion
Integer promotion is the method of converting values with integer types that
are smaller than unsigned int or int to unsigned int or int. See the example
below:
#include <stdio.h>
main() {
int i = 1;
char c = ‘c’; /* ascii value is 9 */
int sum;
sum = i + c;
printf(“Value of sum : %d\n”, sum );
}
If you compile and execute the code above, it will produce this result:
Value of sum: 10
For this particular example, the value of the sum is 10 because you resorted
to integer promotion. You also converted the ‘c’ value to ASCII before you
performed the actually operation of addition.
In this chapter, we discussed command line arguments. In the next chapter,
get ready to create your first program!
Great progress so far!
Chapter 12 Extension Methods
Extension Methods (introduced in C# 3.0) provides programmers with a
simple framework to “extend” the functionalities of existing types in their
programs. “Static” in nature, Extension Methods gives you the freedom to
add already present methods into your types without a need to create new
derived types or modifying old ones. They use a “this” keyword in their
parameters / parameters lists. Since they are “static” methods, it’s essential
for you to use them in static classes. However, they are used as if they were
instance methods of the extended type.
In this chapter, we will discuss Extension Methods in depth, and will learn:
Contents
What Extension Methods are
How to create them
How to applying Extension Methods to
existing types
i. Extension Methods
The OCP, Open close principle, directs programmers to write code and
functions in a way that they are open for extension all the time, but dead end
on modification. In C#, Extension Methods are a practical case of OCP,
which we can use in both custom defined and system defined user types to
cater to our requirements.
It’s also important for us to know a few basic facts about Extension Methods
and how they work. One, they have only access (and hence can only use) the
“public” properties of the data type they are extending. Two, their type
signature should never be the same as any existing method of that type.
Three, to use Extension Methods, their parent type must be in the namespace
of the calling application. Four, in the case of a method overloading (methods
with same signature), an instance method will be executed (called) instead of
the Extended Method (as per the overload resolution mechanism), and lastly,
we cannot apply Extension Methods on events, properties, and fields.
The generic, or old way, of doing that is:
Example 1:
struct MyExample
{
int num;
public MyExample(int val)
{
this.num = val;
}
public int Negative()
{
return -num;
}
}
static void Main(string[] args)
{
MyExample i = new MyInt(34);
Console.WriteLine(i.Negative());
}
While the code is quite basic, where we have created a strict “MyExample()”
that has a simple function that returns negative of our passed value.
ii. Creating Extension Methods
The code above works fine, but technically speaking we are not actually
extending the type of our existing type. Instead we have created a new type
altogether. Hence, if we are really looking to “extend” the functionality of our
existing type, we should be doing something better and more generic than
that.
Example 2:
static class MySampleExtension
{
public static int Negative(this int val)
{
return -val;
}
}
static void Main(string[] args)
{
int i = 53;
Console.WriteLine(i.Negative());
}
While the basic functionality and output of this is similar in that it will output
the negative of the passed “int”, how it works is different. See the method
declaration here: “public static int Negative()”. We are adding our method
“negative” with type “int” and are bounding it to be called only with the int
type. We are not creating a new type as in the previous example, and we are
only extending functionality of the type “int”. Hence, to create our Extension
Methods, we should:
Have a “Static” class.
Use a “public static” method with the same name as the
class and have an explicit return type.
Use the parameters type with the “this” keyword.
The “this” keyword is very important since it tells our compiler that
we are “extending” this type and are not using it as an expected argument
type.
iii. Extension Methods on existing types
Using the above created Extension Method, let’s now see how we can
call an Extension Method on our existing types. Also note that we used the
“this” keyword above, but what about the cases where we want to use
additional parameters? We can easily do this too by defining all such
parameters with their expected data type after specifying our “extending”
type with the “this” keyword. The code below will help us to better
understand:
Example 3:
static class MySampleExtMethods
{
public static int Negative(this int val)
{
return -val;
}
public static int Multiply(this int val, int multi)
{
return val * multi;
}
}
static void Main(string[] args)
{
int i = 8;
Console.WriteLine(‘ Using Extension method the input yields: {0}’,
i.Multiply(2));
}
Note that here we have defined another extension function called “Multiply”.
While we are extending it on type “int” as specified by “this in val”, the
second argument “int multi” lacks the “this” keyword. This is because we are
using the second argument as an “argument,” and extending it with the first
type. However, note that we can also pass “strings,” “char,” or “float” values
in “arguments” as our needs warrant.
The rest of the code is quite straightforward. We have created two extension
methods and are calling the “multiply” method with such an argument of “2,”
and are extending it on the value of “I” which is 8. The output of above code
will be:
Output 3:
16
Exercise 4
Task:
Create an Extension Method that checks if a string is an int or not, and if it is,
convert the string's numeric value into a corresponding int value. For
example, string str=”2345” should be converted into int or return false
otherwise.
Solution
using System;
using System.Text;
namespace SampleExtensionMethod
{
public static class SampleClass
{
public static bool IsInt(this string x)
{
float outcome;
return float.TryParse(x, out outcome);
}
Console.ReadLine();
}
}
}
Chapter 13 Nullable Types
C# provides some special types that consist of an additional null value along
with the usual possible range of values of that data type. For example, an
int32 data type can store a value ranging from -2147483648 to 2147483647
while the nullableint32 is able to store a null value along with its original
possible range. Similarly, in the case of a Boolean variable, the Nullable of a
Boolean variable is able to store a true, false, or a null value in it.
In this chapter we will study:
Contents
Type Range
Nullable Boolean True or False or Null
Nullable byte 0 to 255 or Null
The following example illustrates the Nullable type in action for Boolean and
DateTime types.
Example 2:
Namespace nullable
{
Class program
{
static void Main ()
{
int? a= null;
int? b=5;
Double? c=null;
Double? d=6
bool? Val= new bool?();
DateTime? Start= DateTime.today;
DateTime? End= null;
Console.Writeline(‘Showing values of Nullables: {0}, {1}, {2}, {3}’,a,b,c,d);
Console.Writeline(‘A Nullable Boolean Variable: {0}’,Val);
Console.Writeline(Start);
Console.Writeline(‘We don’t know yet:’, End);
Console.readKey();
}
}
}
In this program, we are using the Nullables of int, double, Boolean, and
DateTime. Later, we are simply displaying them on the console. As the
program compiles, it shows the values of the variables as:
Output 2:
6/8/2015 12:00:00 AM
We don’t know yet:
HasValue Property:
The value is of the same type as the declared type. The Has property has a
value if the Hasvalue property is true. If the Hasvalue property is false, the
Has property will throw an Exception. See the code below to better
understand this:
Example 3:
using System;
Namespace nullable
{
Class program
{
static void Main ()
{
int? a= null;
Console.WriteLine(a.HasValue); // HasValue property is false
Console.WriteLine(a.Value); // will cause an exception
Console.readKey();
}
}
Because our variable “a” has a null value the “HasValue” property will be
false. If we try to display the "Value" on the console, we get an exception.
Output 3:
False
Example 4:
using System;
Namespace nullable
{
Class program
{
static void Main ()
{
int? a= null;
Console.WriteLine(a.HasValue); // HasValue property is false
Console.readKey();
}
}
Output 4:
False
True
5
5
C#
The practical intermediate’s guide to
learn c# programming in one day step-
by-step.
(#2020 updated version | effective
computer programming languages)
Steve Tudor
Text Copyright ©
All rights reserved. No part of this guide may be reproduced in any form
without permission in writing from the publisher except in the case of brief
quotations embodied in critical articles or reviews.
Legal & Disclaimer
The information contained in this book and its contents is not designed to
replace or take the place of any form of medical or professional advice; and is
not meant to replace the need for independent medical, financial, legal or
other professional advice or services, as may be required. The content and
information in this book has been provided for educational and entertainment
purposes only.
The content and information contained in this book has been compiled from
sources deemed reliable, and it is accurate to the best of the Author's
knowledge, information and belief. However, the Author cannot guarantee its
accuracy and validity and cannot be held liable for any errors and/or
omissions. Further, changes are periodically made to this book as and when
needed. Where appropriate and/or necessary, you must consult a professional
(including but not limited to your doctor, attorney, financial advisor or such
other professional advisor) before using any of the suggested remedies,
techniques, or information in this book.
Upon using the contents and information contained in this book, you agree to
hold harmless the Author from and against any damages, costs, and expenses,
including any legal fees potentially resulting from the application of any of
the information provided by this book. This disclaimer applies to any loss,
damages or injury caused by the use and application, whether directly or
indirectly, of any advice or information presented, whether for breach of
contract, tort, negligence, personal injury, criminal intent, or under any other
cause of action.
You agree to accept all risks of using the information presented inside this
book.
You agree that by continuing to read this book, where appropriate and/or
necessary, you shall consult a professional (including but not limited to your
doctor, attorney, or financial advisor or such other advisor as needed) before
using any of the suggested remedies, techniques, or information in this book.
Introduction
C is a general high-level programming language ideal for creating various
firmware or portable applications. C is one of the most used programming
languages, as well as one of the oldest existing languages there is. It has led
to the creation of other languages such as C++. It’s one of the preferred
languages because of its power and flexibility.
Even with its low-level proficiencies, C was made to promote cross-platform
programming and has achieved a huge following, even in academic
communities. It has also been standardized and made a part of POSIX, which
stands for Portable Operating System Interface.
The first major creation using C was actually the Unix operating system.
Because of that, Unix has been always connected to C. Today, however, C
has become independent from Unix but is still viewed as an important
language for every programmer to use.
It’s good to learn C programming; it has been here for a while but because
it’s such a low-level language, it’s still very powerful and useful. It’s a great
way to get to learn other languages better. You’ll find it easy to move om to
other programming languages. C is also relatively easy to use for application
development.
C Programming Features
What features does the C Programming Language offer? Here are some of
them:
• It has this basic form of modularity; files can possibly be separately
linked and compiled.
• You have a set number of keywords that includes control primitives i.e.
if, for, switch, while and do while.
• Different assignments can be used in one statement.
• It offers different mathematical and logical operators with bit
manipulators.
• You can choose to ignore function return values if not needed.
• Typing is static for C, but weakly enforced. All the data has type, yet
can possibly be implicitly converted such as using characters as integers.
Chapter 1 Data Types
In the C programming language, data types allude to a framework
utilized for pronouncing variables or functions of distinctive data types.
The type of a variable decides the amount of space it will take and how
the bit pattern saved in it is utilized. The fundamental classification used
for data types is given below:
● Basic Types:
They are number-crunching sorts and comprises of the two following types:
(a) integer sorts and (b) floating point sorts.
● Enumerated sorts:
They are again number sorts and are utilized to characterize variables that
must be allocated discrete number values all through the system.
● Void type:
The keyword void demonstrates that no value can be assigned.
● Derived sorts:
They incorporate (a) Array, (b) Pointer, (c) Union, (d) Structure and (e)
Function.
The array and structure data types are also referred to as aggregate
types. The type of a function defines the kind of value the function will
return upon termination. We will discuss the essential data types in the
accompanying segments.
Integer Types
Here is a list of data types that follow under this category. In addition,
the storage space occupied by them and their range are also specified for
your reference.
● char
o Allocated Memory: 1 byte
o Range: -128 to 127 or 0 to 255
● signed char
o Allocated Memory: 1 byte
o Range: -128 to 127
● unsigned char
o Allocated Memory: 1 byte
o Range: 0 to 255
● int
o Allocated Memory: 2 or 4 bytes
o Range: -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
● short
o Allocated Memory: 2 bytes
o Range: -32,768 to 32,767
● unsigned short
o Allocated Memory: 2 bytes
o Range: 0 to 65,535
● unsigned int
o Allocated Memory: 2 or 4 bytes
o Range: 0 to 65,535 or 0 to 4,294,967,295
● long
o Allocated Memory: 4 bytes
o Range: -2,147,483,648 to 2,147,483,647
● unsigned long
o Allocated Memory: 4 bytes
Range: 0 to 4,294,967,295
To get the precise size of a variable or data type, you can utilize the
sizeof operator. The declarations sizeof(<data type>) yields the size of the
data type or variable in bytes. Given below is an example, which
illustrates the concept, discussed below:
#include <limits.h>
#include <stdio.h>
int main() {
printf("Data type char (size in bytes): %d \n", sizeof(char));
return 0;
}
Upon compilation and execution of this code, you must get the following
output:
Data type char (size in bytes): 1
You may not be able to comprehend the use and meaning of the void
data type in entirety right now. However, as you move forward, you will
find it easier to relate to and use this data type in your code.
Chapter 2 Data Structures, Handling and
Functions
Introduction and Significance of Data Structures
In this chapter we are going to learn about the definition of data structures
and their significance in the C# programming language. We will learn on the
importance of the data structures and when and how to use them during the
programming sessions. It is equally important to know that a great
programmer writes efficient and effective programs using very appropriate
data structures.
Programming is made up of two major components. These are algorithms and
data structures. This explains the reason why more attention is given to these
two components. A good developer or software engineer is that which has
vast skills and knowledge of data structures and efficient in programming.
Before we get deeper into the data structure there are few terms that we
should know and understand in order to become a good developer.
Algorithm complexity-this can be defined as a standard which examines the
order of the operations count that is performed and evaluated by an algorithm
which becomes a function of input data size. This standard is commonly
represented by O (f) notation which is referred to as “Big O notation or
asymptotic notation”. There are many types of complexities such as
constant, logarithmic, exponential, linear, cubic and, quadratic.
Enumerations
This can be defined as a data type that specifies the number of items by
equally assigning them to an identifier for example a name. This is made
possible by the consideration of the underlying pattern of the base type of the
components of the specification or the enumeration.
The declaration of an enumeration can be done as shown below;
enum Months { January, February, March, April, May, June, July,
Month = Month.January;
if (month == Month.February)
The first element is always a zero when there is no explicit value which is
assigned to the specified or enumerated items. The subsequent elements will
uptake the successive value after zero. On the other end, the specific values
that originate from integral types can always be assigned to specified
elements of enumeration as shown below;
Structs
The keyword that is used to declare a struct is “struct”. They are referred to
as light container weight for objects. They are mostly applied when data is
needed for collection of types of variables.
Structs can be compared to classes. Structs have methods, constructors and
interfaces. The other major differences include;
Structs are usually the value types whereas the classes are
considered to be reference types.
Structs cannot inherit as compared to classes.
Structs require a less memory space and is less expensive as
compared to classes.
dana.heightInMtrs = 1.75;
dana.weightInGrams = 50000;
if (dana.birthDate < DateTime.Now)
The example below shows how constructors can be used in structs for
initialization;
using System;
struct Girl
string name;
DateTime birthDate;
int heightInMtrs;
int weightInGrams;
int weightInGrams)
this.name = name;
this.birthDate = birthDate;
this.heightInMtrs = heightInMtrs;
this.weightInGrams = weightInGrams;
DateTime(1975, 8, 19),
1.75, 50000);
In summary, structs are best used for performance reasons. They work best
when they are holding data amounting to 16bytes but if the programmer is in
doubt he or she can utilize the classes.
At this point we are going to study and compare the different data structures
using algorithm complexities. We are going to encounter with operations
such as searching, addition, deletion and accessing of data by use of indexing.
This will also help us in choosing which data structure to use when
programming or developing our codes. The table below is an illustration of
basic operations done by the complexities;
In this section of the book we are going to discuss situations in which the data
structures listed in the table above is going to be used.
Array
As discussed before, this is a grouping or collection of number of
components of a similar type. We can also refer to the arrays as “a small
container of data having a predefined size”. Addition of new elements into
an array as shown in the table is a very slow process. For this to occur
successfully, allocation of definite space is done and an extra space that can
transfer data from one array to another. Searching of an array is also a slow
process because the comparison is done in accordance to the needed value.
Deletion of an element from the array is a slow process because it’s a reverse
of the addition process. In this case a definite memory is allocated and a
single space is subtracted. However, accessing an array is very fast and
efficient because it utilizes indexing.
Arrays are best for situations like processing fixed amount or number of
components which should be accessed by the use of an index.
Dynamic Arrays
Linked lists
These can either be singly or doubly linked lists. The major function done by
both the singly and doubly linked list is the storage of collection of
components by maintaining their order. They are represented in the memory
as dynamic and pointer-based.
Addition into the linked list is a very fast process. Although it is slower than
dynamic arrays, it is an advanced process. This is achieved by a new
allocation of memory space. It is a high-speed process that is always
unpredictable. Searching is a very slow process because it uses the same
principle as dynamic arrays to traverse all the elements during the search.
Deletion of an element is a slow operation. This is because searching is done
before deletion hence the indexing process makes it generally slow.
In summary, a linked list has a fast addition process. It is suitable for
situations when addition and removal are needed at a faster rate at both sides
of the linked lists.
Stack
This is a linear data structure that has three major steps; addition of
components to the top of the specific stack(push), removing components
from the top of the specific stack(pop) and inspection of the components at
the top of the stack without interfering with the order(peek).
The addition and deletion of the stack is a very fast process because a
constant time is used. The stack does not have the searching and accessing by
index features. It generally works with the LIFO technique where the Last In
is the First Out.
Stack is used in situations where LIFO (Last In First Out) is applicable.
Queue
This is also another type of linear data structures that is specific to two
operations: addition of a component to the tail (enqueue) and extraction of
the component from the head (dequeue). The two processes are fast because
it utilizes a constant timing. The operations here are similar to the processes
in addition and deletion of linked lists.
The Queue uses the FIFO technique where First In usually leads to the First
Out. Similar to stacks, the searching and access by index is not supported by
the queue. Apart from FIFO, the queue embraces the concept of Breadth-
first search (BFS). This works by starting from the first component in the
list and hence its surrounding components are aligned in a queue.
Queue is appropriate in situations where the BFS and the FIFO are
applicable.
Our objective is to create a simple code that is going to output the subsets of
W. We start from an empty set of {}. We add the empty set to each and every
component of set W and we get the collection below;
Then we add to each element to the subsets from set W so that the ones
which have not been included can be reflected in the two elemental subsets.
There is freedom of addition up to the N-elemental subset
At this point, we are going to focus on and choose the right data structure to
implement the above algorithm. In order to choose the right data structure,
we are going to consider the type of operations that are needed to be done. At
the moment, the main operation to be done is traversing through all the
components of the set (subset). This operation can be done efficiently by the
array, dynamic array, hast tables and almost all the other data structures.
i) We shall first consider the array because it is the simplest data structure to
work with.
ii) The next step that comes after picking the data structure is to
pick criterion for storing one of the 2-elemental subsets for example
{beer, money}
iii) Here we check the operations which will efficiently execute this
subset. The operations to be done are addition and checking of the
components of the subset. From our previous knowledge, we know that
arrays and linked lists perform a quicker search. We choose the data
structure that is fast in addition and searching.
iv) We pick on the hash table (set implementation) and hence
keep the collection or grouping of the words in the subsets as shown
below;
{sea, wine}, {sea, computer}, {sea, joy}, {wine, computer},
{wine, joy}, {computer, joy}
v) Using the chosen structure, addition and traversing through the
components of the subset is very efficient. At this point we get to notice
that other data structures such as; stacks, Sets, queue and list also qualify
for this characteristic. On the other end, if we study further we notice that
this set W works with FIFO technique. At this point we choose the queue.
vi) Lastly, we obtain that queue is the best data structure for
this program.
Using the queue data structure
We can illustrate and describe the algorithm using the following procedure;
i) Begin the queue with an empty set {}
ii) Dequeue the components of the subset. Add each and every
element from W in relation to the subset it is located.
iii) Repeat until the queue is empty.
It is very evident that once a developer understands the needs of the program
and hence selects the correct data structure, implementation becomes very
quick and easy. The example below is how the program will look after
applying the correct data structure;
Queue<HashSet<string>>();
subsetsQueue.Enqueue(emptySet);
while (subsetsQueue.Count > 0)
Console.Write("{ ");
Console.WriteLine("}");
if (! subset.Contains(element))
newSubset.UnionWith(subset);
newSubset.Add(element);
subsetsQueue.Enqueue(newSubset);
When the program is run through the compiler the following will be
displayed;
{}
{ sea }
{ wine }
{ computer }
{ joy }
{ sea wine }
{ sea computer }
{ sea joy }
{ wine sea }
sea 0
wine 1
computer 2
joy → 3
using System;
using System.Collections.Generic;
"happiness" };
subsetsQueue.Enqueue(emptySet);
Print(subset);
if (subset.Count > 0)
newSubset.AddRange(subset);
newSubset.Add(i);
subsetsQueue.Enqueue(newSubset);
}
Console.Write("[ ");
Console.WriteLine("]");
After running the compiler through the program it will display the following
output;
[]
[ ocean ]
[ beer ]
[ money ]
[ happiness ]
[ ocean beer ]
[ ocean money ]
[ ocean happiness ]
[ beer money ]
[ beer happiness ]
[ money happiness ]
alphabetical order and for each one of them prints all the names of the
There are many solutions for such an example illustrated in the table above.
We are going to utilize the knowledge we have learned in the previous topics
about data structures to solve this problem. We shall use the examples of data
structures in the Dot Net Framework.
From the requirements of the codes, we need to sort the names of the cities.
This makes us open our line of thoughts towards the data structures that can
make us achieve the sorting criterion. For this case we can consider a
balanced tree either set implementation or dictionary implementation.
However, the records of the phonebook also contain the names of the city and
hence we have to use dictionary implementation. As a result, the list
containing the names of people will be kept with their respective cell phone
numbers. We will initialize the key to be the names of the people and the
value to be their respective phone numbers
The following is an illustration of the program using dictionary
implementation;
SortedDictionary<string, string>>();
using (reader)
{
while (true)
if (line == null)
break;
phoneBook.Add(name, phone);
phonesByTown[town];
}
If the code were run by the compiler, the following would be the appropriate
display;
Town Portland:
Mary - 1-234-765-1983
Laura - 1-454-345-2345
Paul - 1-535-675-6745
Donna - 1-387-387-2389
Kenneth - 1-541-754-3010
class Example
{
//This is the body of the “Example” class.
}
Public Sample()
{
//Insert what you want to say here.
}
Before we dive much more into these classes and start to create one of our
own classes, you should make sure that there is already some object that is
able to fit inside. You can do this with the help of a new keyword and then
you can add in all of the constructors that you will need to work with.
When we are creating these codes in the C# language, you will not be able to
do any manipulation on the objects that you are trying to create directly.
Instead, you will need to be able to assign the objects over to the right objects
ahead of time so that you can handle all of the manipulations that you want
later without problems. Remember that when you would like to access these
methods and the properties that go with the object, you will need to indicate
to the compiler which identifier will go with the object, and then make sure
the dot operator is there.
Organizing the Classes
It is important here for us to learn the proper manner to use in order to
organize the classes that we want to work within this kind of language. There
is mainly just one rule that we want to follow to make sure that this works
and that rule is that we need to make sure that the classes are saved as a .cs
file. This makes them easier to find and work on later when we would like to
pull them out.
Technically, the C# language is going to allow us to save all of the classes
that we will make in a program in just one big file and the compiler is going
to be able to read through it all without an error. But there are going to be a
lot of programmers who find that saving their classes in their own individual
files makes it easier to bring out the classes when you need them later, and
can keep things more organized. You can choose through which method you
like working with here.
Another thing that we are going to use here to gain some more familiarity
with when working in C# is the namespace. This is going to be a set of
classes that are going to be related in some manner. The way that these will
relate with one another is going to change based on the situation of how we
use this, but they should make sense as to why they are related. These could
include their classes, structures, interfaces, and even some of the information
that is placed inside of it. It is even possible for us to take a few of these
classes together and make our own namespace, even if they are sorted out
into different parts of the memory of the computer.
If you are looking to create a new namespace on some of the codes that you
worked with previously, you need to make sure that the directive of “using”
to make things a little bit easier. Most programmers are going to be able to
find that it is easier to put into the very first lines of our file. This ensures that
you don’t accidentally forget about these later on. After you have been able
to insert this directive, then you can go through and declare the namespace.
How to Access Our Classes
The final thing that we are going to work with when it comes to our classes is
how to access these. C# is going to allow us to have some support from four
different modifiers when it comes to who is able to access each of the classes
that we have. these are going to include protected, private, internal, and
public. These modifiers are going to make it easier to control who is able to
see each of the elements that are found in that class you are working with.
The best way to make sure that each of these is going to work will include:
As you can see, each of these elements is going to work in a slightly different
way based on what you would like to have happened in regards to the privacy
of our classes. If you would like to make sure that the class remains private
and that nothing else is allowed to get ahold of it or use the information, then
you will want to work with the private setting. However, if you need other
classes to have the ability to work with this particular class, then it is just fine
to change it to the public modifier.
As we go through some of the programs, you should think about which of
these modifiers is going to be the best one for some of the coding that you
work with. If you do not add in one of these modifiers before the data that is
needed for the class, then it is, by default, the private class. This is not
necessarily a bad thing for your code, but if you want one of the other
options, then you need to go through and make that change or the program
will not offer it.
Remember though this process that these classes are really going to be
important when it is time to write out some of the codes that you have. They
are going to help ensure that these containers are going to be organized, and it
will make sure that you are easily able to pull up the things that are needed
inside of your code. This is going to ensure that things are easier to work
with. Your code will work so much better and writing out codes in C# and
other OOP languages will be easier as well.
When you are choosing which of the objects you would like to add to one of
the classes that you are writing, you need to remember that these objects can
fit into the same class, only if they really make sense to go with one another.
You should be able to get anyone to look inside of the class, and agree that it
does make sense to get these objects to be together in the same class. Of
course, remember that the objects do not need to be identical all of the time.
But they need to make sense of being together.
For example, if you are working with that Toys class that we had before, you
would not have to just put one toy in there, or one type of toy inside. You
could add in all of the toys that you would like inside and this would still
follow the rules that you need. You could also have a class for things that are
all of the same color, one for the animals, and one for different types of
vehicles. As long as the objects go together and match up with one another,
then you will be just fine.
The objects and classes are going to be an important part when you are
working with some of the coding that you want to accomplish in the C#
language. It is important for us to take a look at some of the work that we
want to do with this kind of language, but we need to make sure that we are
writing them up in the right manner, and that we are adding in the right
objects.
Chapter 4 Creating Loops in C#
In many of the OOP languages that you will want to work on, you will find
that it is possible to create something that is known as a loop. This is a really
nice thing to work with because it allows you to fit a lot of code into just a
few lines, saving you time and hassle in the process. And in this chapter, we
are going to take a closer look at what these loops are all about, how you can
create them, and even some of the different types of loops that are available
for you to work with.
When we talk about looping when we are coding, it is going to be a method
that we can use to execute a statement, and sometimes a set of statements,
many times depending on the results of the condition that we want to have
evaluated in order to execute those statements in the first place. Sometimes
the loop is only going to happen a few times, and sometimes it will go
through the iteration many times, depending on what you are hoping to get
out of the code and how many times you really need it to go through all of
this. The result condition should be something that is seen as true to help
execute the statements inside of the loops.
For the most part, you will find that the loops that you are working with are
going to be divided up into two categories. The first kind is going to be the
entry-controlled loops. The loops where you will have the condition tested at
the beginning of the loop will be known as the entry-controlled loops. These
are going to include the for loop and the while loop.
To see this work, you will need to make whatever condition you are testing to
show up at the beginning of the code. The compiler is going to check the
condition in the syntax first, and if it is true, then it will run the loop. This
works well with most of the loops that you are going to work with, but
sometimes it does mean that your loop is not going to run at all because the
conditions are never met.
Let’s take a look at some of the loops that are going to fit into this. The first
type is the while loop. The test condition that is there is going to be seen as
the beginning of the loop, and then all of the statements we work with will be
executed until the given condition, which is Boolean in these loops, is
satisfied. When the condition is considered false with this one, then the
control will be out from the while loop and the loop is going to stop
completely. Instead, it will move on to the next part of the code and move on
from there.
Working with this kind of coding and loop is not that hard to work with. We
are going to take a look at an example of how we are able to handle this in a
moment. Take a look at the syntax and experiment a little bit with it to see
how it is going to work. You can also look for the while part of the code,
which is going to tell us where the loop we are working with is going to start.
An example of how we are able to work with the while loop will be below:
// C# program to illustrate while loop
using System;
class whileLoopDemo
{
public static void Main()
{
int x = 1;
One thing to note before we go through the process of looking at some of the
coding that we want to do with this is that the initialization part is only going
to be evaluated just one time before the for loop starts. If you set this up in
the manner that you would really like to see, then this is going to be plenty.
With this in mind, let’s take some of the information that we talked about
above and add in the coding to see how this kind of loop is going to work:
class forLoopDemo
{
public static void Main()
{
// for loop begins when x=1
// and runs till x <=4
for (int x = 1; x <= 4; x++)
Console.WriteLine("GeeksforGeeks");
}
}
Now that we just talked about some of the entry-controlled loops in C#, it is
time for us to move on to the second type of loops that we are able to use in
our codes. And these are going to be known as the exit-controlled loops. The
loops in which the testing condition is going to be present at the end of the
body of our loop are going to be known as the exit-controlled loops. The best
known of these kinds of loops is going to be the exit-controlled loop.
One thing that we need to note when we are working on these is that the exit-
controlled loops will have the body of the loop evaluated for at a minimum
one time as the testing condition is present at the end of the body of our loop.
With that in mind, we can take a look at how to work with the do-while loop
that we want to focus on here.
The do-while loop is a great one to work with, but you may notice that it has
a lot of similarities to what we are going to see with the while loop. The main
difference that we are going to see between the do while and the while loop is
that the do while is going to check the condition after it goes through and
executes the statements. What this means is that it is going to execute the
body of the loop just one time for sure because it will run the loop, and then
go through and check the condition and see if it has been met yet or not,
rather than doing it in the beginning.
Now we need to take a moment to look at some of the syntaxes of what we
are going to see when it comes to working with the do while loop. These are
nice to work with and can provide us with a lot of great codes, but take a look
at the example below and notice where they do and the while part shows up,
and what kind of information is showing up in between them.
// C# program to illustrate do-while loop
using System;
class dowhileloopDemo
{
public static void Main()
{
int x = 21;
do
{
// The line will be printed even
// If the condition is false
Console.WriteLine("GeeksforGeeks");
x++;
}
while (x < 20);
}
}
Another option that we need to spend some time on here is known as the
infinite loops. These are going to be the types of loops where we will find
that the test condition is not going to evaluate anything as false ever. This
means that they are going to get stuck in the loop and will continue to execute
the statement that you have put into place forever, or until you get an external
force to work on it and make sure that it stops.
This can often happen when you do not go through and actually put in some
of the conditions that your codes need in the first place. You need to make
sure that you are going through and adding in the right conditions right away
and keeping it all in the right place to ensure that you are not going to fall
into the trap of one of these loops and then having to fix your program before
it gets stuck there forever.
To see what this kind of loop is going to look like in case you do make a
mistake and forget the condition that should be there, take a look at the code
that is below and see if you are able to find where the issue is inside of it:
class infiniteLoop
{
public static void Main()
{
// The statement will be printed
// infinite times
for(;;)
Console.WriteLine("This is printed infinite times");
}
}
There are some times in the codes that you want to work with that you will
need to combine two loops together in the same part of the code. You want to
make sure that they are able to combine with one another and both run until
both of them are complete. This is going to be important to some of the codes
that you want to write, such as creating one of your own multiplication tables
along the way. A good example of these nested loops, where you have one
loop present inside of another loop, includes:
// C# program to demonstrate nested loops
using System;
class nestedLoops
{
public static void Main()
{
// loop within loop printing GeeksforGeeks
for(int i = 2; i < 3; i++)
for(int j = 1; j < i; j++)
Console.WriteLine("GeeksforGeeks");
}
}
And finally, the last type of loop that we are going to take a look at in this
chapter is going to be known as the continue statement. This kind of
statement is useful because we can work with it to skip over the execution
part of the loop on a certain condition and then move the flow so that it is
then on the next part for updating when we need it. This one may seem a little
bit confusing when we are first getting started, so a good way to take a look
at this is to look at some of the coding that we need to put it together below:
// C# program to demonstrate continue statement
using System;
class demoContinue
{
public static void Main()
{
// GeeksforGeeks is printed only 2 times
// because of continue statement
for(int i = 1; i < 3; i++)
{
if(i == 2)
continue;
Console.WriteLine("GeeksforGeeks");
}
}
There are a lot of different types of loops when you are working with the C#,
and this is a good thing because there are many situations where you would
want to bring up some of these loops in your codes, and each situation will
need a different kind of loop. The good news is that when you use these in
the proper manner, you will be able to write out some of the best codes that
you need, without having to rewrite a bunch of lines of code at the same time.
Spend some time looking at these different loops and what they can offer to
you, and try a few out to see how they are going to work for your own codes
as well.
Chapter 5 Value types and Reference types
Types in C# can be split into either value types or reference types. The
differences between the types in each category stem from differences in
copying strategies, which in turn result in each type being stored differently
in memory.
Value types
Value types encompass most built-in types (In specific terms, all numeric
types, char type, and bool type) as well as custom struct and enum type.
These types all have a fixed size, variables of value types directly contain
their own values.
Reference types
Reference types comprise all classes, array, delegate and interface types and
are handled differently by the compiler. For example, take the Circle Class
type (previous code listing). Once you declare a Circle variable, the compiler
allocates a small portion of memory which can possibly hold the address of
(or a reference to) additional block of memory holding a Circle. Only once
an actual Circle object is created (via the new keyword) then the memory is
allocated.
Copying value & reference types
When you take a copy of a value type there are two memory locations. For
example, should you create a integer variable called i and give it the value 42
then an additional integer variable named copyi and assign i to copyi, copyi
will hold the identical value as i (42). Although copyi and i hold the exact
same value, there are actually two blocks of memory holding the value 42:
one block for i and another block for copyi. If you adjust the value of i, the
value of copyi doesn’t change:
int i = 42; // declare i as integer & assign it 42
int copyi = i; /* decclare copyi equal to i (i.e copyi now holds a
copyi of i – its value 42) */
i++;/* incrementing i by 1. copyi is unchanged;
I now holds 43, but copyi still has 42 value*/
This is in marked difference to declaring a variable as a class type where you
are essentially copying the same address. E.g. if you declare c as a Circle, c
can refer to a Circle object; the actual value held by c is the address of a
Circle object in memory. Should you declare a further variable called refc (a
Circle) and assign c to refc, refc will have a copy of the identical address as
c. To summarize, both refc and c now denote the one Circle object.
Circle c = new Circle(42); // declare new c variable of Cirlce object
that = 42
Circle refc = c;// assign c to refc. refc has identical address as c
Note that the behaviour of method parameters hinge on on whether they are
value types or reference types.
Null values
The null value identified with the null keyword, indicates that the variable
does not refer to any valid object, i.e. it stipulates that a variable is set to
nothing. You can assign reference types, pointer types and nullable types the
value null. Code that sets a variable to null explicitly assigns the reference to
refer to no valid value. It is possible to check whether a reference refers to
nothing. The subsequent code demonstrates assigning null to a string
variable:
static void Main()
{
String phoneNum;
// …
// Clear the value of phoneNum.
phoneNum = null;
//..
}
Assigning the value null to a reference type is not the same as not assigning it
at all. In other words, a variable that has been assigned null has still been set,
whereas a variable with no assignment has not been set and therefore, will
often result in your program not compiling if used prior to assignment.
Assigning a string value the value null is particularly dissimilar from
assigning an empty string, “”. Use of null indicates that the variable has no
value, whereas “” indicates that there is an empty value – an empty string.
This difference is quite valuable in programming, you could take a phone
number of null to mean that the phone number is unknown, while a
phoneNum value of “” could stipulate no phone exists.
Nullable types
Value types can’t typically be assigned null since by definition they can’t
hold references, which includes references to nothing. However, C# defines
a modifier that you can use to declare that a variable is a nullable value type.
A nullable value type acts in a similar way to the original value type, but you
can assign the null value to it. You use the (?) to specify that a value type is
nullable, like so:
int? i = null; // valid code
You can ascertain whether a nullable variable contains null by testing it in the
same way as a reference type:
if (i == null)
The System.Object class
One of the most important reference types in the .NET Framework is the
Object class in the System namespace. To completely appreciate the
significance of the System.Object class you need understand inheritance -
described later in this Ebook. For the time being, simply accept that all
classes are specialized types of System.Object and that you can use
System.Object to create a variable that can refer to any reference type.
System.Object is such an important class that C# provides the object
keyword as an alias for System.Object.
In the subsequent example, the variables c and o both reference the same
Circle object. The fact that the type of c is Circle and the type of o is object
(the alias for System.Object) in effect offers two different views of the same
item in memory.
Circle c;
c = new Circle(42);
object o;
o = c;
Boxing
As discussed, variables of type object can refer to any item of any reference
type. However, variables of type object can also refer to a value type. To
illustrate, both the two following statements initialize the variable i (of type
int, a value type) to 42 and then initialize the variable o (of type object, a
reference type) to i:
int i = 42;
object o = i;
In the second there is a bit more happening. Remember that i is a value type
and that it lives on the stack. Should the reference inside o referred directly to
i, then the reference would refer to the stack. Nevertheless, all references
must refer to objects on the heap; creating references to items on the stack
could seriously compromise the robustness of the runtime and create a
potential security flaw, so it is not allowed. Therefore, the runtime allocates a
piece of memory from the heap, copies the value of integer i to this piece of
memory, and then refers the object o to this copy. Boxing is term for
automatically copying an item from the stack to the heap.
Unboxing
Because a variable of type object can refer to a boxed copy of a value, it’s
only reasonable to allow you to get at that boxed value through the variable.
You may be thinking that could can access the boxed int value that a variable
o refers to via a simple assignment statement like:
int i = o;
This however will result in a compile error. You can’t use the int i = o code.
The variable o could be referencing absolutely almost anything - not just an
integer. Take for example the subsequent code if such a statement were
allowable:
Circle c = new Circle();
int i = 42;
object o;
o = c; // o refers to a circle
i = o; // what is stored in i?
To get the value of the boxed copy, you must utilise what is known as a cast.
This operation checks if it’s safe to convert an item of one type to another
before it actually making the copy. You prefix the object variable with the
name of the type in parentheses, as follows:
int i = 42;
object o = i; // boxing ok
i = (int)o; // this compiles ok
The effect of this cast is subtle. The compiler sees that you’ve specified the
type int in the cast. It generates code to check what o actually refers to at run
time. It could be really anything. Even though your cast says o refers to an
int, it doesn’t mean that it actually does. If o does actually refer to a boxed int
and everything correlates, the cast will succeed and the compiler will extract
the value from the boxed int and copy it to i. (i.e. the boxed value will be
stored in i.) This is called unboxing
However, if o does not refer to a boxed int, there has been a type mismatch
and the cast will fail. InvalidCastException is invoked. The following
illustrates an unboxing cast that fails:
Circle c = new Circle(42);
object o = c; // fails to box since Circle is a reference variable
int i = (int)o; // compiles ok but throws an exception @ run time
Note that boxing and unboxing are expensive operations because of the
quantity of checking that is required and the need to allocate additional heap
memory. Boxing is useful but overuse will really negatively impact the
performance of your program.
Casting data safely
By utilising a cast, you can in your opinion specify that the data referenced
by an object has a specific type and it is safe to reference the object by using
that type. It is important to note that it is of your opinion. The C# compiler
will not check that this is the case, but the runtime will. If the type of object
in memory doesnt match the cast, the runtime will throw an
InvalidCastException. You should expect this exception and and deal with it
appropriately should it occur.
In saying that, catching an exception and attempting to recover in the event
that the type of an object is rather an unwieldly approach. C# offers two
really useful operators that can help you perform casting in a much more
elegant manner: is and as operators.
The is operator
You can utilise the is operator to authenticate that the type of an object is
what you assume it to be, like so:
WrappedInteger wi = new WrappedInteger();
...
object o = wi;
if (o is WrappedInteger)
{
WrappedInteger temp = (WrappedInteger)o;
// This is safe;
o is a WrappedInteger
...
}
The is operator accepts two operands: the left - a reference to an object, the
right – a type. Should the type of the object, referred to on the heap, has the
specified type, it evaluates to true; or else, it evaluates to false. The prior code
tries to cast the reference to the object variable o only if it knows that the cast
will be successful.
The as operator
The as operator achieves a similar role to is but in a slightly condensed
method. You utilise the as operator like so:
WrappedInteger wi = new WrappedInteger();
...
object o = wi;
WrappedInteger temp = o as WrappedInteger;
if (temp != null)
{...
// Cast was a success !
}
The as operator is similar to the is operator in that it takes an object and a
type as its operands. The runtime attempts to cast the object to the specified
type. If the cast is a success, the result is returned and is assigned to the
WrappedInteger variable. Should the cast fail, then the as operator appraises
to the null value and instead assigns that to temp.
Chapter 6 Enumerations
An enum is a value type that the developer can declare. The key
characteristic of an enum is that it declares at compile time a set of possible
constant values that can be referred to by name. The subsequent is an
example of an enum:
enum Season { Spring, Summer, Autumn, Winter }
Once you have declared an enum, you can use it in the exact same way as any
other type. That is, if the name of your enum is Season then you can create
variables, fields and parameters of type Season as demonstrated here:
enum Season { Spring, Summer, Autumn, Winter }
class Example
{
public void Method(Season parameter) // method parameter
{
Season localVariable; // local variable
...
}
private Season currentSeason; // private field
}
In order to read an enumeration, you must assign a value to it. You can assign
a value that is defined by the enumeration only to an enumeration variable, as
is illustrated here:
Season colourful = Season. Autumn;
Console.WriteLine(colourful); // writes out ‘Autumn'
You can then assign the null value, as well the values defined by the
enumeration, to the variable:
Season? colourful = null;
Structures
Classes specify reference types that are solely created on the heap. However,
on some occasions the class may have so little data that the overhead of
managing the heap turns out to be disproportionate. In such cases, it is best to
define the type as a structure which is a value type. Since structs are stored on
the stack, as long as the structure is reasonably small, the memory
management overhead is often reduced.
A structure is similar to a class in that it can have its own fields, methods, and
constructors.
Declaring a structure is similar to that of a class. You utilize the keyword
struct then use the name of the type, then followed by the body of the
structure, between opening and closing braces.
Here for example is a structure named Time that contains three public int
fields named hours, minutes, and seconds:
struct Time
{
public int hours, minutes, seconds;
}
As per classes, it is not recommended to make the fields of a structure public
in most cases; as there is no way to control the values held in public fields.
Anyone could for example, set the value of minutes or seconds to a value
greater than 60. A better idea is to make the fields private and provide your
structure with constructors and methods to initialize and manipulate these
fields, as shown in this example:
struct Time
{
private int hours, minutes, seconds;
...
public Time(int hh, int mm, int ss)
{
this.hours = hh % 24;
this.minutes = mm % 60;
this.seconds = ss % 60;
}
public int Hours()
{
return this.hours;
}
When you copy a value type variable, you get two copies of the value. With
reference types however, once you copy a variable of reference type, you get
two references to the said object. In summary, use structures for small data
values for which it’s just as or nearly as efficient to copy the value as it
would be to copy an address. Utilise classes for larger more complex data
where copying is too inefficient.
Differences between structures and classes
Syntactically a structure and a class are somewhat alike, although there are a
few significant differences. Firstly, its impossible to declare a default
constructor (i.e. a constructor with zero parameters) for a structure. In the
next example the code would compile if Time were a class, but since Time is
a structure, it doesn’t:
struct Time
{
public Time() { . . . } / Results in compile time error
…
}
Secondly in a class, you can initialize instance fields at their point of
declaration. In a structure, you cannot. In this next example, the code would
compile if Time were a class, but because Time is a structure, it triggers a
compile-time error:
struct Time
{
private int hours = 0; // Results in compile time error
private int minutes;
private int seconds;
...
}
The main differences between a structure and a class as summarized here:
QuestionStructureClass
What type is it?Value type.Reference type.
Are instances on the Structure instancesClass instances known as
stack or the heap?known as values & liveobjects & live on the heap.
on the stack.
Can you declareNo.Yes.
a default constructor?
If you declare your own
constructor, will the compiler
still generate the default
constructor?Yes.No.
Will the compiler
automatically initialize a
field for you in the
constructor if you don’t?No.Yes.
Can you initialize instance
fields at their point of
declaration?No.Yes.
Chapter 7 Decision-making
There are many situations when you require a block of statements to be
executed only if a particular condition is satisfied or conversely, if the
condition concerned is not satisfied. The implementation of such
programming scenarios require decision-making constructs. C# supports
many decision-making constructs; most of which are variations of the classic
if…else construct. All these decision-making elements of the C#
programming language are described in this chapter.
If Statement
The if statement is the most basic decision-making construct that tests the
condition, which appears in the if statement. If the condition is found true, the
block of statements that follow the if statement is executed. On the other
hand, if the condition is false, the if block is simply ignored by the system
and execution begins from the first statement that lies outside the if block.
Sample implementation for the if statement is given below.
using System;
namespace ConditionalStatements{
class DemoIf{
public static void Main(string[] args)
{
int num = 5;
if (num < 5)
{
Console.WriteLine("Inside If Block”);
}
Console.WriteLine("If Executed.");
}
}
}
The output for this code is shown in the image given below.
If Else Statement
The if else is a modified version of the standard if construct that tests the
condition, which appears in the if statement. If the condition is found true, the
block of statements that follow the if statement is executed. On the other
hand, if the condition is found false, the block of statements that follow the
else statement is executed. Sample implementation for the if else statement is
given below.
using System;
namespace ConditionalStatements{
class DemoIf{
public static void Main(string[] args)
{
int num = 5;
if (num < 5)
{
Console.WriteLine("Inside If Block”);
}
else
{
Console.WriteLine("Inside Else Block”);
}
Console.WriteLine("If Else Executed.");
}
}
}
The output for this code is shown in the image given below.
Nested If Statements
There may be situations where you may be required to test many conditions;
each of which being a sub-part of the main condition. In other words, if you
have a programming scenario that needs to perform a block of statements if
the vehicle is an Audi car. So, firstly, you will need to put a condition that
tests if the vehicle is a car. If this condition is found true, the system must
check for a condition that tests if the car is an Audi. This requires two if
statements, one inside another, or a nested if statement.
You can have multiple if statements, one inside another to test multiple
conditions. There is no limit of the amount of nesting that can be performed
for if. However, the higher the number of ifs inside one another gets, the time
complexity of the program increases. Sample code for implementing the
nested if is as follows –
using System;
namespace ConditionalStatements{
class DemoIf{
public static void Main(string[] args)
{
int num1 = 5;
int num2 = 2
if (num1 == 5)
{
Console.WriteLine("Inside If Block 1”);
if (num2 == 2)
{
Console.WriteLine("Inside If Block 2”);
}
}
Console.WriteLine("Nested If Executed.");
}
}
}
The output generated upon the execution of this code can be seen in the
image given below.
Switch Statement
In order to mitigate the complexity issues associated with nested if
statements, C# also provides switch statement, which can test one variable for
multiple values and execute corresponding statements for the same. This
construct internall creates a table, which is used for making execution faster.
The syntax for implementing switch statement is as follows.
Switch (variable_to_be_tested) {
Value_1:
Statement;
break;
Value_2:
Statement;
break;
Value_3:
Statement;
break;
default:
Statement;
break;
}
Nested Switch Statements
There may be programming scenarios that may require you to test multiple
variables and this shall require multiple nested switch statements. C# allows
programmers to use nested switch statements and there is no limit on the
amount of nesting that can be performed.
Conditional Operator
To simplify the conditional construct, C# also provides a conditional operator
(?:).
Chapter 8 Arrays
If you wish to store many elements of the same type and don’t want to create
an individual variable for each of them, then the best data format available for
you is an array. The standard definition of array is a collection of elements
that are of the same data type. Moreover, the size of the elements is fixed and
the order of the same is sequential in the way that contiguous memory is
allocated for the storage of the array elements.
One of the best ways to understand arrays is to see it as a collection of
variables of the same type. The name of the array points to the first element
of the array. The index of the first element is 0. Therefore, the first element of
the array is name_of_array[0]. Subsequent elements of the array can be
accessed by mentioning the index of the element by using the syntax,
name_of_array[0].
Declaring Arrays
In order to declare an array, you need to use the syntax given below –
data_type[] name_of_array;
Here, data_type is the data type of the array, name_of_array is the identifier
that will be used for accessing the array and its elements and [] is the rank or
number of elements in the array. An example of array declaration is given
below.
double[] bal;
Initializing Arrays
While the array declaration statement tells the compiler that an array of this
name is to be created, memory for array is actually allocated when the array
is initialized. It is only after array initialization that values can be assigned to
the elements of the array. Array is initialized using the new keyword in the
following manner –
double[] bal = new double[5];
This statement initializes the array named bal of the type double to have 5
elements.
Assigning Values
Like we mentioned, individual elements of the array can be accessed by
mentioning the index of the concerned element, inside square brackets, next
to the array name in the following manner –
bal[0] = 4.5
This statement initilizes the first element of the array bal to the double value
4.5. The above-mentioned method initializes individual elements of the array
to specific values. Initialization and assignment can be combined together in
the following manner –
double[] bal = {4.5, 66.7, 111.6, 34.0, 98.7};
Alternatively, you may also perform this operation in the following manner –
double[] bal = new bal[5] {4.5, 66.7, 111.6, 34.0, 98.7};
double[] bal = new bal[] {4.5, 66.7, 111.6, 34.0, 98.7};
If you wish to copy an array into another array, you can directly use the
statement similar to the one given below.
double[] cp_bal = bal;
This statement creates an array cp_bal that points to the same location as that
of bal. It is important to mention here that C# also performs auto-
initialization of elements depending on the data type of the array. For
instance, if an int array is created, all its values are initialized to 0.
Accessing Elements
Just like array elements are initialized using their index, array elements can
be accessed an re-initialized using the name of the array followed by the
index of the element, which is enclosed within square brackets. An example
of this is given below.
double val = bal[4];
This statement assigns the value of the last element of the array to the
variable val. The sample code given below demonstrates the working of
arrays in C#.
using System;
namespace DemoApp {
class DemoArray {
static void Main(string[] args) {
int [] num = new int[5]; /* num is an int array of 5 elements */
int x,y;
for ( x = 0; x < 5; x++ ) {
num[ x ] = x + 100;
}
/*Print the values of array elements*/
for (y = 0; y < 5; y++ ) {
Console.WriteLine("Element[{0}] = {1}", y, num[y]);
}
Console.ReadKey();
}
}
}
The output generated upon the execution of this code is shown below.
Foreach Loop
C# provides a special looping construct that uses the contiguous nature of
arrays for performing iterations. The loops iterates through the elements of
the array and its syntax is as follows –
foreach (int var_name in array_name)
{
…
}
Here, var_name is the looping variable and array_name is the name of the
array, which needs to be involved for looping. Sample implementation of this
looping construct is given below.
using System;
namespace DemoApp {
class DemoArray {
static void Main(string[] args) {
int [] num = new int[5];
for ( int x = 0; x < 5; x++ ) {
num[x] = x + 100;
}
foreach (int y in num ) {
int x = y-100;
Console.WriteLine("Value of Element[{0}] = {1}", x, y);
}
Console.ReadKey();
}
}
}
The output generated upon the execution of this code is shown below.
Arrays in C#
C# supports multi-dimensional arrays and the simplest form of the same is 2-
dimensional arrays. Two dimensional arrays are defined and accessed using
the format, array_name[][]. Every new dimension adds a square bracket
combination in front of the array name. C# also supports the concepts of
jagged arrays or arrays of arrays. Besides this, arrays can also be passed as
parameters to functions. Lastly, C# has a defined class in the System
namespace for arrays. This is the base class for all arrays, with inbuilt
functions.
Chapter 9 Creating Objects and Making Them
Work
Classes and objects are really important to how C# and other object-oriented
programming languages will work. This is a pretty simple topic that you
won’t have trouble understanding, but this doesn’t mean it’s something you
should ignore, it is actually very important that you should learn about it
because it will help you learn how all of these works. This chapter will take
the time to carefully look at how you can work with objects so that they will
function the way they should in your code.
Classes and objects
The first thing that we will spend our time talking about are the objects which
are used in this programming language. Programming has changed a lot over
the past few years, and this has changed how programmers create their new
computer applications. The newest form of programming, known as ‘OOP’
or object-oriented programming, is the newest idea that most modern coding
languages rely on to get the coding done. There are a lot of components that
go with this, but it basically makes it easier to sort out and use the coding
language.
What is OOP?
As a beginner, you may be curious as to what OOP means and how it’s
relevant to your coding. OOP is a style of coding that relies solely on objects
to get the program to work. OOP will provide you with a model type that is
based on how things would work in the real world and then you would use
this idea and implement it in the codes that you are writing.
In some of the older coding languages, you had to concentrate on abstract
ideas to help you to get the coding done. This may sound like a great idea,
but it does make things more difficult in the long run. With OOP, you have to
work with real objects, rather than these abstract ideas, which makes the
coding so much easier. This is the approach that most modern programming
languages take and it does make it much easier for the beginner to write their
own codes, create their own program, and even solve some of their own
problems they might encounter as they go about their programming.
Objects
In this section, we will spend some time working with objects to learn more
about them. Programmers use digital objects to help represent the physical
objects that they want to place inside of their code. While you are working
with an OOP language, it is important to remember that these objects have
more than a few characteristics that you should remember. These include:
State
These are the characteristics that will define the object. These can be general
or specific.
Behavior
These are the characteristics that will declare all the actions that an object is
capable of.
For us to understand exactly how all of this will work, we need to take a look
at an example. Let's say that we are looking at a ball. The state of this object
or the traits that define its characteristics are things like its color, what the
ball is made out of, and the size. The behavior of that ball would refer to what
that ball is capable of, such as bouncing, rolling, and so on and so forth.
When you are working on an OOP language, you can easily combine the
technique and the information to process them as the same thing. The
programming object will then match up to how it would behave or look when
it is in the real world and then it will also hold onto the actions and the
information until later.
Classes
While we will discuss this a little bit more in a later chapter, it is important to
understand a little bit about what these classes are at this point. Within this
language, the ‘classes’ refer to what defines all the characteristics of the
objects from above. These classes are in charge of giving you a model or a
structure so that you can effectively define the nature of the object. These
classes are often considered the foundation of OOP languages, and they will
be linked closely to the object. Another thing to note is that each of the
objects that you are using can also represent one specific class.
Let's take a look at how this works so that it makes a lot more sense to you.
For example, we have a class that we named ‘Toys’ and while the object will
be ‘Ball.’ In this sample, the ball is one instance of that ‘Toy’ class that you
worked on. However, that the class will also define the state and the behavior
of all the ‘toys’ that you add to the ‘class’ including the ‘ball.’
Classes may sound complicated, and they will make the organization of your
code a lot easier to handle, many people often see them as the basis of just
about any program. The information they hold onto is meaningful for those
who will take a look inside of the class so they can understand exactly what it
is. For example, if you have a class that you named ‘Toys,’ the other users
can access or look into the class and see that all the items or objects that were
placed inside the code actually belong there. They do not have to be exactly
the same, but putting them together in the same class should make sense.
The classes function to define the behavior of an object, such as the kinds of
actions you want that object to be capable of performing. The object will also
have its own characteristics or attributes. You will see that the attributes
appear as different variables in the body of the class while the behavior, on
the other hand, is defined by the different methods that fall inside the class.
Let's take a look at how this works by examining the Toy class that we talked
about before. When these are applied, you will get the size and the color as
the attributes. To make this work, you will need to bring out and use the
move() and the stop() methods.
How to use these classes in your code
We have already spent a little bit of time talking about classes and how you
can get them to work inside of your code, but now we need to spend some
more time looking at how they work within the program as a whole and how
they are useful at changing what you can write out inside of the code. When
you are working with the C# programming language, you need to define all
of the classes with the help of the ‘class’ keyword to not only make sure that
everything works but to also help make things clear and simple.
After you have started with the code and you typed in the word ‘class,’ this is
when you should indicate the identifier that you would like to see with the
variable and the methods that would help make it certain that all of this
works. As for making sure that all of this would stay simple, there are
specific parts that you need to use since you are working with this kind of
code. The different parts that you need to add to the class when working in
C# include:
Fields
These are any of the variables that belong to a particular data type.
Methods
Properties
In this programming language, the properties are what will enhance how well
the fields work. The property will provide some extra management abilities
for the information and give it to the fields.
At this point, it will probably be easier if you take a look at how you can
work with making classes and how to make sure that they do exactly what
you would like. We will now have a look at an example of how this code will
work and the different theories that have been going on with it. In this
example, we will use ‘book’ as the name of the class and then it will have the
properties of ‘size’ and ‘type.’ The example of this code is as follows:
Public class Book
{
Private string bookType:
Private string size;
Public string BookType
{
Get
{
Return this. bookType;
}
Set
{
This.bookTyupe = value’
}
}
Public string Size
{
Get
{
Return this size;
}
Set
{
this.size = value;
}
}
public Book()
{
this.bookType = “Dictionary”;
this.size = “large”;
}
public book(string bookType, string size)
{
this.bookType = bookType;
this.size = size;
}
public void Sample()
{
Console.WriteLine(“ Is this a {0}, bookType):
Now, at first, this will look like a really complicated code to work with and
you may be worried about how you will keep all of this in order or if you can
understand how to use it at all. It is really not that complicated at all to work
with though and you can use the ideas that are inside.
With this example, the ‘Book’ class will define two different properties, the
book type, and the size. These properties will hide the values inside the fields
of the same names while the code snippet will declare two constructors that
will be generated on the Book class. This code will also create a method
called Sample().
You can use this code for a number of different things, like adding in more
characteristics if you would like, and it doesn’t have to be limited to books,
toys, vehicles, or anything else. You can mess around with your text editor as
much as you want to try out this formula and change it around with some
other classes to make it easier to get the program to work for you.
How to create your own objects
Once you have a class in place to help you out, it is time to work on creating
some of the objects that you would like to use and place inside a class.
Creating your own object is not meant to be difficult to work with so in this
part of the book, we will take the time to have a look at the basics that you
need to know to get started.
Creating the object
The first thing that we have to do here is to create the object that you want to
place inside an existing class. To get this to happen, you need to make your
own keywords. Usually, a programmer will choose to assign the new object a
variable so that it will stay as the same data type as the class that you want to
use. Remember that doing this won’t copy the object over to the right
variable, but it will help give the variable a reference to the object that it is
now assigned to. To make sure that this actually works, use the following
code to do so:
Book someBook = new Book()
This is a good example that you can use because it will take the instance of
the book and assign it over to the variable that we named ‘someBook.’ This
will ensure that the proper object will the right class as is needed.
System classes
If you are new to working with the C# language, you will find that this
language already has a library that is built right in. This library includes a lot
of classes that are kind of default such as string, math, and console. As you
start to use this language more, you must remember that the library is
something that you can easily use and access with the ‘.Net’ applications.
You are definitely going to love how the .NET framework will do the job for
you. This is because the library that you need for C# was installed ahead of
time. These classes are the parts that you can use all of the time, and they are
helpful as you start to learn some of the basics that come with this language,
such as networking, text procession, and execution. These classes are also
helpful to a beginner who has never worked in programming before because
they are prewritten and recognized by the program so you will not have to do
as much work.
One thing that you should remember when you are working with these
classes is that they will hide all the logical implementations. You need to
focus more on what your classes can do, rather than worrying so much about
the mechanics behind how they exactly do this. Because of this, the built-in
classes with C# are not something that the programmer can actually view.
You simply need to use these codes for their general purposes rather than
worrying so much about how they really work because that’s something you
don’t really have to think about.
How to assign a parameter to the object
This programming language will allow you to assign some parameters to the
object that you created. This is something that’s pretty easy to work with, and
you just need to have the basic syntax in place to make sure that this will
work for you. The syntax that you need to use is this:
Book someBook = new Book(“Biography”, “large”)’;
This code will create a new object named ‘someBook’ and will assign the
two different parameters to it as well. With this adjustment, the object’s
‘type’ is now Biography while the size is now large.
Whenever you use the new keyword, the framework of .NET can complete
two things:
This is a process that will occur because of the constructor method. For the
code that we wrote above, the parameters that we set out right away are the
parameters for a ‘class constructor.’ This is what will make sure that the
object will stay inside the class that you chose to create and it will provide
that object with the right characteristics so that it works properly.
Releasing your objects
One thing that you need to concentrate on is learning how to release the
object that you are working with. Some other languages that you will work
with will make you go through and manually release the objects, but this is
not something that is required when it comes to working with C#. This means
that you can release any of the objects that are consuming up too much
memory in your system without having to go through and manually destroy
them. You can just use the CLR system that can be found inside the .NET
framework to make all of this work.
When you are working with the CLR system, the computer can automatically
detect and then release the objects that were not referenced. The memory that
was reserved for these objects is now available again, and you can use them
for some of the other objects or variables that you will create inside of your
code. If you would like to release an object, you should stop and learn how to
destroy the corresponding references as well. An example of how you would
go through and do this is the following:
someBook = null
This process doesn’t mean it’s going to delete the object, but it will make
sure that all references to that object are removed so that the CLR can go
through after you are done with it and perform the deletion for you. This is a
great process to have because it will help to limit the number of issues that
occur in your code and can get rid of some of the bugs that might show up in
the code.
The constructors
The last topic that we will discuss in this chapter is the ‘constructors.’ These
constructors are basically methods that will run when the program creates a
new object. The idea behind using these is so that you can use it to initialize
the data of that new object. You won’t get anything of value to show up when
you go with this method. In addition, this constructor will use the same name
as the class that it comes from, this means you don’t have to try and match up
a few random names along the way. You also get the choice of assigning the
right parameters to this when you work with constructors in C#.
The constructors that come with C# can accept parameters just like any
method that you are using in this programming language. You can set up
several constructors in the class, but you always need to check to see if the
constructors are from different types and numbers of parameters. This will
help to make sure that each parameter is unique.
As you are working with constructors, it is important to remember that these
will run any time that you create a brand new object in your class. If you are
working with a class that has a few different constructors inside of it, you
may be curious to figure out which of the constructors are running as a new
object is created in the code. This programming language can pick out the
right constructor based on what you are working on so you won’t be
responsible for coming up with all that information. The compiler will take
over so things will stay organized without you being stressed out so much
about it.
Now that we have talked about the constructor a little bit, let’s take a look at
an example of how this would work in C#:
public class Device
{
private string type;
private string size;
// A constructor without any parameter
public Device()
{
this.type =”laptop”;
this.type = “large”;
}
//A constructor with two parameters.
{
this.type = type;
this.size = size;
}
}
The parameters that we just set up can help tell the program what are the
tasks or functions that need to be fulfilled. It is also responsible for helping
the C# compiler to figure out the constructor that you would like the program
to use.
How to Define Classes with the Help of C#
Classes are so important when it comes to working with any programming
language because they perform a variety of helpful functions, and this is true
in C# as well. So, let’s take some time to look at how to define classes inside
the C# language.
The basics of working with classes
When you are working with a programming language, the class is the part
that will define the object types and the data types that you can use at that
point in the program. The object is what will contain the information that
defines the class or the container that it is held in. These classes can hold a
ton of information, and they can be used to describe the behavior of the
object as well. These are all the behaviors that the object is capable of doing.
When working with OOP languages, you want to use methods that will help
describe the behavior of the objects.
Components of classes
When you are working with a class, some different components will come
into play to help you get these classes taken care of. There are a few different
parts that come with each class including:
Declaration
This is the line that will declare the identifier of the class.
Body
Just like with methods, the classes to have a single body. You need to define
the body right after you make the declaration. The body is the statement, or
several statements, that are found between the curly brackets. An example of
this is:
class Example
{
//This is the body of the “Example” class.
}
Constructor
This is the part that will allow you to create a new object. An example of this
is:
Public Sample()
{
//Insert what you want to say here.
}
Fields
These are the variables that you will declare within your class. The fields
contain the values that will represent the exact state of the object they are
trying to get to.
Properties
This part will describe the different attributes of the class. Many
programmers will write the class properties right inside the field of their
chosen object.
Methods
Private
The function of this modifier is that will place some strict restrictions on one
of your classes. If the class is tagged as a private class, it will not be
accessible by the other classes in the code. The C# language will use this as
the default modifier if you do not place anything else there. This can help to
avoid problems in the future in case you forget to add on that modifier.
Public
You can also choose to make the class public. This means that the modifier
will tell the other classes that they have access to this class. This modifier can
take away all the limitations about how visible this class is to all the other
classes.
Internal
If your code has the ‘internal’ modifier on it, this means that this class will be
accessible, but only to the files that fall in the same project.
Protected
This is the modifier that you want to use if you would like to prevent a user
from accessing the element. However, it also allows all the descendant
classes to have access to the elements of that class if they need it.
As you can see, each of these elements all works in a slightly different way
compared to one another based on how much you want your classes to be
private in terms of permitted access. If you would like to make sure that the
class remains private and that nothing or no one else is allowed to get ahold
of it or use the information, then you working in the private setting is
obviously the best for you. However, if you need other classes to have the
ability to work with this particular class, then it is just fine to change it to the
public modifier.
As you go through your program, think about which of these modifiers will
work out the best for your code. If you do not place any of these modifiers
before your class, then it will default as a private class, which is not that bad
of a thing. But if you feel that one of the other options is the best for making
your code, then you must make sure that it is written in with the class to
avoid issues later.
A final word about classes
The importance of these classes cannot be emphasized enough when it comes
to writing out your code. They help you to keep things neat and organized
and will also make sure that you can easily pull up the things that you need
from the code. This can make things so much simpler to work with. Your
code will work better, and you will find that writing your own codes isn’t
even really that difficult.
When it comes to picking out the objects that go with the class that you are
writing, you must remember that these objects need to make sense if you put
them together. You should have someone else, like a friend or a co-worker
who’s familiar with programming, look at the class and agree that it makes
sense that those objects ended up together. This does not mean that the
objects need to be identical, but they need to at least be related in some way.
For example, if you have a class that is called ‘Toys,’ you don’t just place the
same toy inside and leave it as it is. You could include all sorts of ‘toys’ or
other objects inside, but some rules have to be followed. This can work with
any kind of class that you would like to work with. You could have a class of
things that are colored blue, one for animals, and one for types of vehicles.
As long as the objects that go inside match up a little bit, that means you’re
doing everything right.
It is important to spend some time learning about objects because they are so
important to ensure that your code works the way that you would like. They
provide the tools to organize your code and make sure it works amazingly
well. Try out a few of the different codes that are in this guidebook, and you
will quickly see how well these work once you try making your own code.
Conclusion
This really is just the beginning of your C# journey. There is so much more
to learn and so much further you can go; this is only the tip of the iceberg.
You’ve learned the syntax and the language conventions; you’ve learned
what goes into a program and how to make things more complex. The most
important part of any computer programming language is the logical aspect.
Yes, you may have learned how to loop through an array like you would look
through a list of grocery items. But, if someone asked you to take an image
and process it, would you know how to do it? Would you know how to scale
it? Rotate it? Flip it? By using an API and your brain, you could figure it out.
Real programming requires you to use the logical part of your brain. It’s
much like learning a foreign language. Learning the language conventions
and the grammar rules is one thing, but the real skill comes from writing the
language in a clean and structured way and in a well-thought-out and logical
manner. As a programmer, the skill comes from being able to put your
knowledge and logic into practice by writing clean code that makes sense,
and most importantly, that works.
Learning a program and truly understanding it is great – it really is the nearest
we have to having magic power. You can make something from nothing,
build it from the ground up, and have it do exactly what you want it to do.
In this series of guides, you learned C# basics, and while I couldn’t possibly
teach you everything you need to know, I have at least set you off on a
journey of discovery. I hope that you now feel you can take the next step, and
that you are prepared to dive deeper into C# and learn it until you are
proficient at using it.
Thank you for taking the time to read my guide and I want to take this
opportunity to wish you luck on your C# programming journey.
Conclusion
This marks the end of this guide. C# is a compiled programming language
developed by Microsoft. C# is also an object-oriented programming
language, meaning that it supports concepts like the use of classes, objects,
inheritance, encapsulation, polymorphism etc. To program in C#, you need
the .Net framework. This framework was also developed by Microsoft. You
also need an integrated development environment (IDE). Visual studio is the
common IDE used for programming in C#. You can get its free edition
online. The .Net framework can only run on the Windows operating system.
This means that if you are using Linux or Mac OS, you have to look for an
alternative so as to be able to program in C#. You can use Mono, an open
source framework that acts as an alternative to the .Net framework. It can be
used on both Linux and Mac OS.
C# is an easy programming language, making it good even to the beginners
in programming. One only needs to setup the environment and start writing
and running their C# code. You can use C# alone to develop a complete
computer application.
If you enjoyed getting started with C#, there is so much more to learn and do
with this wonderful language. Be sure to continue your journey with the
second book in the series, which looks at slightly more complex topics while
still being beginner friendly.
C# is a valuable programming language with a large array of uses. It is
practical, efficient, and extremely easy to use. It will be a great asset and
reference point for your future in programming. If you can think it, you can
create it. Don’t be afraid to try something new.
Good luck and happy programming!
Arduino Programming
Steve Tudor
Text Copyright ©
All rights reserved. No part of this guide may be reproduced in any form
without permission in writing from the publisher except in the case of brief
quotations embodied in critical articles or reviews.
Legal & Disclaimer
The information contained in this book and its contents is not designed to
replace or take the place of any form of medical or professional advice; and is
not meant to replace the need for independent medical, financial, legal or
other professional advice or services, as may be required. The content and
information in this book has been provided for educational and entertainment
purposes only.
The content and information contained in this book has been compiled from
sources deemed reliable, and it is accurate to the best of the Author's
knowledge, information and belief. However, the Author cannot guarantee its
accuracy and validity and cannot be held liable for any errors and/or
omissions. Further, changes are periodically made to this book as and when
needed. Where appropriate and/or necessary, you must consult a professional
(including but not limited to your doctor, attorney, financial advisor or such
other professional advisor) before using any of the suggested remedies,
techniques, or information in this book.
Upon using the contents and information contained in this book, you agree to
hold harmless the Author from and against any damages, costs, and expenses,
including any legal fees potentially resulting from the application of any of
the information provided by this book. This disclaimer applies to any loss,
damages or injury caused by the use and application, whether directly or
indirectly, of any advice or information presented, whether for breach of
contract, tort, negligence, personal injury, criminal intent, or under any other
cause of action.
You agree to accept all risks of using the information presented inside this
book.
You agree that by continuing to read this book, where appropriate and/or
necessary, you shall consult a professional (including but not limited to your
doctor, attorney, or financial advisor or such other advisor as needed) before
using any of the suggested remedies, techniques, or information in this book.
Introduction
In case you’ve never heard of an Arduino before, it is an open-source
electronic interface that has two parts: the first is the programable circuit
board, and the other is a coding program of your choice to run to your
computer. Arduinos come in many forms, including the Arduino Uno,
LilyPad Arduino, Redboard, Arduino Mega, Arduino Leonardo, and others
which we will explain later on.
If you’re unfamiliar with programming, this is a good place to start. The
Arduino can be programmed in various types of programming languages, and
its wide array of Arduino options can give you more programming
experience. Arduinos come with additional attachments, some in the form of
sensors, and others can be obtained anywhere and can be attached to the
various ports on an Arduino. Arduino is a great stepping stone on the way to
understanding programming and sensor interaction.
In programming languages, there is always the well-known program, “Hello
World” that is showcased on the screen. In the microcontroller world that we
are in, this phase or first program is indicated by a blinking of the light, “on”
and “off” to show that everything you have set up works correctly.
We will look at the sketches in their entirety and explain the details after
explaining the code. If you go through something that you cannot make
something out of, keep on reading, and it will be clear.
Let us look at this program, to show you how we will be breaking down the
codes.
Const int PinkL = 13;
Void setup ()
{ pinMode (PinkL, OUTPUT); }
Void loop ()
{digitalWrite(PinkL, HIGH);
delay (600);
digitalWrite(PinkL, LOW);
delay(600); }
On the first part
Const int PinkL = 13;
This line is used to define a constant that is used throughout the program to
specify a particular value. All pins are recommended to have this because it
makes it easy for software change if the circuit is still the same. In
programming in Arduino, the constants are commonly named starting with
the letter "k".
The second to part
Void setup ()
{pinMode (PinkL, OUTPUT);}
The OUTPUT is pin 13. This now makes Arduino control the coding to the
pins, instead of reading from it.
The third part
Void loop()
{digitalWrite (PinkL, HIGH);
delay(600);
digitalWrite(PinkL, LOW);
Delay(600);}
This is where the core part of the code is. A HIGH is written to the pin that
leads to the turning of the LED. When you place HIGH, it means that 5V is
the pin’s output. The other option we have is LOW, which means that you are
putting 0V out.
A delay() is called to delay the number of milliseconds that is sent to it. Since
we send 600, there will be a delay of 0.6 of a second. The LED goes off, and
this is attributed to the LOW that is written as an output on the pin.
A 600 milliseconds delay will be activated.
This will be the sequence until the Arduino goes off or the power is
disconnected from it.
Before you start digesting more content, try this program out and ensure that
it works just fine. To test if you have set your LED in reverse order, the
following might happen. On the UNO board, you have pin 13 connected to a
Light Emitting Diode connected. When it blinks and the breadboard LED
does not blink, then you might have connected your LED in reverse. In case
you see that it is blinking once in a second, then the program has not been
sent to the Arduino successfully.
When you’ve completed the programming, place comments in the coding
lines to instruct the Arduino. These comments can instruct your Arduino to
blink the LED intermittently or through various sequences.
The programs we normally write are usually meant for the computers and not
for people to understand once they are opened up. There is a good provision
that allows us, humans, to read the program easily and the computer will have
no clue about it. There are two comments that are possible in this program:
1. The block comment style starts with two characters, /* which progresses
until */ is seen. Multiple lines are then crossed and here are a few examples.
/* This is the first line*/
/* the program was successful*/
/* we
*are
*going
*far */
2. Commenting can be done on a line that has the backslash operator //. This
is the part that is meant for humans and not machines. It is another way to
insert a comment.
When you add comments in a program, you will have a code that looks like
the statement above.
You will find in the following pages, that if there is no number next to the
line of code, it indicates a comment continuation from the line at the top. We
might not showcase this in perfection because we are using a limited space in
our book. You will find a hyphen at the line’s end that is continued and a
hyphen along the continuation line. This is just our way of handling it, but in
an IDE, you won't find it and you need not type them.
/*
* Program Name: Blink123
*Author: James Aden
* Date written: 24 July 2017
*Description:
* Turns an LED on for a sixth-hundred of a second, then for another sixth-
hundred of a- -second on a continuous repetitive session
*/
/* Pin Definitions */
Const int PinkL = 13;
/*
*Functions Name: setup
*Purpose: Run once after system power up
*/
Void setup(){pinMode(PinkL,OUTPUT);}
/*
Void loop()
{digitalWrite(PinkL,HIGH);Delay(600);digitalWrite(PinkL,LOW);Delay(600):}
Gotchas
If you find out that your program does not compile, or it gives you a different
result than what you need, here are a few things that people get confused
about:
The programming language is normally sensitive to capitalization of letters.
For instance, myVar is considered different to MyVar.
Tabs, blank lines, and white spaces are equivalent to a single space, making it
easier for one to read.
Code blocks are normally grouped using curly braces, i.e., “{“ and “}”
All open parenthesis have a corresponding closing parenthesis, i.e. “(“ and
“)”
Numbers don’t have commas. So instead of writing 1,000, ensure that you
write 1000.
All program statements MUST end with a semicolon. This means that each
statement except for the following two cases:
-In comments
- after curly braces are placed “}”
Assignment task to test what you have learned:
1. Alter the delay time of your LED before it comes back on to
stick to 1.5 seconds. Leave the ON time of the LED limited
to 600 milliseconds.
2. From pin 13, change to pin 2, making it the new connection
to the LED. Keep in mind that both the circuit & and the
program will be different.
This is just a basis for basic Arduino programming. In the rest of the book,
we will be looking at how Arduinos can be programmed with respect to
different functions. If you’re new to programming, don’t let the above codes
frighten you. Coding takes practice, but it relatively easy to learn, just like a
new language.
Chapter 1 Key Terms in Understanding Arduino
hen working with Arduino technologies, it is helpful to understand the
terminology of Arduino. You will need to understand the terminology to
choose a board, write the coded instructions, set up the microcontroller for
use, and finally using the Arduino board. In this chapter, you will find some
key terms that will aid you greatly in your endeavor to become an Arduino
user.
As mentioned earlier, Arduino is open-source, meaning you can use it and
teach it to others without violating any copyright laws. It is based on easy-to-
use hardware, which is the actual physical computer board with which you
will be working, and straightforward software, the coded instructions with
which you will use to direct the hardware to perform a task of your choosing.
The software is also known as code, and the individual pieces of instructions
are called tools.
Anatomy of the Arduino Board
The board itself contains a good number of parts. The digital pins run along
the edges of most Arduino microcontrollers and are used for input, or sensing
of a condition, and output, the response that the controller makes to the input.
For example, the input might be that the light sensor senses darkness, that is,
a lack of light. It will then close a circuit lighting up a bulb as output: a
nightlight for your child.
On most boards, there will be a Pin LED, associated with a specific pin, like
Pin 13 on the Arduino Uno. This Pin LED is the only output possibility built
into the board, and it will help you with your first project of a “blink sketch,”
which will be explained later. The Pin LED is also used for debugging or
fixing the code you have written so that it has no mistakes in it. The Power
LED is what its name implies: it lights up when the board is receiving power
or is “turned on.” This can also be helpful in debugging your code.
There exists on every board the microcontroller itself, called the ATmega
microcontroller, which is the brain of the entire board. It receives your
instructions and acts accordingly. Without this, the entire board would have
no functionality.
Analog in pins exist on the opposite edge of the board from the digital pins
on the Arduino Uno. It is an input into the Arduino system. Analog means
that the signal which is input is not constant but instead varies with time, such
as audio input. In the example of audio input, the auditory input in a room
varies with the people in the room talking and with the noises filtering in
from outside the room.
GND and 5V pins are used to create additional power of 5V to the circuit and
microcontroller. The power connector is most often on the edge of the
Arduino board, and it is used to provide power to the microcontroller when it
is not plugged into the USB. The USB port can be used as a power source as
well, but its main function is to upload, or transfer, your sketch, or set of
instructions that you have coded, from your computer to the Arduino.
TX and RX LED’s are used to indicate that there is a transfer of information
occurring. This indication of communication will happen when you upload
your sketches from your computer to the Arduino so that they will blink
rapidly during the exchange.
The reset button is as it sounds: it resets the microcontroller to factory
settings and erases any information you have uploaded to the Arduino.
Other Terms about Working with Arduino
There are three types of memory in an Arduino system. Memory is the space
where information is stored.
Flash memory is where the code for the program that you have written is
stored. It is also called the “program space,” because it is used for the
program automatically when you upload it to the Arduino. This type of
memory remains intact when the power is cut off, or when the Arduino is
turned off.
SRAM (static random-access memory) is the space used by the sketch or
program you have created to create, store, and work with information from
the input sources to create an output. This type of storage disappears once the
power is turned off.
EEPROM is like a tiny a hard-drive that allows the programmer to store
information other than the program itself when the Arduino is turned off.
There are separate instructions for the EEPROM, for reading, writing, and
erasing, as well as other functions.
Certain digital pins will be designated as PWM pins, meaning that they can
create analog using digital means. Analog, as we remember, means that input
(or output) is varied and not constant. Normally, digital pins can only create a
constant flow of energy. However, PWM pins can vary the "pulse" of energy
between 0 and 5 Volts. Certain tasks that you program can only be carried out
by PWM pins.
In addition, in comparing microcontroller boards, you will want to look at
clock speed, which is the speed at which the microcontroller operates. The
faster the speed, the more responsive it the board will be, but the more battery
or energy it will consume as well.
UART measures the number of serial communication lines the device can
handle. Serial communication lines are lines that transfer data serially, that is,
in a line rather than in parallel or simultaneously. It requires much less
hardware to process things serially than in parallel.
Some projects will have you connecting devices to the Internet of Things,
which essentially describes the interconnectedness of devices, other than
desktop and laptop computers, to various networks in order to share
information. Everything from smart refrigerators, to smartphones, to smart
TV’s are connected to the Internet of Things.
Chapter 2 Working with User-Defined
Functions
Another thing that we need to take a look at before we end this guidebook is
the idea of the user defined function. One of the methods that you are able to
keep the code that you are writing, in Arduino and in other languages, clean
and organized and modular or reusable, is to make sure that you work with
functions inside of that code. In addition, these functions are able to make
some of the code smaller because parts of the code, and small sections of it,
can be reusable. Functions are going to be like tools that were created in
order to serve the particular function that you would like, just like the name is
going to suggest.
While we have already gone through and encountered some examples of
these particular functions as we go through this guidebook, we now need to
go through some of the details that come with them and really understand
some of the parts that go with them. This is going to help us to explain some
of the features that we may have glossed over in the first place, so that we
really know what these functions are like.
The first thing that we are able to do here is to look at the declaration of the
function that we want to work with. A good example of how to do this is
going to be below:
float results: // this will be the value that we are going to return when this
function has been called up. We want to make sure that it is going to
match the type of data that we are using before the name of the function
Return results // return tells the function that it needs to send a value
back once to where it was originally called.
}
Take some time to look over that code and see what it is able to offer in terms
of what you are able to do with it, and even what you are able to understand
out of the code based on what we have already been able to work with. You
can even get some practice in order to get better at this by typing the code out
a few times and gaining a feel for it.
This function is going to take on two arguments in order to be successful. It is
going to be with the hoursWorked and the payRate in order to handle some of
the work that we are doing, and both of these are going to be floats. It does
take us some time to work on simple math on these and then it is going to
return a float as the value.
The return that we are working on here means that we want to end or
terminate the function and then send back the value that was placed with us,
after the word return, which is usually going to be a variable, as the results of
the calculations that we did. All of this is going to be done to help us
understand how these functions work and how we are able to do some stuff
with them.
With this in mind, we then need to go through and call up this function. This
will allow us to see what the earnings of the employee’s are, and can make it
easier to see what we are going to get out of this process as well when we
work with some of the functions. The code that we are going to need to work
with to make this happen will include:
void loop () {
floathoursWorked = 37.5;
As we can see here, we have spent a good deal of time talking about a lot of
different topics, especially the functions that we are able to use when we are
working with the serial class and how it is going to pertain to some of the
programming that happens with the Arduino API. This can help us to get so
much done with some of the coding that we need, and can be an important
class that will help us to get more done with our API.
Chapter 4 Connecting Switch
The push buttons or switches are going to connect two terminals that are open
inside of a circuit.
Pull Down Resistor
The resistor is going to be used when you are working with electronic logic
circuits so that it can make sure that the inputs that are on the Arduino panel
are settled at the logic levels that are expected. In the event that there are
external pieces of equipment that are not connected or are at a high
impedance, then nothing is going to be attached to the input pin. This does
not mean that it is a logical zero. The pull-down resistor is going to be
connected to the ground and the proper pin on the device.
One example would be for the resistor in the circuit to be connected between
the supply voltage and the microcontroller pin. In these circuits, the switch is
going to be closed while the microcontroller input is high. However, when
the switch is open, the resistor is going to pull the input voltage down so that
it can prevent an undefined state of the input.
The resistor has to have a massive resistance over the impedance of the logic
circuit, or it is going to pull the voltage down lower than it is supposed to be
which is going to cause the input voltage to remain at a low value no matter
where the switch is.
Components
1. LED (1)
2. Arduino Uno panel (1)
3. 4.7 k ohm resistor (1)
4. 330 ohm resistor (1)
Code
// constants are not going to change they are going to be used to set the pin
digital representations
Const int buttons pin = 8 // the digital representation of the push button pin
Const int led pin = 2 ; // the LED pin
// variable will change
Int button state = 0 ; // variable for reading the button status
Void setup () {
// initialize the LD pin as an output
Pin mode (led pin, output) ;
// initialize push button as an input ;
Pin mode (button pin, input0 ;
}
Void loop () {
// read the state of the push button value ;
Button state = digital read (button pin) ;
// check if the push button has been pushed
// if yes, then the button state will be high
If (button state == high) {
// turn LED on ;
Digital write (led pin , high) ;
} else {
// turn LED off
Digital write (led pin , low) ;
}
}
Chapter 5 Temperature Sensor
The temperature sensor is going to be a precision integrated circuit of
temperature pieces of equipment that are going to contain an output voltage
linearly proportional to the Centigrade temperature.
The LM35 device is going to have advantages over the linear temperature
sensors that are calibrated to Kelvin so that the user is not required to deduct
an extensive and continuous voltage from the output to get the Centigrade
scaling. This device will not demand any additional calibration from outside
sources or trim with a view to obtaining maximum accuracy. Most accuracies
are going to be a fourth off either direction.
Technical Specifications
Components
Code
This is the code that you are going to place in the Arduino sketch program
after you have created a more up to date file.
Float temp ;
Int temp pin = 1 ;
Void setup () {
Serial begin (8999) ;
Void loop () {
Temp = analog read (temp pin) ;
// read analog volt from sensor and save to variable temp
Temp = temp * 3.939403021 ;
// convert the analog volt to its tempt equivalent
Serial print (temperature = ) ;
Serial print (temp) ; // show temperature value
Serial print ( F ) ;
Serial print in () ;
Delay ( 300) ; // update sensor reading each one second
}
Notes on the code
The result that you are going to see is the temperature displayed on the serial
port monitor which is updated each second.
Water Detector and Sensor
The water sensor brick is going to be designed for detecting water. This is
going to be most often used to sense predetermined markers such as any leaks
or even water levels.
When you are choosing to connect the water sensor to the Arduino panels,
the sensor is going to be able to detect any measurement of water. It can
accurately measure the level, presence, volume, or even if there is a complete
lack of water. This is a great feature and even has the ability to remind the
owner when it is time to water household plants!
You will be able to connect the water sensor to the eighth pin on the Arduino
board.this pin is going to enlist an LED that enables us to identify when the
sensor has come been exposed to water of any level.
Components
Procedure
Code
# define grove water sensor 9 // attach water sensor to Arduino digital pin 8
#define LED 9 // attach an LED to pin 9
Void setup () {
Pin mode (grove water sensor, input) ; // the water sensor will be an input
Pin mode (led, output) ; // the led will be an output
}
Notes on the code
There are going to be three terminals for the water sensor, and it is going to
connect as follows.
PIR Sensor
A PIR sensor is going to allow you pick up motions, in other words, it is
going to be a motion sensor. The sensor will detect movement inside of the
sensors range. You are commonly going to find these sensors outside of
homes and businesses. PIR is going to stand for passive infrared,
pyroelectric, or IR motion sensor.
Here are some of the advantages of having a PIR sensor.
Procedure
Code
#define pir pin 2
Int calibration time = 30 ;
Long unsigned int low in ;
Long unsigned int pause = 4000 ;
Boolean lock low = true ;
Boolean take low time ;
Int pir value = 0 ;
Void setup () {
Serial begin ( 9600) ;
Pin mode (pir pin, input) ;
}
Void look () {
Pir sensor () ;
}
Void pir sensor () {
if (digital read (pir pin ) == high ) {
if (lock low) {
pir value = 1;
lock low = false ;
serial print in (motion detected) ;
delay (60) ;
}
Take low time = true ;
}
If (digital read (pir pin) == low {
If (take low time ) {
Low in = millis() ; take low time = false ;
}
If (!locklow && millis () – lowin > pause) {
Pirvalue = 0 ;
Locklow = true ;
Serial print in (motion ended) ;
Delay (60)
}
}
Notes on code
There are three terminals for the pir.
You are going to be able to adjust the sensor sensitivity and delay time with
two variable resistors that you can find at the bottom of the panel. After the
sensor detects motion, the Arduino is going to send you a message to inform
you that it has detected motion. The pir sensor is going to be delayed for
some time to check if there is any more up to date motion. In the event that
there is no more up to date motion detected, the panel will send you a
message telling you so.
Chapter 6 Using the Stream Class
This is a topic that is going to be so important to what we are trying to do
with some of our work that it really did deserve its own chapter to help us get
the work done. While this one is still going to work with the API of Arduino
that we talked about before it is going to be pretty broad and will talk about a
lot of different parts, so we are going to break off here and work with the
stream class, which also allows us to work with strings along the way.
The stream class is going to be a fairly simple concept even though it is really
important to work with. The stream class on its own is going to be based on
using reading information from a certain source, and then having this as how
you make up your own sketch. Because the stream is all about reading the
data, it is also important that we talk about working with a mouse and
keyboard with the Arduino board in this chapter, even though we may think
that these are not going to be related directly to the stream class that we are
working with.
When you decide to work with the data, especially when you are readying the
data, you will find that there are times when we need to work with sets of
characters that are longer, like a sentence. The idea of strings is going to give
you the chance to do this on our board. Strings are going to basically just be
sets of character values that will be linked together like with an array. This
means that they are going to be contiguous in the memory, and the computer
is going to see them as one large and interconnected unit. Working with the
strings means that we need to learn how to manipulate these units as well as
our abilities will allow.
On its own, it is going to be pretty simple. Thought to work with. Strings are
just going to be what we know as character arrays. That means that we are
still working with some of the C-style strings, which are going to be strings
that have abstraction at a very low level. For example, in a lot of the newer
programming languages, the strings are not going to be revealed in their
character as a character array. Instead of doing this, they are going to be
treated as an abstract object instead. Even if they are considered a character
array, they will be treated in this manner.
A string is going to be composed of the n + 1 characters, where n is going to
be the number of letters that is in the string in general. So, for example, the
size of a string for the word “hello” would end up being the six characters.
The reason for this is because the string is going to end in a null terminating
character, which is going to indicate to us that the end of the array has been
reached and that it can be ended.
You are able to go through and define a string in the same manner that you
would an array. You are able to also make them bigger than the string that
you plan to have them contain. When you go through the process of defining
an array you may give it a value right of the bat, but you can also just define
the size and expand them out at a later time. this also makes strings, more
dynamic and can allow us to change them up later on when we rewrite some
of the data that is inside of that string.
This information is going to be useful to a programmer who is just getting
started because these strings are going to be fundamental and important to
any of the programs that you use that handle information, especially those
that are going to handle the input and the output of the file. We have already
spent some time looking at this, now, but we also need to go ahead and learn
how we are able to define our string. The code that we are able to use for this
one will be below:
char myString[6] = “hello”;
You can then spend some time referring to this entire string at a later point
with the name of the character. Most of the data that is worked with by the
board is going to be worked with in terms of how many bytes it is, and most
of the actual textual data is going to be worked with in terms of C strings
because it is easy to parse these characters when you would like.
It is important that we go over all of these parts so that we learn and develop
the right ideas that we need when it is time to treat the strings in this kind of
programming and we see what we are able to do with some of these parts as
well. Let’s dive a bit more into this to see how it will work.
The Serial
While you are not necessarily able to implement the stream class in itself, you
are able to go through and implement some of the derivatives of it, and this is
where we are going to find a lot of the utility that we need. The serial class
that we are going with here is going to be an extension of what we are able to
do with the stream class, and it is going to help us to communicate with some
of the other devices that we want, such as the computer.
The serial is going to be enacted through both the port on the Arduino for the
Serial, as well as on the link for the USB on the computer. We are going to
then look at some of the functions that are available with the Serial class,
making it easier for you to use this kind of thing and get the most out of this
resource along the way as well:
As we can see here, we have spent a good deal of time talking about a lot of
different topics, especially the functions that we are able to use when we are
working with the serial class and how it is going to pertain to some of the
programming that happens with the Arduino API. This can help us to get so
much done with some of the coding that we need, and can be an important
class that will help us to get more done with our API.
Chapter 7 Calculated Digital Representations
To generate calculated digital representations, you will use the calculated
digital representation functions. You are going to have two functions to
choose from.
1. Calculated ()
Calculated ()
The calculated function is going to create pseudo calculated digital
representations.
Syntax
Long calculated (max) // it generates calculated digital representations from
zero to max
Long calculated (min, max) // it generates calculated digital representations
from min to max
Example
Long rand digital representation ;
Void setup () {
Serial. Begin (4329) ;
// if analog input pin zero is unconnected, calculated analog
// commotion will cause the call to calculated seed () to generate
// different seed digital representations every time that your sketch executes
code
// calculated seed () will then shuffle the calculated function
Calculated seed (analog read (1) ) ;
}
Void loop () {
// print a calculated digital representation from zero to two hundred and
ninety-nine
Serial. Print (“calculated1 =”) ;
Rand digital representation = calculated (301) ;
Serial. Println (rand digital representation) ; // print a calculated digital
representation from zero to two hundred and ninety-nine.
Serial print (“calculated 2”) ;
Rand digital representation = calculated ( 29, 39) ; // print a calculated digital
representation from twenty-nine to thirty-nine
Serial. Print ln (rand digital representation ) ;
Delay (29) ;
}
Bits
A bit is going to be a binary digit.
Any binary system that you use is going to use at least two digits, one and
zero.
The bit system will work like the decimal digital representation system is
going to work, because the digital representations will not hold the same
value, the significance of a bit is going to depend on where you locate it in
the digital representation line for binary digital representations. Take for
example the decimal digital representation three hundred and three is going to
be the same digital representations, but they are going to have different
values.
Bytes
Bytes are going to consist of eight bits.
In the event that bits are represented by digits, then you can safely assume
that a byte will be represented by a digital representation.
All mathematical equations can be completed with a byte.
The digits of a byte are not going to have the same significance.
The leftmost bit is going to have the greatest value, and it is going to be
known as the most significant bit or MSB. On the opposite end, it is going to
be referred to as the least important bit.
Being that there will be eight ones and zeros that are going to be one byte, at
least two hundred and fifty-six of them are going to be used in various ways.
The larger decimal digital representation is going to be shown by using a byte
which will be two hundred and fifty-five.
Chapter 8 Understanding the Arduino
Framework
In this chapter, we’re going to actually start looking at the code which fuels
Arduino. At this point, we are assuming that you have your Arduino unit and
you’ve got it set up and linked to your computer. This is the first step.
The second step is to get an Arduino compatible IDE. For most beginners and
novices, the ones supplied by Arduino themselves will be more than enough.
You can navigate to their website and either download the desktop IDE or
use the web-based IDE. Either one will work perfectly fine.
So, from here, we need to talk about the structure of sketches.
An Arduino sketch has two basic components that make it up: the ‘setup’
function and the ‘loop’ function. Both are essential to the overall functioning
of the Arduino sketch, and so you need to make sure that every sketch you
run has them. Your sketches, of course, are not limited to just these functions,
and you can expand with more functions at ease as we described back in the
C chapter.
The Arduino ‘language,’ so to speak, is just an extension of C and C++,
which means that C and C++ coding conventions will work within them, as
well as all of the things that we described previously. This makes
programming your Arduino unit relatively easy.
The Arduino ‘language’ is actually a library with various different definitions
and functions that are tailored to the Arduino.
This is how the most basic of Arduino programs look, in terms of structure:
void setup()
{
// code within
}
void loop()
{
// code within
}
The setup function should be just after the declaration of variables at the start
of your sketch. It will always be the first function that your Arduino unit
runs, so pay careful attention. You must have your setup function, even if
there is nothing within it.
You use the setup function to do things like initializing Arduino relevant
variables, like your pin modes. In other words, any necessary setup that you
have to do to get everything up and running, those functions should be called
from within your setup function.
Do note that not necessarily all of your variables must be declared here.
Variables should generally be declared within their primary function or in the
global scope. If you fail to define a function at these levels, you won’t be able
to use it where you want it to. For example, if you defined a variable within
the setup function, you wouldn’t be able to use it within your loop function
since it was defined within another function and isn’t global.
The loop function does pretty much exactly what it sounds like: it loops over
and over until the program is brought to an end. When the program finally is
brought to an end, the loop ends. Programs are generally brought to an end by
cutting off power to your Arduino unit, so there isn’t much of a way to exit
the Arduino loop function. This is the primary function of your program, and
everything happens from here.
Consider the fact that when you program something like an Arduino gadget,
it really is just looping some function over and over every second, even if that
loop is just something like waiting to receive input and then responding
respectively when said input is given.
In terms of actual Arduino code from the framework, there are a few that you
really need to know at this point.
Constants
Constants are a foundational part of Arduino programming because they
allow you to make comparisons or assign certain things easily. Constants are
variables which are predefined and do not change. They can be used as
references in other functions used within the language.
Two constants are ‘TRUE’ and ‘FALSE.’ This harkens back to the language
on Booleans. TRUE here is defined as anything other than zero, where
FALSE is zero.
Two more are ‘HIGH’ and ‘LOW.’ These refer to the voltage being given to
the pin, and the respective pin levels. HIGH refers to a pin which is ‘ON’ and
which is receiving 5 volts while LOW refers to a pin which is ‘OFF’ and is
receiving zero volts. This is used most often when you are either giving or
receiving data from digital pins.
The other two constants that you need to know at this point are ‘INPUT’ and
‘OUTPUT,’ which merely allow you to define the mode of something and
whether it is for incoming data or outgoing data.
Functions
There are some different functions that are inherent to Arduino programming
that we need to cover. While a large amount of Arduino functions will vary
depending upon the gadgets you have and the project that you’re specifically
trying to tackle, there are nonetheless manifold important
The first is pinMode, which takes the arguments of pin and mode. Pin is the
respective integer of the given pin, where mode is either OUTPUT or INPUT,
as we just said. Therefore, it ties in perfectly to what we were just discussing
with the constants. This function will always be called within your setup
function.
The next is digitalRead(), which takes an argument of a given pin, either as
a constant or a variable. This will read in a value from a given pin and return
either HIGH or LOW, this indicates either true/false, on/off, or 5v/0v.
The next is digitalWrite, which takes the arguments of a pin as well as
HIGH or LOW, which will essentially turn a given pin on or off.
The next is analogRead, which accepts an argument of a given pin and will
take a value from the analog in pins. It will return an integer value instead of
HIGH or LOW.
After that is analogWrite, which will take the arguments of pin and value.
AnalogWrite allows you to write what is essentially an analog value to a
given pin. The value can be from 0 to 255, and the size of the number will
indicate how often the signal sent is either 5 or 0 volts; a larger number
indicates that the charge will more often be 5 volts than 0 volts. This works in
a wave manner and will, therefore, act as a means to regulate how much
power is being sent to the given pin.
After the read and write functions is the delay function, which pauses the
program. It takes an argument of milliseconds, either as a variable or a
constant. It will cause a pause in that length.
Beyond that is millis() which just returns the number of milliseconds that
have passed since the current sketch started as a long. This number resets
after several hours.
After that are the min and max functions, which take two arguments both and
return either the smaller or larger number respectively. They accept numbers
regardless of data type.
After that is randomSeed which accepts a given integer as an argument. This
creates a seed for a random number generator.
Beyond this are the two random functions. Given one argument, the random
function will return any number from zero to the max value. Given two
arguments, it will return a number between the two numbers given. You must
use randomSeed before you use a random function.
The last two functions we need to cover are the ‘Serial’ functions, which
allow you to transmit serial data:
{
int i = *p1;
*p1 = *p2;
*p2 = i;
}
Easy peasy. The logic behind it is a little rough, but that’s all an important
part of the learning process!
Now, moving on beyond this, we’re going to now work with our sort
function. The sort function will create two iterative arrays. It will accept the
arguments of the array’s size and the array itself. It will iterate through these
accordingly. Since we’re comparing in a forward manner, the active position
should only extend to the size of the array minus one element; otherwise,
when the last element in the array is reached, there will be an element
overflow error, and the program will crash (if it executes at all.)
For the second for loop, we need to iterate according to the size minus the
active position minus 1.
Within the second for loop, we need to define an if statement which checks to
see whether the active integer is larger than the number immediately ahead of
it. If it is, then the two swap positions, meaning we throw the memory
addresses of the two to the swap function.
Here is how I would define this function:
void sort(int myArray[], int size)
{
for (int i = 0; i < size - 1; i++)
for (int j = 0; j < size - i - 1; j++)
if (myArray[j] > myArray[j+1])
swap(&myArray[j], &myArray[j+1]);
}
Again, it’s not a terribly difficult algorithm, but it does require a bit of
thought and is a decent introduction to algorithmic thinking if you’ve never
done so before. To test this all, we can create a program with our test array
that will do all of this, then print it out for us so that we can see if all is in
working order:
#include <stdio.h>
void swap(int *p1, int *p2)
{
int i = *p1;
*p1 = *p2;
*p2 = i;
}
void sort(int myArray[], int size)
{
for (int i = 0; i < size - 1; i++)
for (int j = 0; j < size - i - 1; j++)
if (myArray[j] > myArray[j+1])
swap(&myArray[j], &myArray[j+1]);
}
int main()
{
int numbers[10] = { 39, 63, 10, 70, 23, 34, 63, 13, 76, 34 };
int size = sizeof(numbers)/sizeof(numbers[0]);
sort(numbers, size);
for (int i = 0; i < size; i++)
{
printf(“%d”, numbers[i]);
}
}
Your end program should look somewhat like the one above. If so, then
you’ve succeeded.
The next thing that we’re going to discuss in an algorithmic sense is
probability using a very rudimentary version of Bayes’ theorem.
So what exactly is Bayes’ theorem, and why is it useful as an Arduino
programmer? Well, Bayes’ theorem in and of itself is a way of determining
true probability of a given situation based upon the likelihood that something
has happened in the past. It takes into account various given rates and then
returns a certain dimension based on those rates.
For this, we can take two events: event X and event Y. We then have P(X)
which is the likelihood of X, and P(Y) which is the likelihood of Y. P(X|Y) is
the likelihood of event X given that Y is true, and P(Y|X) is the likelihood of
event Y if event X is true.
Let’s say we’re trying to find the likelihood of event X given that Y is true,
and we have data related to event Y is X is true. Bayes’ theorem then allows
us to look at it like so:
P(X|Y) = P(Y|X)*P(X) / P(Y)
In other words, the probability of event X given that Y is true is equivalent to
the probability of Y given that X is true multiplied by the probability of X,
then all of this divided over the probability of Y.
Bayes’ theorem is a little difficult to grasp if you aren’t looking at it in an
intuitive manner. Take, for example, spam filtering, which is a rather
common application of Bayes’ theorem in the world of computer science.
Let’s say that event X is the likelihood that the message is spam, and event Y
is the likelihood that it contains certain words flagged as spam. P(X|Y) is the
probability that it is spam given that it contains words flagged as spam.
P(Y|X) is the probability that a certain word flagged as spam will be in a
spam message. P(X) is the probability that any given message is spam, and
P(Y) is the probability that the words within are flagged for spam.
{
return (ygivenx * x) / y;
}
int main()
{
double spam = 3100, words = 6888, wordsgivenspam = 7000;
double spamgivenwords = calc_prob(wordsgivenspam, spam, words);
printf(“%.2f”, spamgivenwords);
}
With that, you’ve written your second algorithm. Probability algorithms
become massively useful when you need your Arduino programs to be able
to act predictively. For example, you could use your Arduino to model
certain situations or react accordingly. While it’s not powerful enough for
hardcore number crunching, it will definitely be powerful enough for basic
probability equations. This, for example, is nothing too intensive. So long as
it can retrieve information to form a dataset, you can use much of the
information in this book to make highly reactive Arduino sketches that could,
ideally, change the world.
The purpose of introducing these two algorithms was to give you insight as to
how algorithms might impact your programming and how thinking
algorithmically can be a major boon to your ability to program in the first
place. Consider that the ability to mentally process and break apart certain
functions is foundational to being able to think like a programmer, which - in
the end - is what this book is trying to help you do.
Chapter 10 Troubleshooting
As you work on your projects, there are specific situations when there will be
troubleshooting and debugging.
The more you use Arduino and electronics, the better you become and gain
experience. This will end up making the whole process less painful. Don’t be
frustrated with the problems that you experience. It is much easy than the
way it might look at the start.
Since each Arduino project consists of a hardware and software, there are
many places to check when things go wrong. Therefore, when debugging,
you need to consider these three aspects:
Understanding
You should strive to understand as much as you can in the way the parts you
have in your project operate and how they should contribute to the final
project. This method will allow you to develop ways in which you can check
every component independently.
Simplify and segment
In the ancient Romans, they had what we call divide and rule type of
government. You need to break down your project into different components
using your intelligence to determine which part of a given function starts and
ends.
Exclusion and Certainty
While investigating, you need to check each component individually to
ensure that you are sure every component works by itself. You will slowly
develop your confidence and note the parts of the project that are doing well
and areas that you should fix.
Debugging is the term we refer to the process of fixing errors in software. It
was first used by Grace Hopper back in the 1940s. This was the time when
computers were majorly electrochemical. It is believed one computer stopped
working after an actual insect found its way inside.
However, many of today’s bugs are not physical like in this case. Instead,
they are virtual and invisible. This means they call for more time and that
process can be boring.
Testing the Board
What if the first example of blinking an LED failed to work? That would
possibly be frustrating. Let us see what you can do.
Before you throw complains at your project, you need to ascertain that
several things are in the right place. This is similar to the way airline pilots
follow when they run through a list of things to make sure that there will be
no problems when the plane takes off.
The first thing you need to do is to plug your USB into your computer:
Create a stand using the cardboard and allow power to flow to the Arduino
using a battery. You can build a cover that has some numeric displays close
to the lights.
Tilt switches are cheap and affordable components to help one tell the
orientation of something. Another example of tilt sensors are the
accelerometers. In addition, they are quite expensive. If you are only
interested to see whether something is up or down, you should go with the tilt
sensors.
The Code
Define a constant
In this project, you will need to have several global variables so that you can
have everything work. To begin with, define a constant called switchPin.
Declare a variable to store time
Declare an unsigned long variable. This variable will record the last time the
LED changed.
Declare variables to hold inputs and outputs
Define variables for both the switch state and previous switch state. The input
and output variables will help make a comparison of the switch’s position
from one state to the next. Declare a variable called led. This will make the
next LED to switch on. You can start with pin 2.
Variable declaration showing the interval between two events
The last variable to define is the interval between each LED. This is the long
datatype.
Determine the time the program started.
Once the loop() begins, you can find the time the Arduino has been on using
the function millis() and place it in a variable called currentTime.
Determine the time that has elapsed since the first loop()
With the help of an if() statement, you need to determine whether time has
reached to switch on the LED. Perform some mathematical operations by
subtracting the currentTime from the original time and test to see if it is more
than the interval variable.
Switch on the LED, and prepare for the next
The previousTime displays the last time the LED was on. The moment the
previousTime is set, switch on the LED and increase the led variable. If you
pass the time interval again, the next LED lights up.
Find out whether all the lights are on
Create another if statement in the program to help you determine whether the
LED on pin marked 7 is on. Make sure you do not attempt anything with it.
Towards the end of the loop, save the state of the switch in the
prevSwitchState, and compare it with the value you receive for the
switchState in next loop().
If you are done with programming the board, look at the time in the clock.
Once 10 minutes pass, the first LED has to be turned on. After every 10
minutes, a new light will display. After an hour, all the six light will turn on.
Chapter 12 Spend Time Thinking Outside the
Box (and the Arduino)
In this chapter, we’re going to talk about how creative thinking and spending
time away from Arduino programming both might enable you to be a better
Arduino programmer in the end.
This may not make a lot of sense, but the fact is that both of these ideas have
a lot of credence. No masterful painter ever got to their mastery by working
simply with oils, though they may strongly prefer to work with oils. The
same applies here: without thinking outside the box and working outside of
your comfort zone, you’re going to be missing out on a lot of different things
that would lead you to become a better programmer and a better Arduino
builder in general.
Here’s a simple fact for you: all of creativity is based on the way that the
brain processes inputs and outputs. Although there is some variety of
spontaneous components, you can only ever invent things which are based on
those things you’ve already learned or those things you’ve already been made
aware of. Your ideas will almost always be based on those inputs that you’ve
already dealt with in the past instead of being based on things that are
spontaneously generated in terms of new ideas.
Spontaneous generation of ideas can lead to really cool and abstract things,
but even the most spontaneous ideas are based on learned stimuli, from a
psychological perspective. In other words, no thought that you’ve ever had
has been completely original, because all of your thoughts are formed by the
world around you and the unique way in which you happen to process all of
that information.
If you want to be a good Arduino programmer, you really need to not stop at
Arduino programming. For example, the fundamental languages which
power the Arduino language itself, C and C++, have been used for a massive
variety of different utilities in the nearly forty years that they’ve been around.
At some point in these languages’ long histories, there has been something
done that you’ve never even thought of, surely.
It is by taking in these inputs and getting this practice that you enable
yourself to become a better programmer and do more.
I think that a good example would harken back to the phenomenon known as
a Magic Mirror. Magic Mirrors are computer monitors which display
information fed in by a Raspberry Pi, a microcomputer not too different from
an Arduino through a tad bit more powerful and intended for different
purposes. The monitor is tucked behind a one-sided mirror such that the
information on the monitor displays on the reflective side of the mirror. What
results is a mirror that is incredibly science fiction becoming a science
reality.
The thing is that while the project itself is simple, the logic behind the
program really isn’t; for example, to display the data, a modified version of
the Chromium browser is used. Within that Chromium browser, a custom
page is built using HTML, CSS, and JavaScript (to retrieve information from
the web).
It is through the knowledge of how to make these different things happen that
a project as ambitious as the Magic Mirror was made possible. If one didn’t
have the knowledge of how to modify and recompile the Chromium browser,
nor if they didn’t have the knowledge on how to build web pages using
HTML, CSS, and JavaScript, the project simply would have never happened;
it would have remained science fiction.
In other words, you may have incredible ideas, but actually being able to take
action to make them happen is an entirely different beast altogether. One
thing is for certain: building up the knowledge required to, for example, build
web pages or modify and recompile a web browser then write a bash script to
automatically launch it upon the operating system starting up are things
which go well beyond the scope of hobbyist programming for the Arduino.
You can ask for the help of other people, but that will only get you so far and
nudge you along a little at a time. So what’s the other option, then?
All of this chapter has been building up to this: your ability to program
Arduino sketches and to make your dream projects happen is based on you,
not programming in Arduino at all.
Programming is a common set of skills that usually transfer across projects,
but as an Arduino programmer, you generally are not building these skills in
the optimal way. Reading books like this one is a start because they teach you
the underlying concepts to all of the computer science mumbo-jumbo that
you’re being fed, which hopefully acts to help make things click a little bit.
But there are a lot of bigger concepts that you aren’t going to pick up just
within your Arduino IDE. These are things like working with APIs, learning
how to read documentation, learning how to create header files or libraries to
make your programs more modular, learning in general how to be a better
programmer.
These are skills which you gain through continually challenging yourself and
trying to come up with new things.
And this has a little perk tacked onto the end of it, too: if you try to work on
new things, you will be inspired more often. You’ll learn how to do things
and start having ideas that you wouldn’t have had otherwise, because you’ll
be enjoying new experiences and getting all sorts of new inputs. When you
think about things you’ve never thought about before, your brain interprets
this as a good thing - as a learning experience. This will expand your mind
and make you more creative, in turn making you simultaneously a better
programmer and a better tinkerer.
So in other words, if you want to be a good Arduino programmer, one of the
best things that you can possibly do for yourself is to start working on
projects that aren’t Arduino-based. You need to be exposing yourself to new
things and challenging yourself to become better all of the time.
Chapter 13 Troubleshooting
As you work on your projects, there are specific situations when there will be
troubleshooting and debugging.
The more you use Arduino and electronics, the better you become and gain
experience. This will end up making the whole process less painful. Don’t be
frustrated with the problems that you experience. It is much easy than the
way it might look at the start.
Since each Arduino project consists of a hardware and software, there are
many places to check when things go wrong. Therefore, when debugging,
you need to consider these three aspects:
Understanding
You should strive to understand as much as you can in the way the parts you
have in your project operate and how they should contribute to the final
project. This method will allow you to develop ways in which you can check
every component independently.
Simplify and segment
In the ancient Romans, they had what we call divide and rule type of
government. You need to break down your project into different components
using your intelligence to determine which part of a given function starts and
ends.
Testing the Board
What if the first example of blinking an LED failed to work? That would
possibly be frustrating. Let us see what you can do.
Before you throw complains at your project, you need to ascertain that
several things are in the right place. This is similar to the way airline pilots
follow when they run through a list of things to make sure that there will be
no problems when the plane takes off.
The first thing you need to do is to plug your USB into your computer: