Python Tricks Tips
Python Tricks Tips
Python
Tricks and Tips
Gain
Insider
Skills
Step 1
Don’t skip - While it’s fun to see what’s coming up later in the book, it
does make understanding what you’re reading more difficult. After all,
you wouldn’t start reading a book on speaking French, then skip further
in without first learning proper grammar, sentence structure and so
on. The same applies here. Take your first read-through page by-page,
once you’ve mastered the book, then you can return to key concepts
whenever you need.
Step 2
Ever-Changing - While every effort has been made to ensure that this
book is up to date, there’s no knowing what updates may occur over
time. While some companies do offer an accurate roadmap of their
future development of a product, it’s not always written in stone. For
example, an app available for Windows 10 now may not be available with
the next update of the operating system. It’s up to Microsoft to decide
whether they want to drop it for one reason or another. The same, to
some extent, applies here. However, we continually update the content
in this title, so it’s as accurate as possible.
Step 3
Follow the Steps - An obvious one, this. Following the steps from one
onwards, in most tutorials in this book, will ensure that you get the result
that’s intended. If you skip steps, then you may miss out on something
important, and not understand how it works later in the book. The
temptation to skip something you already know is often too much, but
stick with the logical progression of the steps and you’ll get the most
from what’s on offer.
Step 4
Have Fun - Learning a new skill is supposed to be fun. We had fun
writing the book, and hopefully you’ll have fun reading it and applying
new skills. Everyone learns at a different pace, so take your time, digest
the tutorials, and keep returning to key concepts if you feel the need to
master any element within these pages. The content in this book isn’t
something we’re going to be testing you on, so have fun and enjoy the
art of learning something new. And if you create something amazing
after reading this book, then let us know.
Contents
BDM’s
Code Port
60+ Pytho al
Contents
n program
21,500+ li s
Master Pyt
nes of code
hon w ith the he
fantastic C lp of ou
o
code for g de Portal, featurin r
Visit: http am es, too g
s://bdmp ls and more.
code-port ublications.com/
al, and
to get acce log in
ss!
38 C++ Input/Output
40 User Interaction
42 Character Literals
44 Defining Constants
46 File Input/Output
4 www.bdmpublications.com
Contents
www.bdmpublications.com 5
Say Hello to C++
www.bdmpublications.com 7
Say Hello to C++
Why C++?
C++ is one of the most popular programming languages available today. Originally
called C with Classes, the language was renamed C++ in 1983. It’s an extension of the
original C language and is a general purpose object-oriented (OOP) environment.
C EVERYTHING
Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs,
device drivers and even entire operating systems.
Dating back to 1979, the start of the golden era of home computing labs and by regular people who didn’t have access to the
computing, C++, or rather C with Classes, was the brainchild of mainframes and large computing data centres.
Danish computer scientist Bjarne Stroustrup while working on his
PhD thesis. Stroustrup’s plan was to further the original C language, C++’s impact in the digital world is immense. Many of the programs,
which was widely used since the early seventies. applications, games and even operating systems are coded using
C++. For example, all of Adobe’s major applications, such as
C++ proved to be popular among the developers of the ‘80s, Photoshop, InDesign and so on, are developed in C++. You will find
since it was a much easier environment to get to grips with and that the browser you surf the Internet with is written in C++, as
more importantly, it was 99% compatible with the original C well as Windows 10, Microsoft Office and the backbone to Google’s
language. This meant that it could be used beyond the mainstream search engine. Apple’s macOS is written largely in C++ (with some
8 www.bdmpublications.com
Why C++?
other languages mixed in depending on the function) and the likes begin with Python and spend some time getting to grips with
of NASA, SpaceX and even CERN use C++ for various applications, programming structure and the many ways and means in which
programs, controls and umpteen other computing tasks. you find a solution to a problem through programming. Once
you can happily power up your computer and whip
C++ is also extremely efficient and performs out a Python program with one hand tied behind
well across the board as well as being an your back, then move on to C++. Of course,
easier addition to the core C language. there’s nothing stopping you from jumping
This higher level of performance over straight into C++; if you feel up to the task,
other languages, such as Python, BASIC go for it.
and such, makes it an ideal development
environment for modern computing, Getting to use C++ is as easy as Python, all
hence the aforementioned companies you need is the right set of tools in which
using it so widely. to communicate with the computer in
C++ and you can start your journey. A C++
While Python is a great programming IDE is free of charge, even the immensely
language to learn, C++ puts the developer powerful Visual Studio from Microsoft
in a much wider world of coding. By is freely available to download and use.
mastering C++, you can find yourself You can get into C++ from any operating
developing code for the likes of Microsoft, Apple system, be it macOS, Linux, Windows or even
and so on. Generally, C++ developers enjoy a higher mobile platforms.
salary than programmers of some other languages and
due to its versatility, the C++ programmer can move between Just like Python, to answer the question of Why C++ is the
jobs and companies without the need to relearn anything specific. answer is because it’s fast, efficient and developed by most of the
However, Python is an easier language to begin with. If you’re applications you regularly use. It’s cutting edge and a fantastic
completely new to programming then we would recommend you language to master.
www.bdmpublications.com 9
Say Hello to C++
C++ SETUPS
Most, if not all, operating systems have C++ in their code, so it stands to reason that you can learn to program in C++ no matter
what OS you’re currently using.
COMPUTER
Unless you fancy writing out your C++ code by hand on a sheet of
paper (which is something many older coders used to do), a computer
is an absolute must have component. PC users can have any recent
Linux distro or Windows OS, Mac users the latest macOS.
AN IDE
Just as with Python, an IDE is used to enter and execute your C++
code. Many IDEs come with extensions and plugins that help make
it work better, or add an extra level of functionality. Often, an IDE
provides enhancements depending on the core OS being used, such as
being enhanced for Windows 10.
COMPILER
A compiler is a program that converts the C++ language into binary,
so that the computer can understand. While some IDEs come with a
compiler built in, others don’t. Code::Blocks is our favourite IDE that
comes with a C++ compiler as part of the package. More on this later.
TEXT EDITOR
Some programmers much prefer to use a text editor to assemble their
C++ code before running it through a compiler. Essentially you can
use any text editor to write code, just save it with a .cpp extension.
However, Notepad++ is one of the best code text editors available.
INTERNET ACCESS
While it’s entirely possible to learn how to code on a computer that’s
not attached to the Internet, it’s extraordinarily difficult. You need
to install relevant software, keep it up to date, install any extras or
extensions and look for help when coding. All of these require access
to the Internet.
OS SPECIFIC NEEDS
C++ will work in any operating system but getting all the necessary pieces together can be confusing to a newcomer. Here are
some OS specifics for C++.
LINUX WINDOWS
Linux users are lucky in that they already have a compiler and We have mentioned previously that a good IDE is Microsoft’s
text editor built into their operating system. Any text editor Visual Studio. However, a better IDE and compiler is
allows you to type out your C++ code, when it’s saved with a Code::Blocks, which is regularly kept up to date with a new
.cpp extension, use g++ to compile it. release twice a year. Otherwise Windows users can enter
their code in Notepad++, then compile it with MinGW as used
by Code::Blocks.
RASPBERRY PI MAC
The Raspberry Pi’s operating Mac owners will need to
system is Raspbian, which download and install Xcode
is Linux based. Therefore, to be able to compile their
you’re able to write your code C++ code natively. Other
out using a text editor, then options for the macOS
compile it with g++ as you include Netbeans, Eclipse or
would in any other Linux distro. Code::Blocks. Note: the
latest Code::Blocks isn’t
available for Mac due to a lack
of Mac developers.
www.bdmpublications.com 11
Say Hello to C++
How to Set Up
C++ in Windows
Windows users have a wealth of choice when it comes to programming in C++. There
are plenty of IDEs and compilers available, including Visual Studio from Microsoft.
However, in our opinion, the best C++ IDE to begin with is Code::Blocks.
CODE::BLOCKS
Code::Blocks is a free C++, C and Fortran IDE that’s feature rich and easily extendible with plug-ins. It’s easy to use, comes with
a compiler and has a vibrant community behind it.
STEP 1 Start by visiting the Code::Blocks download site, at STEP 3 When you’ve located the file, click on the
www.codeblocks.org/downloads. From there, click Sourceforge.net link at the end of the line and a
on the ‘Download the binary releases’ link to be taken to the latest download notification window appears; click on Save File to start
downloadable version for Windows. the download and save the executable to your PC. Locate the
downloaded Code::Blocks installer and double-click to start. Follow
the on-screen instructions to begin the installation.
STEP 2 You can see that there are several Windows versions STEP 4 Once you’ve agreed to the licencing terms, there is a
available. The one you want to download has choice of installation options available. You can opt
‘mingw-setup.exe’ at the end of the current version number. At for a smaller install, missing out on some of the components but we
the time of writing this is: codeblocks-17.12mingw-setup.exe. The would recommend you opt for the Full option as default.
difference is that the mingw-setup version includes a C++ compiler
and debugger from TDM-GCC (a compiler suite).
STEP 5 Next choose an install location for the Code::Blocks STEP 8 Before you start using Code::Blocks it’s worth
files. It’s your choice, but the default will generally explaining exactly why you need the added
suffice, unless of course you have any special requirements. When compiler. First, a compiler is a separate program that reads
you click Next, the install begins; when it’s finished a notification through your C++ code and checks it against the latest acceptable
pops up asking you if you want to start Code::Blocks now, so click Yes. programming standards; this is why you need the most recently
available compiler. This is currently C++17, with C++20 underway.
STEP 6 The first time Code::Blocks loads it runs an STEP 9 Essentially, computers work and understand only
auto-detect for any C++ compilers you may already binary, ones and zeros, or Machine Language.
have installed on you system. If you don’t have any, click on the Programming in binary isn’t effective for human beings. For
first detected option, GNU GCC Compiler, and click the Default example, to output the words “Hello World!” to the screen in C++
button to set it as the system’s C++ compiler. Click OK when you’re would appear in binary as:
ready to continue.
01100011 01101111 01110101 01110100 00100000
00111100 00111100 00100000 00100010 01001000
01100101 01101100 01101100 01101111 00100000
01010111 01101111 01110010 01101100 01100100
00100001 00100010 00111011
STEP 7 When the program starts another message appears, STEP 10 The compiler therefore takes what you’ve
informing you that Code::Blocks is currently not the entered as C++ code and translates that to
default application for C++ files. You a couple of options: to leave Machine Language. To execute C++ code the IDE ‘builds’ the code,
everything as it is or allow Code::Blocks to associate all C++ file checking for errors, then pass it through the compiler to check
types. Again, we would recommend you opt for the last choice to standardisation and convert it to ones and zeros for the computer
associate Code::Blocks with every supported file type. to act upon. It’s rather clever stuff, when you stop to think about it.
www.bdmpublications.com 13
Say Hello to C++
How to Set Up
C++ on a Mac
To begin C++ coding on a Mac you first need to install Apple’s Xcode. This is a free, full
featured IDE that’s designed to create native Apple apps. However, you can also use it
to create C++ code relatively easily.
XCODE
Apple’s Xcode is primarily designed for users to develop apps for macOS, iOS, tvOS and watchOS applications in Swift or
Objective-C but you can use it for C++ too.
STEP 1 Start by opening the App Store on your Mac, Apple STEP 3 When you’re ready, click on the Get button which
Menu > App Store. In the Search box enter ‘Xcode’ then turns into Install App. Enter your Apple ID
and press Return. There are many suggestions filling the App Store and Xcode begins to download and install. It may take some time
window but it’s the first option, Xcode, that you need to click on. depending on the speed of your Internet connection.
STEP 2 Take a moment to browse through the app’s STEP 4 When the installation is complete, click on the
information, including the compatibility, to ensure Open button to launch Xcode. Click Agree to the
you have the correct version of macOS. Xcode requires macOS licence terms and enter your password to allow Xcode to make
10.12.6 or later to install and work. changes to the system. When that is done, Xcode begins to install
additional components.
STEP 5 With everything now installed, including the STEP 8 The next step asks where to create a Git Repository
additional components, Xcode launches, displaying for all your future code. Choose a location on your
the version number along with three choices and any recent projects Mac, or a network location, and click the Create button. When
that you’ve worked on; with a fresh install though, this is blank. you’ve done all that, you can start to code. The left-hand pane
details the files used in the C++ program you’re coding. Click on the
main.cpp file in the list.
STEP 6 Start by clicking on Create New Xcode Project; this STEP 9 You can see that Xcode has automatically
opens a template window to choose which platform completed a basic Hello World program for you.
you’re developing code for. Click the macOS tab, then click the While it may not make much sense at present, you will discover
Command Line Tool option. Click Next to continue. more as you progress, the content is just Xcode utilising what’s
available on the Mac.
STEP 7 Fill in the various fields but ensure that the STEP 10 When you want to run the code, click on Product >
Language option at the bottom is set to C++; simply Run. You may be asked to enable Developer Mode
choose it from the drop-down list. When you’ve filled in the fields, on the Mac; this is to authorise Xcode to perform functions without
and made sure that C++ is the chosen language, click on the Next needing your password every session. When the program executes,
button to continue. the output is displayed at the bottom of the Xcode window.
www.bdmpublications.com 15
Say Hello to C++
How to Set Up
C++ in Linux
Linux is a great C++ coding environment. Most Linux distros already have the essential
components preinstalled, such as a compiler. The text editors are also excellent for
entering code into, including colour coding. There’s also tons of extra software available
to help you out.
LINUX++
If you’re not familiar with Linux, then we recommend taking a look at one of our Linux titles from the BDM Publications range.
If you have a Raspberry Pi, the commands used below work just fine and for this example we’re using Linux Mint.
STEP 1 The first step is to ensure Linux is ready for your C++ STEP 3 Amazingly, that’s it. Everything is already for you
code, so check the system and software are up to to start coding. Here’s how to get your first C++
date. Open a Terminal and enter: sudo apt-get update && sudo apt- program up and running. In Linux Mint the main text editor is Xed,
get upgrade. Then press Return and enter your password. These which you can launch by clicking on the Menu and typing Xed into
commands update the entire system and any installed software. the search bar. Click on the Text Editor button in the right-hand pane
to open it.
STEP 2 Most Linux distros come preinstalled with all STEP 4 In Xed, or any other text editor you may be using,
the necessary components to start coding in enter the lines of code that make up your C++ Hello
C++; however, it’s always worth checking to see if everything World program. It’s a little different to what the Mac produced:
is present. Still within the Terminal, enter: sudo apt-get
#include <iostream>
install build-essential and press Return. If you have the right
components nothing is installed; if you’re missing some then they int main()
are installed by the command. {
//My first C++ program
std::cout << “Hello World!\n”;
}
STEP 5 When you’ve entered your code, click File > Save As STEP 8 Before you can execute the C++ file you need to
and choose a folder in which to save your program. compile it. In Linux it’s common to use g++, an open
Name the file as helloworld.cpp (it can be any name as long as it has source C++ compiler; as you’re now in the same folder as the C++
.cpp as the extension). Click Save to continue. file, enter: g++ helloworld.cpp in the Terminal and press Return.
STEP 6 The first thing to notice is that Xed has STEP 9 It takes a short time while the code is compiled by
automatically recognised this as a C++ file, since the g++ but providing there are no mistakes or errors in
file extension is now set to .cpp. The colour coding is present in the the code you are returned to the command prompt. The compiling
code and if you open up the file manager you can also see that file’s of the code has created a new file. If you enter: ls into the Terminal
icon has C++ stamped on it. you can see that alongside your C++ file is a.out.
STEP 7 With your code now saved, drop into the Terminal STEP 10 The a.out file is the compiled C++ code. To run
again. You need to navigate to the location of the code enter: ./a.out and press Return. The
the C++ file you’ve just saved. Our example is in the Documents words ‘Hello World!’ appear on the screen. However, a.out isn’t
folder, so we can navigate to it by entering: cd Documents. very friendly. To name it something else post-compiling, you can
Remember, the Linux Terminal is case sensitive, so any capitals recompile with: g++ helloworld.cpp -o helloworld. This creates an
must be entered correctly. output file called helloworld which can be run with: ./helloworld.
www.bdmpublications.com 17
Say Hello to C++
DEVELOPING C++
Here are ten great C++ IDEs that are worth looking into. You can install one or all of them if you like, but find the one that
works best for you.
ECLIPSE Eclipse is a hugely popular C++ IDE that offers CODELITE CodeLite is a free and open source IDE that’s
the programmer a wealth of features. It has a regularly updated and available for Windows,
great, clean interface, is easy to use and available for Windows, Linux and macOS. It’s lightweight, uncomplicated and extremely
Linux and Mac. Head over to www.eclipse.org/downloads/ to powerful. You can find out more information as well as how to
download the latest version. If you’re stuck, click the Need Help link download and install it at www.codelite.org/.
for more information.
GNAT The GNAT Programming Studio (GPS) is a powerful NETBEANS Another popular choice is NetBeans. This
and intuitive IDE that supports testing, debugging is another excellent IDE that’s packed with
and code analysis. The Community Edition is free, whereas the features and a pleasure to use. NetBeans IDE includes project based
Pro version costs; however, the Community Edition is available for templates for C++ that give you the ability to build applications with
Windows, Mac, Linux and even the Raspberry Pi. You can find it at dynamic and static libraries. Find out more at www.netbeans.org/
www.adacore.com/download. features/cpp/index.html.
VISUAL STUDIO Microsoft’s Visual Studio is a ANJUTA The Anjuta DevStudio is a Linux-only IDE that
mammoth C++ IDE that allows you features some of the more advanced features you
to create applications for Windows, Android, iOS and the web. The would normally find in a paid software development studio. There’s
Community version is free to download and install but the other a GUI designer, source editor, app wizard, interactive debugger and
versions allow a free trial period. Go to www.visualstudio.com/ to much more. Go to www.anjuta.org/ for more information.
see what it can do for you.
QT CREATOR This cross-platform IDE is designed to MONODEVELOP This excellent IDE allows developers
create C++ applications for desktop and to write C++ code for desktop and
mobile environments. It comes with a code editor and integrated web applications across all the major platforms. There’s an advanced
tools for testing and debugging, as well as deploying to you chosen text editor, integrated debugger and a configurable workbench to
platform. It’s not free but there is a trial period on offer before help you create your code. It’s available for Windows, Mac and Linux
requiring purchasing: www.qt.io/qt-features-libraries-apis-tools- and is free to download and use: www.monodevelop.com/.
and-ide/.
DEV C++ Bloodshed Dev C++, despite its colourful name, U++ Ultimate++ is a cross-platform C++ IDE that boasts a
is an older IDE that is for Windows systems only. rapid development of code through the smart and
However, many users praise its clean interface and uncomplicated aggressive use of C++. For the novice, it’s a beast of an IDE but behind
way of coding and compiling. Although there’s not been much its complexity is a beauty that would make a developer’s knees go
updating for some time, it’s certainly one to consider if you want wobbly. Find out more at www.ultimatepp.org/index.html.
something different: www.bloodshed.net/devcpp.html.
www.bdmpublications.com 19
C++ Fundamentals
“How did
you know so
much about
computers?”
“I didn’t, it was
the first one.”
– Admiral Grace Hopper
(pioneer programmer)
when interviewed by
David Letterman
www.bdmpublications.com 21
C++ Fundamentals
HELLO, WORLD!
It’s traditional in programming for the first code to be entered to output the words ‘Hello, World!’ to the screen. Interestingly,
this dates back to 1968 using a language called BCPL.
STEP 1 As mentioned, we’re using Windows 10 and the STEP 3 At the moment it doesn’t look like much, and
latest version of Code::Blocks for the rest of the C++ it makes even less sense, but we’ll get to that
code in this book. Begin by launching Code::Blocks. When open, click in due course. Now click on File > Save File As. Create or find a
on File > New > Empty File or press Ctrl+Shift+N on the keyboard. suitable location on your hard drive and in the File Name box, call
it helloworld.cpp. Click the Save as type box and select C/C++ files.
Click the Save button.
STEP 2 Now you can see a blank screen, with the tab STEP 4 You can see that Code::Blocks has now changed
labelled *Untitled1, and the number one in the top the colour coding, recognising that the file is now
left of the main Code::Blocks window. Begin by clicking in the main C++ code. This means that code can be auto-selected from the
window, so the cursor is next to the number one, and entering: Code::Blocks repository. Delete the #include <iostream> line and
re-enter it. You can see the auto-select boxes appearing.
#include <iostream>
STEP 5 Auto-selection of commands is extremely handy and STEP 8 Note again the colour coding change. Press Return at
cuts out potential mistyping. Press Return to get to the end of the previous step’s line, and then enter:
line 3, then enter:
std::cout << “Hello, world!\n”;
int main()
Note: there’s no space between the brackets.
STEP 6 On the next line below int main(), enter a curly bracket: STEP 9 Just as before, Code::Blocks auto-completes the
code you’re entering, including placing a closing
{
speech mark as soon as you enter the first. Don’t forget the
This can be done by pressing Shift and the key to the right of P on an semicolon at the end of the line; this is one of the most important
English UK keyboard layout. elements to a C++ program and we’ll tell you why in the next
section. For now, move the cursor down to the closing curly bracket
and press Return.
STEP 7 Notice that Code::Blocks has automatically created STEP 10 That’s all you need to do for the moment. It may
a corresponding closing curly bracket a couple of not look terribly amazing but C++ is best absorbed
lines below, linking the pair, as well as a slight indent. This is due to in small chunks. Don’t execute the code at the moment as you need
the structure of C++ and it’s where the meat of the code is entered. to look at how a C++ program is structured first; then you can build
Now enter: and run the code. For now, click on Save, the single floppy disc icon.
//My first C++ program
www.bdmpublications.com 23
C++ Fundamentals
Structure of a
C++ Program
C++ has a very defined structure and way of doing things. Miss something out, even
as small as a semicolon, and your entire program will fail to be compiled and executed.
Many a professional programmer has fallen foul of sloppy structure.
C++ #INCLUDE
The structure of a C++ program
C++ was invented by Danish is quite precise. Every C++ code
student Bjarne Stroustrup in begins with a directive: #include
1979, as a part of his Ph.D. <>. The directive instructs the
thesis. Initially C++ was called C pre-processor to include a
with Classes, which added section of the standard C++
features to the already popular code. For example: #include
C programming language, <iostream> includes the
while making it a more iostream header to support
user-friendly environment input/output operations.
through a new structure.
BRACES
The open brace (curly brackets) is something
that you may not have come across before,
especially if you’re used to Python. The
open brace indicates the beginning of the
main function and contains all the code that
belongs to that function.
COMMENTS <<
Lines that begin with a double slash are comments. This means they The two chevrons used here are insertion operators. This means
won’t be executed in the code and are ignored by the compiler. that whatever follows the chevrons is to be inserted into the
Comments are designed to help you, or another programmer std::cout statement. In this case they’re the words ‘Hello, world’,
looking at your code, explain what’s going on. There are two types which are to be displayed on the screen when you compile and
of comment: /* covers multiple line comments, // a single line. Lines execute the code.
that begin with a double slash are comments. This means they won’t
be executed in the code and
are ignored by the compiler.
Comments are designed
to help you, or another
programmer looking at
your code, explain what’s
going on. There are two
types of comment: /* covers
multiple line comments, // a
single line.
STD OUTPUTS
While std stands for something quite different, in C++ it means Leading on, the “Hello, world!” part is what we want to appear on
Standard. It’s part of the Standard Namespace in C++, which covers the screen when the code is executed. You can enter whatever you
a number of different statements and commands. You can leave the like, as long as it’s inside the quotation marks. The brackets aren’t
std:: part out of the code but it must be declared at the start with: needed but some compilers insist on them. The \n part indicates a
using namespace std; not both. For example: new line is to be inserted.
#include <iostream>
using namespace std;
//My first C++ program
cout << “Hello, world!\n”
COUT ; AND }
In this example we’re using cout, which is a part of the Standard Finally you can see that lines within a function code block (except
Namespace, hence why it’s there, as you’re asking C++ to use it from comments) end with a semicolon. This marks the end of the
that particular namespace. Cout means Character OUTput, which statement and all statements in C++ must have one at the end or
displays, or prints, something to the screen. If we leave std:: out we the compiler fails to build the code. The very last line has the closing
have to declare it at the start of the code, as mentioned previously. brace to indicate the end of the main function.
www.bdmpublications.com 25
C++ Fundamentals
STEP 1 Open Code::Blocks, if you haven’t already, and STEP 3 Start by clicking on the Build icon, the yellow cog.
load up the previously saved Hello World code you At this point, your code has now been run through
created. Ensure that there are no visible errors, such as missing the Code::Blocks compiler and checked for any errors. You can see
semicolons at the end of the std::cout line. the results of the Build by looking to the bottom window pane. Any
messages regarding the quality of the code are displayed here.
STEP 2 If your code is looking similar to the one in our STEP 4 Now click on the Run icon, the green play button.
screenshot, then look to the menu bar along the top A command line box appears on your screen
of the screen. Under the Fortran entry in the topmost menu you can displaying the words: Hello, world!, followed by the time it’s taken
see a group of icons: a yellow cog, green play button and a cog/play to execute the code, and asking you press a key to continue. Well
button together. These are Build, Run, Build and Run functions. done, you just compiled and executed your first C++ program.
STEP 5 Pressing any key in the command line box closes it, STEP 8 Create a deliberate error in the code. Remove the
returning you to Code::Blocks. Let’s alter the code semicolon from the cout line, so it reads:
slightly. Under the #include line, enter:
cout << “Hello, world!\n”
using namespace std;
Then, delete the std:: part of the Cout line; like so:
cout << “Hello, world\n”;
STEP 6 In order to apply the new changes to the code, you STEP 9 Now click the Build and Run icon again to apply the
need to re-compile, build, and run it again. This time, changes to the code. This time Code::Blocks refuses
however, you can simply click the Build/Run icon, the combined to execute the code, due to the error you put in. In the Log pane at
yellow cog and green play button. the bottom of the screen you are informed of the error, in this case:
Expected ‘;’ before ‘}’ token, indicating the missing semicolon.
STEP 7 Just as we mentioned in the previous pages, you STEP 10 Replace the semicolon and under the cout line,
don’t need to have std::cout if you already declare enter a new line to your code:
using namespace std; at the beginning of the code. We could have
cout << “And greetings from C++!\n”;
easily clicked the Build/Run icon to begin with but it’s worth going
through the available options. You can also see that by building and The \n simply adds a new line under the last line of outputted text.
running, the file has been saved. Build and Run the code, to display your handiwork.
www.bdmpublications.com 27
C++ Fundamentals
Using Comments
While comments may seem like a minor element to the many lines of code that
combine to make a game, application or even an entire operating system, in actual fact
they’re probably one of the most important factors.
C++ COMMENTS
Commenting in C++ involves using a double forward slash ‘/’, or a forward slash and an asterisk, ‘/*’. You’ve already seen some
brief examples but this is how they work.
STEP 1 Using the Hello World code as an example, you can STEP 4 Be careful when commenting, especially with block
easily comment on different sections of the code comments. It’s very easy to forget to add the closing
using the double forward slash: asterisk and forward slash and thus negate any code that falls inside
the comment block.
//My first C++ program
cout << “Hello, world!\n”;
STEP 2 However, you can also add comments to the end STEP 5 Obviously if you try and build and execute the
of a line of code, to describe in a better way what’s code it errors out, complaining of a missing curly
going on: bracket ‘}’ to finish off the block of code. If you’ve made the
error a few times, then it can be time consuming to go back and
cout << “Hello, world!\n”; //This line outputs the
rectify. Thankfully, the colour coding in Code::Blocks helps identify
words ‘Hello, world!’. The \n denotes a new line.
comments from code.
Note, you don’t have to put a semicolon at the end of a comment.
This is because it’s a line in the code that’s ignored by the compiler.
STEP 3 You can comment out several lines by using the STEP 6 If you’re using block comments, it’s good practise
forward slash and asterisk: in C++ to add an asterisk to each new line of the
comment block. This also helps you to remember to close the
/* This comment can
comment block off before continuing with the code:
cover several lines
without the need to add more slashes */ /* This comment can
* cover several lines
Just remember to finish the block comment with the opposite
* without the need to add more slashes */
asterisk and forward slash.
www.bdmpublications.com 29
C++ Fundamentals
Variables
Variables differ slightly when using C++ as opposed to Python. In Python, you can
simply state that ‘a’ equals 10 and a variable is assigned. However, in C++ a variable has
to be declared with its type before it can be used.
STEP 1 Open up a new, blank C++ file and enter the usual STEP 3 You can build and run the code but it won’t do
code headers: much, other than store the values 10 and 5 to the
integers a and b. To output the contents of the variables, add:
#include <iostream>
using namespace std; cout << a;
cout << ”\n”;
int main()
cout << b;
{
The cout << “\n”; part
}
simply places a new line
between the output of
10 and 5.
STEP 2 Start simple by creating two variables, a and b, with STEP 4 Naturally you can declare a new variable, call it
one having a value of 10 and the other 5. You can result and output some simple arithmetic:
use the data type int to declare these variables. Within the curly
int result;
brackets, enter:
result = a + b;
int a;
cout << result;
int b;
Insert the above into the code as per the screenshot.
a = 10;
b = 5;
STEP 5 You can assign a value to a variable as soon as you STEP 8 The previous step creates the variable StartLives,
declare it. The code you’ve typed in could look like which is a global variable. In a game, for example,
this, instead: a player’s lives go up or down depending on how well or how bad
they’re doing. When the player restarts the game, the StartLives
int a = 10;
returns to its default state: 3. Here we’ve assigned 3 lives, then
int b = 5;
subtracted 1, leaving 2 lives left.
int result = a + b;
cout << result;
STEP 6 Specific to C++, you can also use the following int main()
to assign values to a variable as soon as you
{
declare them:
double area, radius = 1.5;
int a (10);
area = pi * radius * radius;
int b (5);
cout << area;
Then, from the C++ 2011 standard, using curly brackets:
}
int result {a+b};
www.bdmpublications.com 31
C++ Fundamentals
Data Types
Variables, as we’ve seen, store information that the programmer can then later call up,
and manipulate if required. Variables are simply reserved memory locations that store
the values the programmer assigns, depending on the data type used.
Boolean bool
No Value void
These basic types can also be extended using the following modifiers:
Long, Short, Signed and Unsigned. Basically this means the modifiers
can expand the minimum and maximum range values for each data
type. For example, the int data type has a default value range of
-2147483648 to 2147483647, a fair value, you would agree.
Now, if you were to use one of the modifiers, the range alters:
Unsigned int = 0 to 4294967295
Signed int = -2147483648 to 2147483647
Short int = -32768 to 32767
Unsigned Short int = 0 to 65,535 Build and run the code and as you can see the output is only
Signed Short int = -32768 to 32767 3.14159, representing cout’s limitations in this example.
Long int = -2147483647 to 2147483647
You can alter the code including the aforementioned cout.precision
Signed Long int = -2147483647 to 2147483647
function, for greater accuracy. Take precision all the way up to 22
Unsigned Long int = 0 to 4294967295
decimal places, with the following code:
Naturally you can get away with using the basic type without the
#include <iostream>
modifier, as there’s plenty of range provided with each data type.
using namespace std;
However, it’s considered good C++ programming practise to use the
double PI = 3.141592653589793238463;
modifiers when possible.
int main()
There are issues when using the modifiers though. Double
{
represents a double-floating point value, which you can use for
cout.precision(22); This is mainly due to the conversion from binary in the compiler
cout << PI; and that the IEEE 754 double precision standard occupies 64-bits
of data, of which 52-bits are dedicated to the significant (the
}
significant digits in a floating-point number) and roughly 3.5-bits
are taken holding the values 0 to 9. If you divide 53 by 3.5, then you
arrive at 15.142857 recurring, which is 15-digits of precision.
To be honest, if you’re creating code that needs to be accurate to
more than fifteen decimal places, then you wouldn’t be using C++,
you would use some scientific specific language with C++ as the
connective tissue between the two languages.
You can create your own data types, using an alias-like system called
typedef. For example:
Again, build and run the code; as you can see from the command
line window, the number represented by the variable PI is different
to the number you’ve told C++ to use in the variable. The output
reads the value of PI as 3.141592653589793115998, with the
numbers going awry from the fifteenth decimal place.
#include <iostream>
using namespace std;
typedef int metres;
int main()
{
metres distance;
distance = 15;
cout << “distance in metres is: “ << distance;
}
This code when executed creates a new int data type called metres.
Then, in the main code block, there’s a new variable called distance,
which is an integer; so you’re basically telling the compiler that
there’s another name for int. We assigned the value 15 to distance
and displayed the output: distance in metres is 15.
It might sound a little confusing to begin with but the more you use
C++ and create your own code, the easier it becomes.
www.bdmpublications.com 33
C++ Fundamentals
Strings
Strings are objects that represent and hold sequences of characters. For example, you
could have a universal greeting in your code ‘Welcome’ and assign that as a string to be
called up wherever you like in the program.
STRING THEORY
There are different ways in which you can create a string of characters, which historically are all carried over from the original
C language, and are still supported by C++.
STEP 1 To create a string you use the char function. Open a STEP 3 Build and run the code, and ‘Welcome’ appears
new C++ file and begin with the usual header: on the screen. While this is perfectly fine, it’s
not a string. A string is a class, which defines objects that can be
#include <iostream>
represented as a stream of characters and doesn’t need to be
using namespace std;
terminated like an array. The code can therefore be represented as:
int main ()
#include <iostream>
{ using namespace std;
} int main ()
{
char greet[] = “Welcome”;
cout << greet << “\n”;
}
STEP 2 It’s easy to confuse a string with an array. Here’s an STEP 4 In C++ there’s also a string function, which works in
array, which can be terminated with a null character: much the same way. Using the greeting code again,
you can enter:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main ()
int main ()
{
char greet[8] = {‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, {
‘e’, ‘\0’}; string greet = “Welcome”;
cout << greet << “\n”; cout << greet << “\n”;
} }
STEP 5 There are also many different operations that you STEP 8 Just as you might expect, you can mix in an integer
can apply with the string function. For instance, to and store something to do with the string. In this
get the length of a string you can use: example, we created int length, which stores the result of string.
size() and outputs it to the user:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main ()
int main ()
{
string greet = “Welcome”; {
cout << “The length of the string is: “; int length;
cout << greet.size() << “\n”; string greet1 = “Hello”;
string greet2 = “, world!”;
}
string greet3 = greet1 + greet2;
length = greet3.size();
cout << “The length of the combined strings
is: “ << length << “\n”;
}
www.bdmpublications.com 35
C++ Fundamentals
C++ Maths
Programming is mathematical in nature and as you might expect, there’s plenty of
built-in scope for some quite intense maths. C++ has a lot to offer someone who’s
implementing mathematical models into their code. It can be extremely complex or
relatively simple.
C++ = MC2
The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the C++
Math Library, you can also calculate square roots, powers, trig and more.
STEP 1 C++’s mathematical operations follow the STEP 3 Multiplication and division can be applied as such:
same patterns as those taught in school, in that
#include <iostream>
multiplication and division take precedence over addition and
using namespace std;
subtraction. You can alter that though. For now, create a new file
and enter: int main ()
{
#include <iostream>
float numbers = 100;
using namespace std;
numbers = numbers * 10; // This multiplies 100
int main ()
by 10
{
float numbers = 100; cout << numbers << “\n”;
numbers = numbers + 10; // This adds 10 to the numbers = numbers / 10; // And this divides
initial 100 1000 by 10
cout << numbers << “\n”; cout << numbers << “\n”;
numbers = numbers - 10; // This subtracts 10 }
from the new 110
cout << numbers << “\n”;
}
STEP 5 The interesting maths content comes when you call STEP 8 Calculating powers of numbers can be done with:
upon the C++ Math Library. Within this header are
dozens of mathematical functions along with further operations. #include <iostream>
Everything from computing cosine to arc tangent with two #include <cmath>
parameters, to the value of PI. You can call the header with: using namespace std;
#include <iostream> int main ()
#include <cmath> {
using namespace std; float number = 12;
int main () cout << number << “ to the power of 2 is “ <<
{ pow(number, 2) << “\n”;
cout << number << “ to the power of 3 is “ <<
}
pow(number, 3) << “\n”;
cout << number << “ to the power of .08 is “
<< pow(number, 0.8) << “\n”;
}
STEP 6 Start by getting the square root of a number: STEP 9 Here we created a float called number with the
value of 12, and the pow(variable, power) is where
the calculation happens. Of course, you can calculate powers and
#include <iostream>
square roots without using variables. For example, pow (12, 2)
#include <cmath>
outputs the same value as the first cout line in the code.
using namespace std;
int main ()
{
float number = 134;
cout << “The square root of “ << number << “
is: “ << sqrt(number) << “\n”;
}
www.bdmpublications.com 37
C++ Input/Output
“Measuring
programming
progress by lines
of code is like
measuring aircraft
building progress
by weight.”
– Bill Gates
(Co-founder of Microsoft)
www.bdmpublications.com 39
C++ Input/Output
User Interaction
There’s nothing quite as satisfying as creating a program that responds to you. This
basic user interaction is one of the most taught aspects of any language and with it
you’re able to do much more than simply greet the user by name.
HELLO, DAVE
You have already used cout, the standard output stream, throughout our code. Now you’re going to be using cin, the standard
input stream, to prompt a user response.
STEP 1 Anything that you want the user to input into the STEP 3 The cin command works in the opposite way from
program needs to be stored somewhere in the the cout command. With the first cout line you’re
system memory, so it can be retrieved and used. Therefore, any outputting ‘What is your age’ to the screen, as indicated with the
input must first be declared as a variable, so it’s ready to be used by chevrons. Cin uses opposite facing chevrons, indicating an input. The
the user. Start by creating a blank C++ file with headers. input is put into the integer age and called up in the second cout
command. Build and run the code.
STEP 5 The principal works the same as the previous code. STEP 8 While cin works well for most input tasks, it does
The user’s input, their name, is stored in a string, have a limitation. Cin always considers spaces as a
because it contains multiple characters, and retrieved in the second terminator, so it’s designed for just single words not multiple words.
cout line. As long as the variable ‘name’ doesn’t change, then you However, getline takes cin as the first argument and the variable as
can recall it wherever you like in your code. the second:
#include <iostream>
using namespace std;
int main ()
{
string mystr;
cout << “Enter a sentence: \n”;
STEP 6 You can chain input requests to the user but just
getline(cin, mystr);
make sure you have a valid variable to store the
input to begin with. Let’s assume you want the user to enter two cout << “Your sentence is: “ << mystr.size() <<
whole numbers: “ characters long.\n”;
#include <iostream> }
using namespace std;
int main ()
{
int num1, num2;
cout << “Enter two whole numbers: “;
cin >> num1 >> num2;
cout << “you entered “ << num1 << “ and “ <<
num2 << “\n”; STEP 9 Build and execute the code, then enter a sentence
with spaces. When you’re done the code reads the
}
number of characters. If you remove the getline line and replace it
with cin >> mystr and try again, the result displays the number of
characters up to the first space.
www.bdmpublications.com 41
C++ Input/Output
Character Literals
In C++ a literal is an object or variable that once defined remains the same throughout
the code. However, a character literal is defined by a backslash, such as the \n you’ve
been using at the end of a cout statement to signify a new line.
ESCAPE SEQUENCE
When used in something like a cout statement, character literals are also called escape sequence codes. They allow you to
insert a quote, an alert, new line and much more.
STEP 1 Create a new C++ file and enter the relevant headers: STEP 3 If you wanted to insert speech quotes inside a cout
statement, you would have to use a backslash as it
#include <iostream> already uses quotes:
using namespace std;
#include <iostream>
int main () using namespace std;
{
int main ()
{
} cout << “Hello, user. This is how to use
\”quotes\”.”;
}
STEP 2 You’ve already experienced the \n character literal STEP 4 There’s even a character literal that can trigger an
placing a new line wherever it’s called. The line: cout alarm. In Windows 10, it’s the notification sound
<< “Hello\n” << “I’m a C++\n” << “Program\n”; outputs three lines that chimes when you use \a. Try this code, and turn up your sound.
of text, each starting after the last \n.
#include <iostream>
using namespace std;
int main ()
{
cout << “ALARM! \a”;
}
A HANDY CHART
There are numerous character literals, or escape sequence codes, to choose from. We therefore thought it would be good for
you to have a handy chart available, for those times when you need to insert a code.
\’ Single Quote
\? Question Mark
\a Alert/Alarm
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
\0 Null Character
UNICODE
CHARACTER TABLE
A complete list of the available Unicode
characters can be found at www.unicode-
table.com/en/. Hover your mouse over the
character to see the unique code to enter in
C++. While it may be a little overwhelming
to look at to begin with, bookmark the page
as you will probably need to come back to
it for reference as you dig deeper into C++,
and indeed character literals. One more
thing, the table will also display characters
from different languages, such as Tibetan
or Sudanese. This means your code can be
truly universal.
www.bdmpublications.com 43
C++ Input/Output
Defining Constants
Constants are fixed values in your code. They can be any basic data type but as the
name suggests their value remains constant throughout the entire code. There are two
separate ways to define a constant in C++, the #define pre-processor and const.
#DEFINE
The pre-processors are instructions to the compiler to pre-process the information before it goes ahead and compiles the
code. #include is a pre-processor as is #define.
STEP 1 You can use the #define pre-processor to define any STEP 3 Note the capitals for defined constants, it’s
constants you want in our code. Start by creating a considered good programming practise to define all
new C++ file complete with the usual headers: constants in capitals. Here, the assigned values are 50, 40 and 60, so
let’s call them up:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main ()
#define LENGTH 50
{
#define WIDTH 40
} #define HEIGHT 60
int main ()
{
cout << “Length is: “ << LENGTH << “\n”;
cout << “Width is: “ << WIDTH << “\n”;
cout << “Height is: “ << HEIGHT << “\n”;
}
STEP 5 You can also define other elements as a constant. STEP 8 Another method of defining a constant is with the
For example, instead of using \n for a newline in the const keyword. Use const together with a data type,
cout statement, you can define it at the start of the code: variable and value: const type variable = value. Using Pi as an example:
#include <iostream> #include <iostream>
using namespace std; using namespace std;
#define LENGTH 50 int main ()
#define WIDTH 40
{
#define HEIGHT 60
const double PI = 3.14159;
#define NEWLINE ‘\n’
cout << “The value of Pi is: “ << PI << endl;
int main () }
{
cout << “Length is: “ << LENGTH << NEWLINE;
cout << “Width is: “ << WIDTH << NEWLINE;
cout << “Height is: “ << HEIGHT << NEWLINE;
}
www.bdmpublications.com 45
C++ Input/Output
File Input/Output
The standard iostream library provides C++ coders with the cin and cout input and
output functionality. However, to be able to read and write from a file you need to
utilise another C++ library, called fstream.
FSTREAMS
There are two main data types within the fstream library that are used to open a file, read from it and write to it, ofstream and
ifstream. Here’s how they work.
STEP 1 The first task is to create a new C++ file and along STEP 3 We’ve included comments in the screenshot of step
with the usual headers you need to include the new 2 to help you understand the process. You created
fstream header: a string called name, to store the user’s inputted name. You also
created a text file called name.txt (with the ofstream newfile and
#include <iostream>
newfile.open lines), asked the user for their name and stored it and
#include <fstream>
then written the data to the file.
Using namespace std;
int main ()
{
STEP 2 Begin by asking a user for their name and writing string line;
that information to a file. You need the usual string ifstream newfile (“name.txt”);
to store the name, and getline to accept the input from the user.
cout << “Contents of the file: “ << endl;
#include <iostream>
getline(newfile, line);
#include <fstream>
cout << line << endl;
using namespace std;
newfile.close();
int main ()
{
string name;
ofstream newfile;
newfile.open(“name.txt”);
cout << “Enter your name: “ << endl;
getline(cin, name);
newfile << name << endl;
newfile.close();
}
STEP 5 The code above is great for opening a file with one STEP 8 Just as you might expect, you can write almost
or two lines but what if there are multiple lines? Here anything you like to a file, for reading either in
we opened a text file of the poem Cimmeria, by Robert E Howard: Notepad or via the console through the C++ code:
string line; string name;
ifstream newfile (“c:\\users\\david\\ int age;
Documents\\Cimmeria.txt”);
ofstream newfile;
cout << “Cimmeria, by Robert E Howard: \n” << newfile.open(“name.txt”);
endl;
cout << “Enter your name: “ << endl;
while (getline(newfile, line)) getline(cin, name);
cout << line << endl;
newfile << name << endl;
newfile.close();
cout << “\nHow old are you: “ << endl;
cin >> age;
newfile << age << endl;
newfile.close();
STEP 7 You can also see that the location of the text file STEP 10 Here’s an exercise: see if you can create code to
Cimmeria.txt isn’t in the same folder as the C++ write several different elements to a text file. You
program. When we created the first name.txt file, it was written to can have a user’s name, age, phone number etc. Maybe even the
the same folder where the code was located; this is done by default. value of Pi and various mathematical elements. It’s all good practice.
To specify another folder, you need to use double-back slashes, as
per the character literals/escape sequence code.
www.bdmpublications.com 47
Loops and Decision Making
www.bdmpublications.com 49
Loops and Decision Making
While Loop
A while loop’s function is to repeat a statement, or a group of statements, while a certain
condition remains true. When the while loop starts, it initialises itself by testing the
condition of the loop and the statements within, before executing the rest of the loop.
TRUE OR FALSE?
While loops are one of the most popular form of C++ code looping. They repeatedly run the code contained within the loop
while the condition is true. Once it proves false, the code continues as normal.
STEP 1 Clear what you’ve done so far and create a new C++ STEP 3 First you
file. There’s no need for any extra headers at the need to
moment, so add the standard headers as per usual: create a condition, so use a
variable called num and give
#include <iostream>
it the value 1. Now create
using namespace std;
the while loop, stating that
int main () as long as num is less than
30, the loop is true. Within
{
the loop the value of num
} is displayed and adds 1 until
it’s more than 30.
STEP 6 It’s important to remember not to add a semicolon STEP 9 You can further expand the code to enable each
at the end of a while statement. Why? Well, as you word of the poem to appear every second. To do
know, the semicolon represents the end of a C++ line of code. If so, you need to pull in a new library, <windows.h>. This is a Windows
you place one at the end of a while statement, your loop will be only library and within it you can use the Sleep() function:
permanently stuck until you close the program.
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
int main ()
{
string word;
ifstream newfile (“C:\\users\\david\\
Documents\\Cimmeria.txt”);
cout << “Cimmeria, by Robert E Howard: \n” <<
endl;
while (newfile >> word)
STEP 7 In our example, if we were to execute the code {
the value of num would be 1, as set by the int cout << word << endl;
statement. When the code hits the while statement it reads Sleep(1000);
that while the condition of 1 being less than 30 is true, loop. The }
semicolon closes the line, so the loop repeats; but it never adds 1 to
return 0;
num, as it won’t continue through the compound statement.
}
STEP 8 You can manipulate the while statement to display STEP 10 Sleep() works in milliseconds, so Sleep(1000) is
different results depending on what code lies within one second, Sleep(10000) is ten seconds and so
the loop. For example, to read the poem, Cimmeria, word by word, on. Combining the sleep function (along with the header it needs)
you would enter: and a while loop enables you to come up with some interesting
countdown code.
#include <iostream>
#include <fstream> #include <iostream>
using namespace std; #include <windows.h>
using namespace std;
int main ()
int main ()
{
string word; {
ifstream newfile (“C:\\users\\david\\ int a = 10;
Documents\\Cimmeria.txt”);
while (a != 0)
cout << “Cimmeria, by Robert E Howard: \n” << {
endl; cout << a << endl;
a = a - 1;
while (newfile >> word)
Sleep(1000);
{
}
cout << word << endl;
} cout << “\nBlast Off!” << endl;
return 0; return 0;
} }
www.bdmpublications.com 51
Loops and Decision Making
For Loop
In some respects, a for loop works in a very similar way to that of a while loop, although it’s
structure is different. A for loop is split into three stages: an initialiser, a condition and an
incremental step. Once set up, the loop repeats itself until the condition becomes false.
LOOPY LOOPS
The initialise stage of a for loop is executed only once and this sets the point reference for the loop. The condition is evaluated
by the loop to see if it’s true or false and then the increment is executed. The loop then repeats the second and third stage.
STEP 1 Create a new C++ file, with the standard headers: STEP 4 After the loop, you created a compound statement
in braces (curly brackets), that displays the current
#include <iostream> value of the integer num. Every time the for loop repeats itself, the
using namespace std; second and third stages of the loop, it adds 1 until the condition <30
is false. The loop then ends and the code continues, ending neatly
int main ()
with return 0.
{
STEP 2 Start simple and create a for loop that counts from
1 to 30, displaying the value to the screen with
each increment:
STEP 5 A for loop is quite a neat package in C++, all
{ contained within its own brackets, while the other
//For Loop Begins elements outside of the loop are displayed below. If you want to
for( int num = 1; num < 30; num = num +1 ) create a 10-second countdown, you could use:
{
#include <iostream>
cout << “Number: “ << num << endl;
#include <windows.h>
}
using namespace std;
return 0;
int main ()
}
{
//For Loop Begins
STEP 3 Working through the process of the for loop, begin for( int a = 10; a != 0; a = a -1 )
by creating an integer called num and assigning it a {
value of 1. Next, set the condition, in this case num being less than cout << a << endl;
30. The last stage is where you create the increments; here it’s the Sleep(1000);
value of num being added by 1. }
cout << “\nBlast Off!” << endl;
return 0;
}
STEP 6 With the countdown code, don’t forget to include STEP 9 Here’s an example of a for loop displaying the
the windows.h library, so you can use the Sleep multiplication tables of a user inputted number.
command. Build and run the code; in the command console you can Handy for students:
see the numbers 10 to 1 countdown in one second increments, until
{
it reaches zero and Blast Off! appears.
int n;
cout << “Enter a number to view its times
table: “;
cin >> n;
for (int i = 1; i <= 12; ++i) {
cout << n << “ x “ << i << “ = “ << n * i
<< endl;
}
return 0;
}
STEP 8 The code from step 7, when built and run, asks for a
number, then displays the factorial of that number
through the for loop. The user’s number is stored in the integer
n, followed by the integer I which is used to check if the condition
is true or false, adding 1 each time and comparing it to the user’s
number, n.
www.bdmpublications.com 53
Loops and Decision Making
DO LOOPS
The good thing about a do… while loop is that it’s guaranteed to run through at least once. It’s structure is: do, followed by
statements, while condition is true. This is how it works.
STEP 1 Begin with a new, blank C++ file and enter the STEP 3 Now, here’s a look at the structure of a do… while
standard headers: loop. First you create an integer called num, with
the value of 1. Now the do… while loops begins. The code inside
#include <iostream>
the body of the loop is executed at least once, then the condition is
using namespace std;
checked for either true or false.
int main ()
{
{
STEP 4 If the condition is true, the loop is executed. This
int num = 1;
continues until the condition is false. When the
do condition has been expressed as false, the loop terminates and the
{ code continues. This means you can create a loop where the code
cout << “Number: “ << num << endl; continues until the user enters a certain character.
num = num + 1;
}
while (num < 30 );
return 0;
}
STEP 5 If you want code to add up user inputted numbers STEP 8 Finally, the while statement checks the condition
until the user enters zero: of the variable number. If the user has entered
zero, then the loop is terminated, if not then it continues
{
indefinitely. When the user finally enters zero, the value of sum,
float number, sum = 0.0;
the total value of all the user’s input, is displayed. The loop, and
cout << “**** Program to execute a Do...
the program, then ends.
While loop continuously ****” << endl;
cout << “\nEnter 0 to stop and display the
sum of all the numbers entered\n” << endl;
cout << “\n---------------------------------
---\n” << endl;
do {
cout<<”\nPlease enter a number: “;
cin>>number;
sum += number;
}
while(number != 0.0);
STEP 9 Using the countdown and Blast Off! code used
cout<<”Total sum of all numbers: “<<sum; previously, a do… while loop would look like:
return 0; {
int a = 10;
}
do
{
cout << a << endl;
a = a - 1;
}
while ( a != 0);
www.bdmpublications.com 55
Loops and Decision Making
If Statement
The decision making statement ‘if’ is probably one of the most used statements in any
programming language, regardless of whether it’s C++, Python, BASIC or anything
else. It represents a junction in the code, where IF one condition is true, do this; or IF it’s
false, do that.
IF ONLY
If uses a Boolean expression within its statement. If the Boolean expression is true, the code within the statement is executed.
If not, then the code after the statement is executed instead.
STEP 1 First, create a new C++ file and enter the relevant
standard headers, as usual:
#include <iostream>
using namespace std;
int main ()
{
STEP 2 If is best explained when you use a number- STEP 3 What’s going on here? To begin, an integer called
based condition: num was created and assigned with the value of 1.
The if statement comes next, and in this case we’ve instructed the
{
code that if the condition, the value, of num is less than 1, then the
int num = 1;
code within the braces should be executed.
if ( num < 30 )
{
cout << “The number is less than 30.” <<
endl;
}
cout << “Value of number is: “ << num << endl;
STEP 4 The second cout statement displays the current
return 0; value of num and the program terminates safely. It’s
easy to see how the if statement works if you were to change the
}
initial value of num from 1 to 31.
STEP 5 When you change the value to anything above STEP 7 The code in Step 6 is simplistic but effective. First we
30, then build and run the code, you can see that created a floating point integer called temp, then a
the only line to be outputted to the screen is the second cout do… while loop that asks the user to enter the current temperature.
statement, displaying the current value of num. This is because the
initial if statement is false, so it ignores the code within the braces.
www.bdmpublications.com 57
Loops and Decision Making
IF YES, ELSE NO
There are two sections of code that can be executed depending on the outcome in an if… else statement. It’s quite easy to
visualise once you get used to its structure.
STEP 1 Begin with a new C++ file and the standard headers: STEP 3 The first line in the code creates the integer called
num and gives it a value of 1. The if statement
#include <iostream> checks to see if the value of num is less than thirty and if it is it
using namespace std; outputs “The number is less than 30!” to the console.
int main ()
{
}
STEP 6 The code works the same way, as you would expect, STEP 8 You can take this up a notch and create a two-player
but what if you wanted to display something if the number guessing game. Begin by creating the variables:
user entered the number 30? Try this:
int num, guess, tries = 0;
{
int num; cout << “***** Two-player number guessing game
****” << endl;
cout << “Enter a number: “;
cout << “\nPlayer One, enter a number for
cin >> num;
Player Two to guess: “ << endl;
if ( num < 30 ) cin >> num;
{ cout << string(50, ‘\n’);
cout << “The number is less than 30!” <<
endl;
STEP 9 The cout << string(50, ‘\n’) line clears the screen so
}
Player Two doesn’t see the entered number. Now
else if ( num > 30 )
you can create a do… while loop, together with if… else:
{
cout << “The number is greater than 30!” do
<< endl; {
} cout << “\nPlayer Two, enter your guess: “;
else if ( num == 30 ) cin >> guess;
{ tries++;
cout << “The number is exactly 30!” << if (guess > num)
endl; {
} cout << “\nToo High!\n” << endl;
}
return 0;
else if (guess < num)
} {
cout << “\nToo Low!\n” << endl;
}
else if (guess == num)
{
cout << “Well done! You got it in “ <<
tries << “ guesses!” << endl;
}
} while (guess != num);
return 0;
www.bdmpublications.com 59
Loops and Decision Making
STEP 1 Let’s begin with a blank page. Enter the usual pre- STEP 2 Next up, we’re going to create a couple of data
processor, #include <iostream>, but also add a new strings that will contain ASCII images that we can use
one: #include <unistd.h> this is a pre-processor that provides access in the code. You can of course create your own, if you’re artistically
to the POSIX operating system API. In our case, we’re going to use it inclined, however, if you’re not, then take to Google and search for
to access a command called Usleep, as we’ll see later. ‘ASCII rocket art’. Define two strings, background and rocket.
STEP 4 When you’ve sorted the ASCII art out, remove the
cout statements and enter the following:
string greet = “Are you ready to explore the stars?”;
int x=0;
cout << background;
cout << “\n”;
while (greet[x] !=’\0’)
{
cout << greet[x];
usleep(95000);
x++;
}
string name;
cout << “\n” << “\n” << “What is your name,
brave astronaut? “;
cin >> name;
cout << flush;
cout << “Press Enter for take off, “ << name
<< “.\n”;
cin.ignore();
cin.get();
www.bdmpublications.com 61
Loops and Decision Making
STEP 7 The previous code displays and animates the rocket STEP 8 Compile the code, ensuring that all brackets are
ASCII art. It uses a for loop to add an extra line closed off and there’s a semicolon at the end of
under the rocket at increasing steps; using the Usleep function to the appropriate lines. When you run through, you will be asked for
lessen the amount of time between each new line, thus giving the your name, press Enter to clear the screen and watch the rocket
appearance of the rocket speeding up into space. Finally, there’s a animation (cheating animation, but animation all the same) take off,
message to the user at the end of the code. with a final ‘Boldly go, NAME’ message at the end.
Game engines, together with C++ code, can be used to create The Unreal Engine helps you develop rich environments and
anything from a top-selling game, to something personal. allows you to add C++ code behind the scenes.
www.bdmpublications.com 63
Code Repository
64 BDM’s Definitive
DefinitiveGuide
GuideSeries
www.bdmpublications.comSeries- -Volume
Volume34
34
Code
Repository
It’s one thing to learn to code, but something
else entirely to view a working program and be
able to customise it for your own needs. With
that in mind, we’ve got some great Python code
examples available for you to try out and use.
There’s code for a Python file manager, number
guessing game, random password generator and
even a game of Hangman. Use the code, tear it
apart and improve it, it’s free for you to play with.
www.bdmpublications.com
www.bdmpublications.com 65
Code Repository
def Read():
path=input(“Enter the file path to read:”)
file=open(path,”r”)
print(file.read()) 2
input(‘Press Enter...’)
file.close()
def Write():
path=input(“Enter the path of file to write or create:”)
if os.path.isfile(path):
print(‘Rebuilding the existing file’)
else:
print(‘Creating the new file’)
text=input(“Enter text:”)
file=open(path,”w”)
file.write(text)
def Add():
path=input(“Enter the file path:”)
text=input(“Enter the text to add:”)
file=open(path,”a”)
file.write(‘\n’+text)
def Delete():
This part of the code imports the necessary modules. path=input(“Enter the path of file for deletion:”)
1 The OS and Subprocess modules deal with the if os.path.exists(path):
print(‘File Found’)
operating system elements of the program.
os.remove(path)
print(‘File has been deleted’)
Each def XXX() functions store the code for each else:
2 of the menu’s options. Once the code within the print(‘File Does not exist’)
function is complete, the code returns to the main
menu for another option. def Dirlist():
path=input(“Enter the Directory path to display:”)
This is part of the code that checks to see what OS sortlist=sorted(os.listdir(path))
3 the user is running. In Windows the CLS command i=0
clears the screen, whereas in Linux and macOS, the while(i<len(sortlist)):
print(sortlist[i]+’\n’)
Clear command wipes the screen. If the code tries
i+=1
to run CLS when being used in Linux or macOS, an
error occurs, which then prompts it to run the Clear def Check():
command instead. fp=int(input(‘Check existence of \n1.File \n2.
Directory\n’))
These are the options, from 1 to 12. Each executes if fp==1:
4 the appropriate function when the relevant number path=input(“Enter the file path:”)
is entered. os.path.isfile(path)
66 BDM’s Definitive
DefinitiveGuide
GuideSeries
www.bdmpublications.comSeries- -Volume
Volume34
34
Python File Manager
def Openfile():
path=input(‘Enter the path of program:’)
try:
os.startfile(path)
except:
print(‘File not found’)
run=1 Imports
while(run= =1): There are three modules to import here: Shutil, OS and
try: Time. The first two deal with the operating system and file
os.system(‘clear’)
except OSError: 3 management and manipulation; and the Time module simply
displays the current time and date.
os.system(‘cls’)
print(‘\n>>>>>>>>>>Python 3 File Manager<<<<<<<<<<\n’)
print(‘The current time and date is:’,time.asctime()) Note how we’ve included a try and except block to check if
print(‘\nChoose the option number: \n’) the user is running the code on a Linux system or Windows.
dec=int(input(‘’’1.Read a file Windows uses CLS to clear the screen, while Linux uses clear.
2.Write to a file The try block should work well enough but it’s a point of
3.Append text to a file possible improvement depending on your own system.
4.Delete a file
www.bdmpublications.com
www.bdmpublications.com 67
Code Repository
68 BDM’s Definitive
DefinitiveGuide
GuideSeries
www.bdmpublications.comSeries- -Volume
Volume34
34
Number Guessing Game
Code Improvements
Since this is such as simple script to apply to a situation, there’s For example, as per the screenshot provided, you could use
plenty of room to mess around with it and make it more something along the lines of:
interesting. Perhaps you can include an option to take score, the
best out of three rounds. Maybe an elaborate way to congratulate Endurance=0
the player for getting a ‘hole in one’ correct guess on their first try. CR=0
Luck=0
Moreover, the number guessing game code does offer some room Endurance = random.randint(1, 15)
CR = random.randint(1, 20)
for implementing into your code in a different manner. What we
Luck = random.randint(1, 10)
mean by this is, the code can be used to retrieve a random number Print(“Your character’s stats are as follows:\n”)
between a range, which in turn can give you the start of a character Print(“Endurance:”, Endurance)
creation defined function within an adventure game. Print(“Combat Rating:”, CR)
Print(“Luck:”, Luck)
Imagine the start of a text adventure written in Python, where
the player names their character. The next step is to roll the
The player can then decide to either stick with their roll or try again
virtual random dice to decide what that character’s combat
for the hope of better values being picked. There’s ample ways in
rating, strength, endurance and luck values are. These can then be
which to implement this code into a basic adventure game.
carried forward into the game under a set of variables that can be
reduced or increased depending on the circumstances the player’s
character ends up in.
www.bdmpublications.com
www.bdmpublications.com 69
Code Repository
More Input
While an easy code to follow, it could be more interesting if you For example, the code could be edited to this:
prompt the user for more input. Perhaps you can provide them
with addition, subtraction, multiplication elements with their from random import *
numbers. If you’re feeling clever, see if you can pass the code import turtle
through some Tkinter GUI code, so it’s presented in a window
rather in the console. print(“\n>>>>>>>>>>Random Turtle Image<<<<<<<<<<\n”)
nmb1=int(input(“Enter the start number: “))
nmb2=int(input(“Enter the second number: “))
Furthermore, the core of the code can be used in a text adventure nmb3=int(input(“Enter the third number: “))
game, where the character fights something and their health, nmb4=int(input(“Enter the fourth number: “))
along with the enemy’s, is reduced by a random number. This
can be mixed with the previous code from Page 154’s Number
Guessing Game, where we defined the stats for the adventure turtle.forward(nmb1)
game’s character. turtle.left(90)
turtle.forward(nmb2)
You can also introduce the Turtle module into the code and turtle.left(90)
perhaps set some defined rules for drawing a shape, object or turtle.forward(nmb3)
turtle.left(90)
something based on a user inputted random value from a range
turtle.forward(nmb4)
of numbers. It takes a little working out but the effect is certainly turtle.left(90)
really interesting.
Whilst it’s a little rough around the edges, you can easily make it
more suitable.
70 BDM’s Definitive
DefinitiveGuide
GuideSeries
www.bdmpublications.comSeries- -Volume
Volume34
34
Random Number Generator/Password Generator
Random Password
Generator
We’re always being told that our RNDPASSWORD.PY
passwords aren’t secure enough; Copy the code and run it; each time you’ll get a random string
well here’s a solution for you to of characters that can easily be used as a secure password
which will be incredibly difficult for a password cracker to hack.
implement into your own future
import string
programs. The random password import random
generator code below will create a
def randompassword():
12-letter string of words (both cases) chars=string.ascii _ uppercase + string.ascii _
lowercase + string.digits
and numbers each time it’s executed. size= 8
return ‘’.join(random.choice(chars) for x in
range(size,20))
print(randompassword())
Secure Passwords
There’s plenty you can do to modify this code and improve it Adding a loop to print a password fifty times is extremely easy,
further. For one, you can increase the number of characters the for example:
generated password displays and perhaps you can include special
characters too, such as signs and symbols. Then, you can output import string
the chosen password to a file, then securely compress it using the import random
previous random number generator as a file password and send it
to a user for their new password.
def randompassword():
chars=string.ascii _ uppercase + string.ascii _
An interesting aspect to this code is the ability to introduce a loop lowercase + string.digits
and print any number of random passwords. Let’s assume you have size= 4
a list of 50 users for a company and you’re in charge of generating return ‘’.join(random.choice(chars) for x in
a random password for them each month. range(size,20))
n=0
while n<50:
print(randompassword())
n=n+1
www.bdmpublications.com
www.bdmpublications.com 71
Code Repository
def start():
print(“\n ----------”)
print(“Do you approach the...”)
print(“\n”)
print(“1. Ragged looking man”)
print(“2. Dangerous looking guards”)
cmdlist=[“1”, “2”]
cmd=getcmd(cmdlist)
72 BDM’s Definitive
DefinitiveGuide
GuideSeries
www.bdmpublications.comSeries- -Volume
Volume34
34
Text Adventure Script
if cmd == “1”:
ragged() def getcmd(cmdlist):
elif cmd == “2”: cmd = input(name+”>”)
guards() if cmd in cmdlist:
return cmd
def ragged(): elif cmd == “help”:
print(“\n” * 200) print(“\nEnter your choices as detailed in
print(‘’’You walk up to the ragged looking man and the game.”)
greet him. print(“or enter ‘quit’ to leave the game”)
He smiles a toothless grin and, with a strange return getcmd(cmdlist)
accent, says. elif cmd == “quit”:
“Buy me a cup of wine, and I’ll tell you of print(“\n-----------”)
great treasure...’’’) time.sleep(1)
time.sleep(2) print(“Sadly you return to your homeland without
fame or fortune...”)
def guards(): time.sleep(5)
print(“\n” *200) exit()
print(‘’’You walk up to the dangerous looking guards
and greet them.
The guards look up from their drinks and if _ _ name _ _ =
=” _ _ main _ _ ”:
snarl at you. start()
“What do you want, barbarian?” One guard reaches
for the hilt of his sword...’’’)
time.sleep(2)
Adventure Time
This, as you can see, is just the beginning of the adventure and
takes up a fair few lines of code. When you expand it, and weave
the story along, you’ll find that you can repeat certain instances
such as a chance meeting with an enemy or the like.
www.bdmpublications.com
www.bdmpublications.com 73
Code Repository
+---+
| |
O |
|
|
|
= = = = = = = = = ’’’, ‘’’
+---+
| |
O |
| |
|
|
= = = = = = = = = ’’’, ‘’’
+---+
| |
O |
/| |
|
|
= = = = = = = = = ’’’, ‘’’
+---+
| |
O |
/|\ |
|
|
= = = = = = = = = ’’’, ‘’’
+---+
| |
O |
/|\ |
/ |
74 BDM’s Definitive
DefinitiveGuide
GuideSeries
www.bdmpublications.comSeries- -Volume
Volume34
34
Hangman Game Script
www.bdmpublications.com
www.bdmpublications.com 75
Black Dog Media
EXCLUSIVE Offers on
our Tech Guidebooks
Print & digital editions
Featuring the very latest updates
Step-by-step tutorials and guides
Created by BDM experts
Check out our latest titles today!
PLUS
of technology terms and phrases. We have looked across the tech boarders to bring to you the
definitive jargon buster, but it should help you to understand the common terms people use
0-9 Active Matrix Organic Light Emitting Diode. A One of the “Big Four” of American carriers
bright and colourful display technology popular on
smartphones (although it has now been superseded
3G by Super AMOLED and qHD.)
B...
The third generation of mobile data networking
used by both the iPhone and iPad. This connection is Bit
slower than Wi-Fi, but is more readily available and is Android A contraction of binary digit, the smallest unit of
used to transfer data from your device when you are The name of the operating on your smartphone
information storage or digital information that can
on the go. It uses the mobile phone network. (we are assuming you own an Android phone if you
take on one of two values, 0 and 1.
are reading this magazine). There have so far been
eleven versions/updates released.
4G Bit Depth
The fourth generation of mobile data networking. Defines how many bits of colour data are used
Android Market to describe each pixel or channel. For example, 2
The previous name for the Google Play Store. The
5G bits per pixel only allows for black or white. 8 bits
place to go to find apps, books and movies to install
The fifth generation of mobile data networking provides 256 colours. When referring to an 8-bit
on your phone.
offers increased speed when transferring data on colour image, 256 is multiplied by the three primary
the go but it is still in its early stages of adoption by channels (red, green and blue) to create what is
mobile phone networks. Anti-Aliasing Filter commonly called 24-bit colour, with a possible
This is an optical filter, also known as low-pass filter, 16,777,266 colours.
which is placed on the camera sensor to create a
A... slight blur or softening that helps counteract aliasing
Black Point
or Moiré interference.
In image editing, the black point is a tonal
Accessibility adjustment that sets the point at which the deepest
A series of tools and features designed to make an Apk (.apk) shadow detail in the histogram is clipped to black.
Apple device such as the Mac and mobile The file extension of Android applications.
devices easier to use by those with disabilities such
as vision or hearing impairments. You can find Bloatware
the Mac’s Accessibility features and customise them Apps (Applications) The name given to unwanted applications
in System Preferences. The programs, such as Angry Birds, Facebook preloaded onto your phone. Bloatware cannot
or Soundhound, that you install and run on you usually be removed by the end user unless they
Android phone. decide to root their handset.
ADB
Android Debug Bridge. Part of the Android Software
Development Kit, used to send commands from a App Store BlueTooth
computer to an attached phone. The App Store is where you can download free and Short range file data system built into almost every
paid programs to your device using your Apple ID. Android smartphone ever made. Can be used to
You can access it through the application found on send files and connect speakers or headphones
Adobe Bridge your home screen. wirelessly to your phone.
Bridge is a browser application produced by Adobe
Systems as part of the Creative Suite and is usually
installed alongside Photoshop. Its main function is as App Inventor Books
the file management hub of the Creative Suite. It can A web-based system that lets anyone develop apps Apple’s eBook reader, available from the App
be used to open, manage, rate and rename files as for Android. Originally created and run by Google, Store. It handles the standard electronic publishing
well as edit their metadata. but now run as an open-source project. formats protected by FairPlay DRM and PDF. It was
introduced in 2010 along with the iPad.
Dock
Comments The opaque strip at the bottom of the home screen.
File Format
A comment is a section of real world wording The structure of how information is encoded in a
Apps in the dock remain in a special row of icons (or
inserted by the programmer to help document computer file. File formats are designed to store
Folders post iOS 4) along the bottom of iPhone, iPod
what’s going on in the code. They can be single line specific types of information, such as JPEG and TIFF
touch and iPad screens and do not change when
or multi-line and are defined by a # or ‘’’. for image or raster data, AI for vector data or PDF for
you swipe between home screens.
document exchange.
Root Tegra 3
NVIDIA’s newer, quad-core, mobile processor.
VPN
In Android, to Root means to unlock the device to
allow more access to the core software (or root).
(Virtual Private Network):
This provides secure access over the Internet to
Tethering
private networks, such as the network at your
Using your smartphones data connection to provide
Router company or school.
internet access for another device (laptops, etc.)
A device that manages and organises your home
network devices, whether they connect to the router
using a cable (LAN), or wirelessly (WLAN). Text Field W...
Any area where you can add text. For example, the
S... search field is where you type something you’re While Loop
looking for. Tap on a text field to bring up the virtual A coding loop that repeats code while a
keyboard. comparative statement returns the value True.
Safari
Apple’s web browser, both for Mac OS X and iOS
(sometimes called Mobile Safari). Based on KHTML/
Thumbnail Image White Balance (WB)
A small, low-resolution image preview used on the In digital photography, white balance establishes
WebKit renderer and the Nitro JavaScript engine.
web to link to a high-resolution version of the file. the colour balance of the image in relationship to
Thumbnails can also be embedded in file formats colour temperature of the lighting conditions. Most
Samsung such as TIFF and PSD. digital cameras have several built-in white balance
A huge Korean smartphone and electronics presets (tungsten, daylight, cloudy, fluorescent, etc.)
manufacturer. along with an auto setting and the ability to set a
TIFF or TIF (Tagged Image File Format)
custom WB.
An open standard file format specifically designed
SD Card for images. TIFF can incorporate several types of
A small memory card which can often be inserted compression, including LZW, JPEG and ZIP. The Widgets
into smartphones to increase storage capacity. format is suitable for the storage of high quality The name given to the home-screen gadgets which
archive images. The DNG format is based on the allow you to see app updates, news, etc.
Sense main TIFF standard.
The user interface designed by and used on HTC Wi-Fi
phones. TouchWiz A group of backwards-compatible radio
Samsung’s custom user interface. technologies used to connect peripherals to a
Sharpening network wirelessly.
The process of increasing or emphasising contrast Twitter
around the edges of details in an image, to give the One of the most popular social networks built WLAN
impression that the image is sharper than it really is. around a follower and following system rather than Wireless Local Area Network. Your network of
friends. wireless devices, as opposed to devices connected
Sideload with a cable (see LAN).
The process of installing an app onto your phone U...
outside of the Google Play store. World Phone
A device which works on both CDMA and GSM
UPnP
SIM Card networks outside of its home country.
Universal Plug and Play. A protocol used by digital
The small plastic chip required in all GSM phones to media players for enjoying video, music, and
connect to the mobile network. pictures over your home network. WPS
Wi-Fi Protected Setup, an easier way of connecting
Siri wireless devices to your router.
URL
Apple’s intelligent virtual assistant, that replaces Uniform Resource Locator. This is a web address,
VoiceControl on the iPhone. used to access a web page on the Internet, and XYZ...
usually starts ‘www’ and ends in ‘.com’, or some
Sleep/Wake Button other top-level domain.
Xperia
Physical hardware button. Used to power on, wake A range of smartphones developed by Sony
from sleep, put to sleep and power down most USB Ericsson. Includes the Xperia T and the Xperia Play,
smartphones and tablets. Universal Serial Bus. The connection method the PlayStation smartphone.
now used by most smartphones to connect to a
Sony Ericsson computer or power source (MicroUSB).
YouTube
The company formed by Sony and Ericsson to Google-owned, web-based video streaming service.
manufacture and distribute mobile devices. V... A YouTube app is usually pre-installed on Android
devices.
Sprint Vanilla
One of the large US mobile carriers. Sometimes used to describe Android without any
custom user interface applied.
SSID
Service Set ID. In a nutshell, this is the ‘name’ of your VDSL
wireless network, and can be changed using your Very High Speed Digital Subscriber Line. It’s another
router. protocol for getting on the Internet using your
phone line, and is sometimes shortened to DSL.