100%(1)100% found this document useful (1 vote) 553 views97 pagesCoding For Beginners - 12th Edition 2022 - Coding For Beginners
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
’ Coding
For Beginner
aes alae)
Inside
Jargon-free Step-by-step | Clear Full
Tips & Advice Tutorials Colour GuidesWant to master your Code?
Then don't miss our NEW Programming
& Coding magazine on Ei Readly now!
NOW ABOUT PI!
The Future Is Code
(EW Even vou NEED TO Ki
di
The unimate
Raspberry
Pe Special
7 Program,
/ [is
| Build,
7 [= rt
,
Packed with OVER
Top Pi coding tips and guides
is the Pico really 2
Dive deep into Raspbian
coding game changer?
Lear which model PI
and learn it all!
is the right one for you
Click our handy link to read now: https://bit.ly/30cL1zxCoding
For Beginners
Coding For Beginners is the first and only choice if you
are new adopter and want to learn everything you'll need
to get started with coding and programming. This
independent manual is crammed with helpful guides and
step-by-step fully illustrated tutorials, written in plain
easy to follow English. Over the pages of this new user
guide you will clearly learn all you need to know about
coding your own amazing apps. With this unofficial
instruction manual at your side no problem will be
unsolvable, no question unanswered as you learn,
explore and enhance your programming skills.
Papercut
www.pclpublications.comas 34) Coding with C++
8 _ Being a Programmer 36 Your First C++ Program
10 ABrief History of Coding 38 Compile and Execute
12 Choosing a Programming Language 40. Using Comments
14 Creating a Coding Platform 42 Variables
44 Data Types
18 WhycH? 48 C++ Maths
20 C++ Facts & Figures ence
22 _ Equipment You Will Need
24 Structure of C++ Code 52 ) Introducing Python
26 How to Set Up C++ in Windows
28 Howto Set Up C++ ona Mac
30 Howto Set Up C++ in Linux
32 Other C++ IDEs to Install
54 Why Python?
56 What Can You Do with Python?
58 Python in Numbers
60 Equipment You will Need
62 Getting to know Python
64 Howto Set Up Python in Windows
66 Howto Set Up Python in Linux
Python on the Pi
Starting Python for the First Time
Your First Code
76 Saving and Executing Your Code
78 Executing Code from the Command Line
80 Numbers and Expressions
Using Comments’ - _ a
° . |
_
elm)
great coding titles
Miele mst)
TAA
pclpublications
ncryption;-Aljegamingyasci
ae eel Pe eatin ae ft
bute ne Jey ci ,
help May Wien
Er Faas et ain omg
=~ BEIR alah
lt aby
BTR Lapel eb PoE
1On4n41
etna eee ee
De a] fe
1.09301 001101 o0 o1
anne jos) als he he hehe
PPP Tee CLEC ERAN, |e) sheets ean Nala: Aenea eb ee):
rT ERR kala ee ee ee
Lan by 2A ee ee ee
potas ,
ay eee
Mears Ot pa i
103, OH 1 oK 002201 OO
01 @0 oo
i EA ot Aya B Le
PLE eK e
7 oN oy 1 Breen
y aie! ae
By
afb eeo oo(Welcome, Future Coder fp
Welcome,
Future Coder
Everything you do online, every time you
DUR UEC R CUR Ly
your in-car GPS, use your phone, play a game
ona tablet, console or PG, it's all been coded
Ree use
pee Rey
a ek rue uae a
Re ree Rune
Pe eee
eee ULL ee
Mukul
aac ai ee
Ce Se eke Ae oa eae
ete Ue erWelcome, Future Coder
Being a Programmer‘Times have changed since programming in the ‘80s,
but the core values still remain,
“It's up to you
how far to take
your coding
adventure!”
Being able to follow a logical pattern and
‘see an end results one ofthe most valued
‘kills ofa programmer.
a
(Being a Programmer Be
MORE THAN CODE
For those of you old enough to remember the ‘80s, the golden era of home
‘computing, the world of computing was a very iferent scene to how its
today. 8-bit computers that you could purchase asa whole, as opposed to
being in kit Form and you having to solder the parts together, were the stuff
of dreams; and getting your hands on one was sheer bliss contained within
a large plastic box. However, it wasn't so much the new technology that
computers then offered, moreover it was the Fact that forthe first time
ever, you could control what was being viewed on the ‘television’
Instead of simply playing one of the thousands of games available atthe
time, many users decided they wanted to create their own content, their
‘own games; or simply something that could help them with their homework
(or home finances. The simplicity of the 8-bit home computer meant that.
creating something from a few lines of BASIC code was achievable and so
the First generation of home-bred programmer was born,
From that point on, programming expanded exponentially. t wasn't long
before the bedroom coder was a thing ofthe past and huge teams of
designers, coders, artists and musicians were involved in making a single
‘game. This of course led to the programmer becoming more than simply
someone who could fashion a sprite on the screen and make it move at the
press of akey.
"Naturally ime has moved on and with it the technology that we use.
However, the fundamentals of programming remain the same; but what
exactly does it take to be a programmer?
‘The single most common trait of any programmer, regardless of what
they/re doing, isthe ability to see a logical pattern. By this we mean
someone who can logically Follow something from star to finish and
envisage the intended outcome. While you may not feel you're such a
person, its possible to train your bran into this way of thinking. Yes, ft
takes time but once you start to think in this particular way you willbe able
to.construct and Follow code.
Second tologicis an understanding of mathematics. You dont have to be
at a genius level but you do need to understand the rudiments of maths.
"Maths is all about being able to solve a problem and code mostly falls under
the umbrella of mathematics,
Being able to see the big picture is certainly beneficial for the modern
programmer. Undoubtedly, as a programmer, you will be part ofa team
of other programmers, and more than likely part of an even bigger team
of designers all of whom are creating a final product. While you may only
be expected to create a small element of that Final product, being able to
Understand what everyone else is doing wil help you create something
that’s ultimately better than simply being locked in your own coding cubicle.
Finally, there's also a level of creativity needed to be a good programmer.
‘Again though, you don't need to be a creative genius, just have the
imagination to be able to see the end product and how the user will interact
with
‘There is of course a lot more involved in being a programmer, including
learning the actual code itself, However, wth time, patience and the
determination to learn, anyone can become a programmer. Whether
you want to be part of a triple-A video game team or simply create an
automated routine to make your computing life easier, i's up to you how
Farto take your coding adventure!A Brief History of Coding
(eto at Ca eur en Lee eee P ete CeCe
is a modern concept that's only reallyyhappened in the last Fifty years or so. However,
that assumption is quite wrong, coding has actually been around for quite some time.
Cee Re RTO MORRO eek keg
Essentially all Forms of coding are made up of ones and zeros, on or off states. This works for a modern computer
een toca tC
7c
Petree ieee ord
Peet its
Fe ne
Cet end
eeu aee
Cie pcre
Peete oe
See ee ens
and orrery used to predict
Petree
Dee ey
Peon te
De gees
Book oF Ingenious Devices in around
Cone ec
eet
Bit eres oe
eres eee es
See eer cary
Deu oa ee a
punched holes to create the textile design.
Pea ese
design on a previous automated weaving
Dre SRL es
eee
ey
eee
pee eee
cee
Ree
Certs
ero aa
Red
ac)
Preece
program, Not bad,
considering there were
eure Tecra
cooDesa
Pee
Rao
Cerca
Cee at)
eye
Pere)
eee artery)
nen’
rs ee
nein
ese ee
Seren eter
ae CC Ug
Regional Assembly Language.
eraser
eee a
Cee eT
Seu eg
Peis oer
eee mo)
and ALGOL 58 were developed
teen eee
Classes (C+4), MATLAB, Common Lisp and more came tothe
fore. The 80s was undoubtedly the golden age ofthe home:
‘computer, a time when silicon processors were cheap enough
eee ea aU See nse)
Peruse ree
Computer programming was
Reson
eer)
See
pee es
Sener mics
Carta
the development of BASIC
eee
Peete
Sacer
Denese
emai Tee)
Peseta etry
Poem eae ny
Eee re a
hhow to code but they could Freely share
their code and source other code to
Ci
Crna read
the team that developed the UNIVAC
Rem eer eat)
developed a compiler frit. n time,
erect
COBOL (Common Business-oriented
rere easter ny
Poet
perce) "Choosing a
Programming
Language
It would be impossible to properly
explain every programming language in
a single book of this size. New languages
and ways in which to ‘talk’ to a computer
elms (Ue E-IneRs1aeaaieatae (oa e-1c2 ole)
invented almost daily; and with the
onset of quantum computing, even more
complex methods are being born. Here
isa list of the more common languages
EC Te Renae aie e oea cece
Cee hee ee ee
(American National Standards institute) standard, there ae differen versions oF
ee eee eee eee
ee ese ee eee ga
BN Ce ae JavaScript (often shortened to J) isa lightweight,
interpreted, object-oriented language with frst class
Functions. JavaScript runs on the client side ofthe web, that can be used to design
‘or program how the web pages behave on the occurrence of an event. JavaScript is
an easy to learn and also powerful scripting language, widely used for controlling
Reese
& Pw Java Is the foundation for virtually every type of networked
Ber a eee ere ec and
ee aS
PTT ishaetosierredslia irate taarep actdidakirtiLarhedelaa
Java Virtual Machine (JVM) that translates Java code into machine language.
itis an elegant object-oriented language that enables developers to
build a variety of secure and robust applications that run on the NET
Pete ee tte ten ast ee aes
client server applications, database applications and much more. The curly-brace
syntax of C# wll be instantly recognisable to anyone familar with C, C++ or Java,
POPU <0) Peceutetern deter eeeedand
Peston eecinpnaicsnngee net ote
See ee ene een peter
Dee ea ee Su Ce ek eu
abe pret eerie te ace ett
eet
C#+ (pronounced cee plus plus) is a general purpose programming
ee ee ee ar)
Features. It was designed with a bias toward system programming and embedded,
resource-constrained and large systems, with performance, efficiency and Flexibility
of use asits design highlights.
a Rubyis a language of careful balance. Its creator, Yukihiro "Matz"
Peer en ee ree eee ae cls
Se our ee ari
CO ee ree tea
parts of Ruby can be removed or redefined, at wll Existing parts can be added to,
i - Seeereeetoemneete trices
‘ toe enicuny sneer
Poremeretenkately tment Son eee
beifebtsicieil oregonian ie dbelnuee salou
powerful builtin support for text pracessing and has one of the most impressive
eons
‘Swifts a powerful and intuitive programming language For macOS,
EZ 05, watchOS and tvOS, Writing Swift code is interactive and fun,
Cee ese ee et eed
Cee re ee eee
Lightning fast. A coding tutorial app, Swift Playgrounds, is available forthe iPad,Welcome, Future Coder
Creating a Coding
Platform
pep eieertrenrsrnnrre
Bair eenpeinineneer hcg tnn
reee einen ee
peabrenmrnernen Wee ar
cee ee Ce ceria
peer eeeiente Cena
pia heen geet ae
pia EORTC
ere Tegner
peepee eS oes
eee
foe as
Thankfully, coding at the
cass ayy
foundation level doesn’
hydrogen-cooled PC. IF
you own a computer, no matter how basic you can begin to
learn how to code. Naturally, ifthe computerin question isa
‘Commodore 64 then you may have some difficulty following a
modern language tutorial, but some of the best programmers
‘around today started on an 8 bit machine, so there's hope yet.
You will need access to the Internet to download, install and
Update the coding development environment, alongside @
computer with Windows 10, macOS, or Linu, installed. You
canuse other operating systems, but these are the ‘big three!
and you wil find that most code resources are written with
fone, oral, ofthese in mind,
vwvnvpcgubiatenscom
CeO et ed
Pre enero a Gee tnt
Cir
huge amount of third-party software to consider. n addition, by
accessing the internet, you will discover that there are countless.
lable forthe language in which you've decided
enone ere eee
ST eee eins
SI ee EL nes eek
into coding. Like all good projects, you need a solid foundation
ee ete eee ee este
Peer eee ea ace ora try
Creating a coding platform comes in a twill be your learning
Foundation while you begin to take your Firs tentative steps into
Pei)
In terms of sofware,
most ofthe development
environments have
tools that allow you to
code, compile the code
and executeit, Freely
‘avaliable
tools avallable that w
Over time, you may find yourself progressing From the:
mainstream development environment and using a collection
‘of your own, ciscovered, tools to write your code. It's al
personal preference in the end and as you become more
experienced, you will start to use different tools ta get the
job done,OPERATING SYSTEMS
\windows 10s the most widely used operating system in the
world, so i's natural that the vast majority of coding tools are
written for Microsoft's leading operating system. However,
don't discount macOs and especialy Linux
‘mac users enjoy an equal number of coding tools to their
windows counterparts. n act, you will probably Find that a
lot of professional coders use a Mac over a PC, simply because
of the Fact that the Mac operating system is but on top of
Unix the command-tine OS that powers much ofthe world's
filesystems and servers). This Unix layer lets you test programs
Inalmost any language without using a specialised IDE
However, Linux's, by farand away, ne of the most popular
and important coding operating systems avalable. Not only
does ithave a Unixike backbone, t's also free to download,
install and use and comes with most of the tools necessary to
start learning how to code. Linux powers most of the servers
that make up the Internet. It’ used on nearly al oF the top
supercomputers, as well as specifically n organisations such
Eas NASA, CERN and the miltary, tals forms the base of
£ android-powered devices, smart TVs and incar systems, Linux,
as a coding platform, is an excellent idea and it can be installed
inside a virtual machine without ever affecting the instalation
(of Windows or macOS.
Baa
If youhaven't already heard ofthe Raspberry, then we
suggest you head overto www.raspberrypl.org and check
tout. In shor, the Raspberry Pits a smal Fully functional
computer. It comes with its own customised, Linux
based operating system that's preinstalled with
everything you need to start learning how to
code in Python, C++, Scratch and more.
Costing around €35, it's incredibly
cheap andallows you to utilise
different hardware, in
the form of robotics and
electronics projects, as well
as offering a complete desktop
experience. Although not the most
powerful computing device in the world, the
Raspberry Pi has alot going For it especialy n terms
(of being one ofthe best coding platforms available.
} The advantage of a virtual machine isthat you can work with
Linux, For example, without it affecting your currently installed
host OS. This means that you can have Windows 10 running and
launch your virtual machine client, Boot into Linuxand use all
the functionality oF Linux, while still being able to use Windows.
YOUR OWN CODING PLATFORM
Creating a Coding Platform Be
AU ela 9
‘Avirtual machine sa piece of software that alowsyou toinstalla
fully working operating system within the confines of the software
itselé. The installed 05 vil allocate user-defined resourcesfrom the
host computer, providing memory, hard drivespaceet, aswell as,
sharing the host computer's internat connection,
‘This, of course, makes it a fantastic coding platform, as you can
have different installations of operating systems running from
the host computer while using different coding languages.
You can test your code without fear of breaking your host OS
{andit's easy to return to a previous configuration without the
need to reinstall everything again
Virtualisation fs the key to most big companies nove You.
will probably Find, rather than having a single server with an
installation of Windows Server, for example, the IT team have
instead opted fora virtualized environment whereby each
Windows Server instance isa virtual machine running from
several powerful machines. his cuts down on the number
‘of physical machines, allows the team to better manage
resources and enables them to deploy an entire server
dedicated toa particular task ina Fraction of the time,
‘Whichever method you choose, remember that your coding
platform will probably change, as you gain experience
and Favour one language over anather, Don't be
affaid to experiment along the way, as
‘you willeventually create your
‘own unique platform that
canhandle all the code
By: you enter into it
ea
reIntroducing
ty
i
10h
uy ah
I 0)
uy oO
uu i
a i
oD
10
oe
i CnCUrueo Eirias
i) Caste cea RCo ts
iY Pte cari Ceetauc Cin tar
7 using Windows, macOS or Linux, is created
}0 Pen Kemer ecru een ud
RCRA ee eens
Pca earer een elses
Pee eee ee
mare eie Pum eeu teT
RIP Tee CL ee cue
applications, games and much more. It’s used in
Ree ae une a cae mee eels aca
space industry, and much more.
pn el call academy bee
relate er er Sot tee
7<4 Introducing C++ ;
Why C++?
C EVERYTHING
Due to both the complexity of the language 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 ofthe golden era ofhome
computing, C#4, or rather C with Classes, was the brainchild oF
Danish computer scientist Bjarne Stroustrup, while working on
his Ph.D. thesis Stroustrup's plan was to Further the original C
language, which had been widely used since the early seventies.
C++ proved to be popular among the developers ofthe 80s, since
Tewas a much easier environment with which to get to grips,
‘and, more importantly, It was 99% compatible wth the original C
language. This meant that, beyond the mainstream computing labs,
regular people who didnt have access to the mainframes and large
computing data centres could use it.
C++'simpactin the digital world isimmense. Many ofthe programs,
applications, games, and even operating systems are coded
cos cadets uch atria ober
OD Saco nen
Using C++. For example, all of Adobe's major applications, such as.
Photoshop, InDesign and so on, are developed in C++. You will Find
that the browser you use to surf the Internet is written in C++, a5,
well as Windows 10, Microsoft Office, and the backbone to Gcogle's
search engine. Apple's macOSis written largely in C++ (with some
‘ther languages mixed in depending on the function), and the likes
‘of NASA, SpaceX, and even CERN use C++ for various applications,
programs, controls, and umpteen other computing tasks.
Aswell as being an easier addition to the core C language, C+ is
also extremely efficient and performs well across the board. This,
higher level of performance over other languages, such as Python,
BASIC and such, makes itn ideal development environment for
‘modern computing; hence the aforementioned companies using i
so widely.tind, intempo Unpupe ps
ee ~ stp detopmen ith
cont
ees
a = Liens
a —
a
‘Microsoft's Visual Studio is a great, free
‘environment in which to learn C++.
‘C¥+ puts the developer ina much wider world of coding. By
mastering C++, you wil Find yourself being able to develop code for
the ikes of Microsoft, Apple and so on. Generally, Cr+ developers
‘enjoy a higher salary than programmers of some other languages,
‘and, due to its versatility the C++ programmer can move between
{obs and companies without the need to relearn anything speci
You will discover, as you become a more advanced coder, that many
‘oF the developersin various coding jobs around the worid tend to
use pre-designed development engines. For example, when creating
‘games, the likes of Bethesda, the team behind Oblivion and Skyrim,
utilse 8 3D game engine called The Creation Engine. This enables
the team to quickly create animations, characters, tems, terrains,
ooms, and just about everything else you'd se inthe game. The
‘engine itself has been modified to make the most of the current
‘graphics card hardware, and computer or console processing
ower These engines are mostly written in C++, and when making
Indeed, the operating system
you're using is written in C+.
Windows 10
debian
Improvements to the engine, or when creating anew game, if
the developers want to add something that the engine can't do,
they wil use C++ to create the new content of link between two
different engines. The end result, of course, is 8 game that contains
the latest graphical technology, while being seamlessly bound
together with some pretty clever C++ coding.
Getting to use C++is quite easy, all you needs the right set of tools
in which to communicate with the computerin C++, and youcan
start yourjoumey. A C#+ IDEs Free of charge, even the immensely
powerful Visual Studio from Microsoft freely avalable to
‘download and use. You can get into C++ from any operating system,
bbeit macOS, Linux, Windows, or even mobile platforms.
So, to answerthe question of Why C++, the answer is because it's Fast,
efficent, and developed by most ofthe applications you regularly
use. lt cutting edge, and a fantastic language ta have mastered.
Mac
ubuntubh Introducing C+ :
C++ is one of the top
programming languages
in the industry. It's quick,
powerful, and used by
nearly every major tech
and gaming company in
the world. Here’s some
interesting Facts about
the rather wonderful C++. 2
C++is
one of the
predominant
programming
languages for the
development of all
kinds of technical
and commercial
software.
NASA, CERN,
4 microsort,
ORACLE, PAYPAL,
¥ LINKEDIN, AMAZON AND
“Ly THE MILITARY USE C++.
C++ has
e ih IN E influenced other
programming
3D ANIMATION, Gagesgeeuehae
MODELLING, C# and Java.
AND SIMULATIONS
SSF
LSE es eeeeeees
Alot of the
Linux operating
system is coded
using C++, therefore
you could say that most
of the world's Internet
hosting servers are
available thanks to C++.
r SUPERCOMPUTING USES C++ CODE More than 70% of all
‘Y- TOCALCULATE VAST AMOUNTS OF fee noe
q> 4 DATA, INCLUDING THE NASA-BASED (HET), and the software
4 SUPERCOMPUTING FARM THAT RUNS responsible is written in
f SIMULATIONS OF THE UNIVERSE. See tomake use cf i
y high speed.Soures "obsWatch, my
Google, Quor, Stock ( C++Facts & Figures Eg
ae a bce fecs | wha
stachoverton
atta, ES thextax
Avpoynanies ‘operating system
Uses C++ as its
backbone.
Gaming is one of the
biggest users of C+.
Ithandles the
Many database applications complexities of 3D games,
are built using Ce, such supports multiplayer coogle chrome, MacKis
as MySQL. it's also used options, and enables Firefox, and even MicrosoR’s
by Wikipedia, Yahoo and intensive CPU and Edge web browsers are
YouTube. GPU hardware coded in ++.
Functions.
THE
CHis tr
used in computer
networking as the nm
main code behind the
Programmable Logic PERCENTILESALARY i mossrecaes
Controller, connecting FORAUKBASED Cr+ sable of products
servers, processors, other DEVELOPER IS erenpeit:
hardware, and Using C+.
even robotics.
MRI scanning
machines and _
‘Windows 95,98, 2000, Computer Aided Design The Unreal 4 Engine,
XP, 7,8.1 and 10, as well as all use C++ to help with which is coded in C++,
icrosoft Office, use C++ the enhanced imagery is used for hundreds
asthe backbone programming produced by these of games, including
language of choice. systems. Fortnite.
RADAR
aes
ise)
ote)
Panay
ADVANCED
eae
plate]
SS aoe dee e cece eeeeeeeeeeees
| FLIGHT CONTROL SYSTEMS IN
MODERN AIRCRAFT, INCLUDING
MILITARY AIRCRAFT, USE C++.Bp Introducing C++)
Equipment You
Will Need
Noe ol aurtreReoM te Mue eee OM Uo A Re cod CG ee D TOL)
feleyaNen t-te alee Reo Ul eiiven R=] Mol mel iores-) Elen R Tene R CANE
modern computer, everything else is freely available.
C++ SETUPS
‘As most, if not all, operating systems have C++ at their code, it stands to reason that you can learn to program in C++ no
matter what OS you're currently using.
[| computer
Unless you fancy wring out your C++ code by hand ona sheet of paper (ich is
someting many oder cers used todo), then 3 computer isan absolute mast nave
component. Pc users canhave any recent Linuxaltro or Windows OS, Mac users the
tatestmacos.
|_| AN IDE
‘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 will provide enhancements depending on the core OS being used,
such as enhancements for Windows 10.
|_| COMPILER
‘A.compiler is @ program that converts the C++ language into binary that the
‘computer can understand, While some IDEs come with a compiler built in, others
don't. Code:Blocksis cur Favourite IDE that comes with a C++ compiler as part of the
package. More on this later.
[_] TEXT EDITOR
Some programmes much prefer to use text eo to assemble ther C+ code
before runing trough a compiler Essent, you can se ary ext editor to write
ce stsavett witha cop extension However, Notepads one ofthe best code
texteditorseviable
|_| INTERNET ACCESS.
‘while it's entirely possible to learn haw to cade on a computer that’s not attached
tothe Internet, i's extraordinarily difficult, You will need to install the relevant
software, keep it up to date, install any extras or extensions, and look For help when
‘coding. All of which require access to the Internet.
TIME AND PATIENCE
You're going to need to set aside significant time to spend on learning how to code
in Ce. Sadly, unless you'r a genius, it's not going to happen overnight, or even ina
‘week. A good C++ coder has spent many years honing their craft, so be patient, start
small and keep learning.Equipment You Will Need
OS SPECIFIC NEEDS
C#+ will work in any operating system; however, getting all the necessary pieces together can be confusing to a newcomer. Here's
some OS specifics For C+,
ray
’As we've mentioned previously, one good IDE is Microsoft's
Visual Studio, However, a better IDE and compiler is
Code:Blocks, whichis Kept regularly up to date with anew
release twice yearly, or sa, Otherwise, Windows users can
enter their code in Notepad++ then compile it with MinGW —
wich CodeBlocks uses
Linux users are lucky in that they already have a compiler and
text editor builtinto their operating system. Any text editor
il allow you to type out your C++ code, when its saved with
2.cpp extension, use ge= to compile it
1a
‘The Raspberry P's operating
system is Raspbian, whichis
Linux based. Therefore, you're
able to write your code out
using atext editor and then
compile ewith g++, as you
‘would in any other Linux distro,
Mac owners willneed to
download and install Xcode,
in orderto compile their
C+ code natively Other
‘options for the macOS
Include Netbeans, Eclipse or
Coderlocks. Note: the
latest Code: Blocks isnt
available for Mac, due toa
lack oF Mac developers.
asBD inc)
Structure of C++ Code
eee eee TMT CMete cd Me TR eco sce ee
designer, or work at the cutting edge of science or engineering technology, then being
able to code in C++ is a must. Remember, you're never too old to learn how to code.
#INCLUDE
‘As you learn the basics of programming, you will begin to understand the structure of a program. The commands may be
Fferent, but you will start to see how the code works.
a #INCLUDE 7 ane
Te strucure of + program ae a
Danish student Bjarne can look complex, but once you ieee ee
Stowtrupimentedcesin £ getfomtarwthtyouibegh to
1979,asapartorhisPhO. | seehowitfows Every Cr+ cade
thesis inoly Cre was called beginewtha directive, ncude | =
‘Cwith Classes, which added =. Thedirective instructsthe ¢”) *newcode.cpp
FAUSERSEENESTIM: preprecesoriobcinies
C programming language ‘section of the standard C++ #include
vite making a more tock, For eral itu
Userfriendyenafonment. ? indudes the
stream header suppor:
Bjarne Stroustrup, inventor ‘input/output operations.
ofr.
INT MAIN() 2 areas
3 int main( initiates the a Documents
4 2 declaration of a Function, which pee st View, poms Bee
isa group ofcodestaterents
underthe name maint All
(C++ code begins at the main
function regardless of where _(¢") #neweode.cpp_
ilies within the main body of
the code, bower sinclude
(A.
int main()
BRACES . newcode.cpp (-/Documents) 2
The open brace is File Edit View Search Tools Documents Help
something that you may
fnothave come across
before, especially if
‘you're used to other
coding languages. The
‘open brace indicates the
beginning ofthe main
function, and contains
allthe code belonging to
that function
[ci *newcode.cpp x
#include
int main()
{
24COMMENTS
Lines that begin with a double slash are comments. This means they
‘won't be executedin the code and are ignored by the compiler. Why
{are they there? Comments are designed to help you, or another
programmer [ooking at your code, explain what's going on. There
‘are two types of comment: * covers multiple ine comments, // 3
single tne.
. snewcode.cpp (Documents)
Fle Edit View Search Tools Docunens Help
‘include
dint main()
(/ 7 Best Coe program!
STD
In C++, STD means Standard. t's a part ofthe Standard Namespace
in C++, which covers a numberof different statements and
‘commands, You can leave the std part out of a code, but it must be
declared atthe start with: using namespace std.
. *newcode.cpp (-/Documents)
Fle Edt View Search Tools Documents Help
‘€)tnewcodecpp %
include
using namespace std;
int main()
(
{1 7 Firat coe progrant
COUT
In this example we're using cout, whichis apart ofthe Standard
Namespace hence why it's there, as you're asking C++ to use itfrom
that particular namespace. Cout means Character OUTput, which
‘displays, or prints, something to the screen. Fwe leave stds: out we
have to declare it atthe start ofthe code; as mentioned previously
. snewcode.
int main()
1 My first Ces program!
std::cout
y
K! Structure of C++ Code Be
<<
“The two chewons used here are insertion operators. This means
that, whatever follows, the chevrons are tobe inserted into the
std=cout statement. this case, they are the words ‘Hello World’,
“which are to be displayed on the screen when you compile and
execute the code,
. “newcode-epp (-/Documents)
Fle Edt View Search Tools Documents Help
(€trewcode cpp
l#include
Ant main()
UL My first Ces program!
Std: icout << ("Hello World!\n")
OUTPUTS
Leading on, (Hello World!) is the part that we want to appear on.
the screen when the code is executed. You can enter whatever you
like, 2s long asi’ inside the quotation marks. The brackets aren't
needed, but some compilers insist-on them. The \n pat indicates a
new line i to be inserted,
7/ My first C++ program!
cout << ("Hello World!\n")|
; AND}
Finally you will notice that lines within a Function code block
(except comments) end with a semicolon. This marks the end of
the statement, and all statementsin C++ must have one at the end
fr the compiler wil Fall to build the code. The very last line has the
closing brace to indicate the end of the main Function.Bp Introducing C++)
How to Set Up
C++ in Windows
Windows users have a wealth of choice when it comes to programming in C++. There
are loads of IDEs and compilers available, including Visual Studio from Microsoft.
MMe a cana ene Pack Tamer ect sel cre ce
CODE::BLOCKS
CodeBlocks is a free C++, Cand Fortran IDE that is Feature rich and easily extendible with plugins. It's easy to use, comes with
‘a compiler and has.a vibrant community behind it too.
BRPEED starts visting the Code:Blocks download ste, at IBPEMS when you've located the fie, click on the
www.codeblocks.org/downtoads. From there, click Sourceforge.net link atthe end of the ine and a
‘on the ‘Download the binary releases’ nkto be taken tothe 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 lick to start. Follow
the on-screen instructions to begin the instalation.
(@ coaesdocis naa
Wolcome to CodeBlocks Setup
Sup tes thas ert fests,
eereconmede at yuo peng
‘iresarag Sau Taran pss ope
‘Seton er tettorg erent es
ru
acne canoe
ESTEE There you can see, there are several windows ESTeeE RD Once you agree to the licencing terms, a choice of
versions available. The one you want to download installation options becomes available. You can opt
has mingw-setup.exe atthe end ofthe 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 recommend that you opt fo the Full option, as default
difference is that the mingw-setup version includes a C++ compiler
and debugger from TDM-GCC (a compiler suite). eananieeieties
ew Congrats
Beeman Comes ore eet ea
—— "| Sep teem nee ns sr et
ose Ye seecenpectenat tien siese stewing |
vs | Sigmar
ym ame
peaveneneee renee Soxcerened: 251446( Howto Set Up C++ in Windows
Next choose an instal tcaton for the Coderslols There's ak you can doin Codelocks 30 you need
supe files. It's your choice but the default is generally Suet to dig in and Find a good C++ tutorial to help you
suffiden(nlessyouhave ay spec requirements ofcourse. _getthe mostfrom k However, to begin with, cicon File» New >
Whensou cle, hes begins; hen sisted Empty Fle. Tiscrestes new, bank window for youto type n
natfcaton pops psig you you wane tart Code-Blcksrow,
‘so click Yes. sae
eae era csr advo Roane cent ronsstt Melos!
Pcseseseasessee ci asnceasnenaen aaecancas asa]
ere oi
a
m7 rs
ener iUnadnastaanne cesar Meu
The first time Coder:Blocks loads feruns an
‘autodetect For any C++ compilers you may already
have installed on your system. If you don't have any click on the
First detected option: GNU GCC Compiler and click the Default ai
button to sett asthe systemis Cr+ compiler Click OK whenyou'e °
ready to continue.
#include
/MMy Siest CH peogean
Stdzrcout << “Hello World! \n";
totes cn entre eset ep eect eee "
neo Notice how CodeBlocks auto-inserts the braces and speech quotes.
FETED The program starts and another message appears RETESET lick File > Save as and save the code with a
Informing you that Code:Blocksis currently not pp extension (helloworld.cpp, for example)
the default application For C++Files. You have two options, toleave CodeBlocks changes the view to colour code according to C++
everything as itis or allow CodeBlocks to associate all C++ lle standards. To execute the code, click on the Bulld and Run icon
types. Again, we would recommend you opt For thelast choice, to along the top of the screen, It's a green play icon together with a
associate Code:Blocks with every supported filetype. vellow cog,Introducing C++
How to Set Up C++
ona Mac
To begin C++ coding on a Mac you can use Apple's own developer platform: Xcode. This
is a free, Full featured IDE that's designed to create native Apple apps. However, it’s
also able to be used to create C++ code relatively easily.
Xcode is primarily designed for users to develop apps For macOS, iOS, tvOS and watchOS applications in Swift or
but we can use it for C++ too,
FTTEEEDD 21ty opening the App Store on your Mac, Apple STEM when you're ready click onthe Getorcloudicon
Menu App Store Inthe Search box enter Xcode, button which wil install the Xcode app. Enter your
and press Return. There wilbe many suggestions filing the App "Apple D, and Xcadewilbeginto download and instal. may take
‘Store window, but I's first option, Xcode, that you need to clickon, some time depending on the speed of your internet connection, as
Xcode is in excess oF 1168.
ESTEE Tekea moment to browse through the app's FETS DD When the installation is complete, click on the Open
Information, including the compatibility to ensure button to launch Xcode. Click Agree to the licence
you have the correct version of macOS. Xcode requires macOS tess, and enter your password to alow Xcode to make changes.
10.12.6 or laterto install and work. to the system. When you've done that, Xcode will begin to instal,
additional components.FETED With everything now installed including the
additional components, Xcode wil launch displaying
the version number along with three choices and any recent projects
that you've worked on although Fora fresh instal ths willbe blank
How to Set Up C++ on a Mac 9p
BETeeE DD The next step asks where to create a Git Repository
For allyour Future code. Choose a location on your
IMac, ora network location, and click the Create button. When
you've done allthat, you can start to code. The leftshand pane
details the Files used in the C++ program you're coding. lick on the
rmain.cpp file thelist
‘Start by clicking on Create New Xcode Project, this
SUES ‘opens a template window to choose which platform:
Youre developing code for ick the macOs tab, then cick he
Command Line Tool option, Clkext to conve
Fill inal the fields, but ensure that the Language
‘option at the bottom is set to C++. Simply choose
it from the drop-down list, when you've filled in the fields, and
made sure that C++ isthe chosen language, clck on the Next
button to continue,
Yeuvil notice hat codehas automaticaly
Guar) completed a basic Hello World program for you.
‘The iferences ere aretha the nt main uncon now contans
rule funtion andthe yout sight ferent. This
Xcode utilising the content that’s available to your Mac.
BETS Whenyou want to run the code, click on Product >
Run. You may be asked to enable Developer Mode
‘on the Mac, this to authorise Xcode to perform functions without
needing your password every session. When the program executes,
the output willbe displayed at the bottom of the Xcode window.Ep Introducing C++ )
How to Set Up C++
in Linux
LINUX++
‘There are many different versions of Linux available, For this example we're using one of the more popular distributions: Linux
Mint. However, these steps will work in any Debian-based Linux.
FETED The firststep with ensuring Linuxis ready foryour EPI Amazinaly,thatsit. everything is allready For you
Cr codels check the system and software are tostart coding, Here's how to get your first C++
upto date. Open a Terminal and enter: sudo apt-get update program upand running In Linux Mint the main text editor is Xed
66 sudo apt-get upgrade. Press Return and enter your canbe launched by clicking on the Menu and typing xed into the
password. These commands updates the entire system and any search ba. Click on the Text Editor button in the right-hand pane to
installed software. open Xed.
File Edit View Search Terminal Help
Ere eran ee
[sudo] password for david: Mf
ERTSSER Most Linux distros come preinstalled with all the PEED 10 Xed, or any other text editor you may be using
necessary components to start coding in C++. enter the lines of code that make up your C++ Hello
However, t's always worth checking to ee iFeverything s present, World program, To remind you, i's:
sostill within the Terminal enter: sudo ape-g: 11
#include
build-sesential and press Return. f you have the right
components, nothing is installed butif you're missingsomethen int main()
they are installed by the command, ;
TS
Fie Est Vow Ser Teal Hop sae a
¢
| samy rat cn poaran
b( How to Set Up C++ in Linux Ee
PEP) when youve entered your code, click File>save As RNMPNPBS sofore you can execute the C++ file youneed to
{and choose a folder where you want to save your compile it In Linux t's comman to use g++, an open
program. Name the file as helloworld.cpp, ar any other name justas source C++ compiler and as you're nowin the same Folder asthe
long as it has.cpp as the extension, Clck Save to continue. C++file,goto the Terminal, enter:g#+ hel
press return,
[ davidemi:
| Fie edie View Search Terminal Help
rrr Pras ac
errerrseerey
nT
‘The first thing you can seeis that Xed has FEED there willbe a brief pause asthe code is compiled
‘automatically recognised this asa Cr+ file, since the by gs+ and providing there are no mistakes oF
File extension is now set to.cpp. The colour cading ispresentinthe _errorsinthe code yauare retumed to the command prompt. The
code and iF you open up the file manager you can also see that the compiling of the code has created a new file, you enter 1s into the
file's icon has C++ stamped ont. Terminal you can see that alongside your C++ files a.out
aaa File Edit View Search Terminal Help
e reece Freestar eT)
ts
Poets)
tprenirenstsy
PEPER with vourcode now saved, drop into the Terminal EPMIM) The acutfileis the compiled C++ code. Torun the
‘again. You need to navigate to the location of
code enter: ./a-out and press Return, The words
the C+ file you've just saved, Our example isin the Documents Hello World appears on the screen, However, a.out isnt very Friendly
Folder, so we can navigate to it by entering: cd. Docunients. Toname it something else post-compiling, you can recompile with:
Remember, the Linux Terminalis case sensitive, soany capitals must g++ helloworid.cpp ~2 hellowor1d. Ths creates an output
be entered correctly file called helloworld which can be run with: /hel Lower ld.
Fle Et View Search Terinal_Hep
File Edit View Search Terminal Help
CEC
COMO tieyOther C++ IDEs to Install
ICU ccc econ hn C meade Aen cei
plenty of options available to you. Windows is the most prolific platform For C++ IDEs
eserer ea cus ious ur eaten
DEVELOPING C++
Here are ten great C++ IDES that are worth looking into. You can install one oral of them ifyou like, but Find the one that
works best for you.
ESTED EicseisahuoelypopuiarC++iD€ that offers PRINTS Codelite sa free and open source IDE that's
the programmer 2 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 clckthe Need Help link download and install tat www-codelite.ora/.
For more information.
lvikibivwrlcelue®’
‘The GNAT Programming Studio (GPS] is powerful ‘Another popular choice is NetBeans. This
‘and intuitive IDE that supports testing, debugging 's another excellent IDE that's packed with
‘and code analysis. The Community Editon is free, whereas the Features and a pleasure to use. NetBeans IDE includes project based
Pro version costs; however, the Community Editions 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/
Features/epp/index html.
Tes TEERECTOR Microsoft's visual studio isa
mammoth C+ IDE that allows you
to.create applications for Windows, Android, iOS and the web. The
‘Community version s free to download and install but the other
versions allow a free trial period. Go to wwwvisualstudio.com/ to
‘see what it can do for you.
Other C++ IDEs to Install Be
“The Anjuta DevStudio sa Linux-only IDE that
Features some of the more advanced Features you
‘would normally Find ina paid software development studio. There's
@ GUI designer, source editor, app wizard, interactive debugger and
‘much more. Go to wwww.anjuta.org/ for more information.
een This cross-platform IDEis designed to
create C++ applications for desktop and
mobile environments. It comes with a code editor and integrated
tools for testing and debugging, as wel as deploying to you chosen
platform, t's not free but there is atrial period on offer before
Fequiring purchasing: wwrw.qt.io/qt-Features-libraries-apis-tools-
Bloodshed Dev C++, despite its colourful name,
isan older IDE thats for Windows systems only.
DEV C++
However, many users praise its clean interface and uncomplicated
‘way of coding and compiling. Although there's not been much
‘updating for some time, i's certainly one to consider if you want
something different: www.bloodshed.net/devepp.html,
eRe Ths excellent DE allows developers
towrite C++ code for desktop and
\web applications acrosallthe major platforms. There's an advanced
text editor, integrated debugger and a configurable workbench to
help you create your code.’ avalable for Windows, Mac and Linux
ands Fee to downlead and use: www.monodevelop.comy.
tH
ine
FYFE Utimaters isa cross-platform C++ IDE that boats arapid
development of code through the smart and aggressive
Use of C++. For the novice it's a beast of an IDE but behind its
complexity isa beauty that would make 2 developers knees go
‘wobbly. Find out more at wwwultimatepp.org/index. html(Gereliare
with C++
Reese Rue E ea
Cee ak ee)
execute your first C++ code, through to
CC Rec esrtedUMeey ace)
Reheat dure caren ear
tricks will lead you in the right direction.
era era hk ee
languages in this book, and it’s continually
SES uCr cli tacos
Ed mR cee LU
Sas CONTR gee
sought-after coder and a vital member of the
eo RTs
35BD eirssance)
Your First C++ Program
SEM aco Cece Mercato Treg svi Cath col
working exclusively in Windows and Code::Blocks from here on. Let's begin by writing
oN Ask Coes cele Eee date a eure nner meee ae
HELLO, WORLD!
Ws traditional
dates back to 1968 using a language called BCPL.
programming for the First code to be entered to output the words ‘Hello, World!’ to the screen. interestingly,
We're going to use Windows 10 and the excellent
IDE Code:locks forthe rest of the C++ code and
tutorialsinthis book. Begin by launching CodeBlocks. When open,
‘dick on File> New > Empty File or press CirShift+N onthe keyboard,
AB Cox:20:h8
we
o—e—9—
ir"
‘Atte moment it doesnt look like much, and
it makes even less sense, but well get to that
in due course. Now click on Fle > Save File As, Create or find @
suitable location on your hard drive andin the File Name box, call
ithellowori.cpp. Click the Save as type box and select C/C++ fils.
Click the Save button,
Now you cin see a blank screen, with th tab
labelled *Untitiedt, andthe ndmber one in the top
left ofthe(inain Code:logks window. Begin by clicking inthe main. |
window, so the cprsorisnextto the numbef one, andentering: 0
1 finetide dlostzeam9 O11 1 10
1 ¥ 0 0 100
0.0 | [wis cocaine
ie Ed Vw Sah Piet al Dg aan th To ese Pgs Soot
ine
[Pm
0
0
1
_-o-
aaa
Sotican see that CodeBlcks has ndw changed
thetolour coding, recognising thatthe ies now
Crricode. This meats thatcode canbe auto selected from the 0
Code: Blocks repository. plete the tnclude ostream line and) | 0 9
reenterit; Youcan seethe autoselect boxes appeating. 0
(toned pce Ti
Fie Est nw Sach Pijed Bald Deg Fonte woth Ta Tee Pgs oy
[eager xmalagiorsonYour First C++ Program Ba
ERTISERD vto-election of commandsis extremely handy and [RPM Nove acain the colour coding change. Press Return at
cuts out potential mistyping, Press Returnto get to the end ofthe previous steps ne, and then enter:
line 3, then enter: ut << “Welle, world!\n"7
etd
int main()
Note: there's no space between the brackets.
Pa
‘include
= oe ce tai, worna!\an|
ESTEE onthenest ine belowintmaind,entera cury bracket: ENMAIPM Just as before, code:Biocks auto-completes the
' ‘ode you're entering, including placing a cosing
speech markas soon as you enter the First. Dont Forget the
‘This can be done by pressing Shiftandithe key tothe right of Ponan semicolon at the end of the line; this sone of the most important
English Uk keyboard layout. elements toa C++ program and well tell you why inthe next
section. For now, move the cursor down tothe closing curly bracket
and press Return,
‘xm alaalo> so ok al>
‘Finclude @ ¥irv 1
ni
] ant main 00
1 a 0
10 | sta: reout << "Hello, world! 1
0 i
0 0 0 1 4 0
] 1 1 " 1 11
ESTEE Notice that Code:stocks has automaticalveréated | ERTIEABR) That's all you need to door the moment. tray
corresponding closing culy bracket a couple of 0 not look erribly amazing but C++ isbest absorbed 0 0
1 ines below, lipking thepap agwellasa slight indentThisisdueto _insmall chunks. Dont execute the code at the moment asyouneed
| the structyre of C++andit’s where the meat of the code isentered. — tolookathow a+ program s structured first; then you can bull
0.0) Nowenter: 4 |» 9 1 andrug the code, For now, click on Save, the single Floppy dsc icon.
Fiwy first C++ program ) 01 ° wa
1 10
0
0
M4
0 °
sn masa) )
o )Sp Coding with c++)
Compile and Execute
You've created your first C++ program and you now understand the basics behind the
Stier oo Mee Lente mane UTC CE Keele Rea
NCoDU Demerol 0) om
GREETINGS FROM C++
Compiling and executing C++ code From Code::Blocks is extraordinarily easy;
the result. Here's how it's done.
Si
‘Open Code::Blocks if you haven't already, and
load up the previously saved Hello World code you
‘created, Ensure that there are no visible errors, suchas missing
semicolons at the end of the std:cout ine.
just a matter of clicking an icon and seeing
Start by clicking on the Build icon, the yellow cog,
[At this point, your code has now been run through
the CodeBlocks compiler and checked for any errors, You can see
the results ofthe Buld by ooking ta the bottom window pane. Any
‘messages regarding the quality ofthe code are displayed here,
Sis}
ESTEE "your code is looking similar to the one in our
screenshot, then look to the menu bar along the top
‘of the screen, Under the Fortran entry in the topmost menu you can
see. group of icons: yellow cog, green play button and a cog/play
button together. These are Build, Run, Build and Run Functions,
eject Bull Debug Fortan waSmith Tools Tooke Plugins DowBloy
xmaliaior soc
fe T_ finclude
2 using namespace sta:
3
4 _ int ming
5 It
é
FM || cont,
using namespace stdi cout << ay
cout << "\n"y
int main() }——— fiocloce
t sing naneapece =?
The cout <<"\n's part
simply placesa nev line
between the output of
toands,
1
Ie:
Finclude
basing namespace sta,
tnt main)
ac
,
ER TeeED St2rt simple by creating twovariables,aand>, with ENTSSIMM Naturally you can declare anew variable, callit
‘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,
brackets, enter: int results
result = a +b:
int a:
int b: cout << result;
— sissies: Geescene: Insert the above into the code as per the screenshot
b=:
sme main
qthis, instead:
1
int b= 5;
int result =a + bs
You can assign avalue toa variable as soon as you
declare it The code you've typed in could look lke
cout << result
declare them:
int a) (10)?
int b (5);
‘Then, from the C++ 2011 standard, using curly brackets
Specific
int result (a4b);
Hinclude
You can create global variables, which are variables
that are declared outside any Function and used in
any Function within the entire code. What you've used so far are
local variables: variables used inside the Function, For example:
using namespace sta
main ()
startLives = st
cout
3
(C++, you can also use the following
to assign values to a variable as soon as you
The previous step creates the varabe States,
Suz? which is a global variable. Ina game, for example,
2 player's go up or down depending on how wellor how bad
theyre doing When the player estate game the Star es
returns tots default states ere we've asgned 3 ves, then
subtracted 1,leoving2 vest
FEED the modern c++ compiler i far more intelligent
than most programmers give it credit. While there
are numerous data types you can declare for variables, you canin
Fact use the auto Feature:
Hinclude
using namespace stds
auto pi = 3.141593;
int maing)
i
double area, radius = 1.51
area = pi * radius * radius:
cout << areas
ESTED DD ® courte of new elements here: fist, auto won't
work unless you go to Settings > Compiler and
tick the box labelled Have G++ Follow the C++11 ISO C++ Language
Standard [std-c++1]. Then, the new data type, double, which
means double-precsion floating point value. Enable C++11, then
build and run the code, The result should be 7.06858.codingth cos
Data Types
Variables, as we've seen, store information that the programmer can then later call up,
ETM Tal oO Lea mete Ue eM TC ed PETES PLAIN TORU Daya Lele Cea eco}
EenTAvel Ueda aod Ngee] clan aime eife Rene ae Konan Kelle B aye Ailey
THE VALUE OF DATA
“There are many different datatypes available forthe programmer
in C+, such as an integer, floating point, Boolean, character and so
on. It's widely accepted that there are seven basic data types, often
called Primitive Bultin Types; however, you can create your own
data types should the need ever arise within your code,
“The seven basic data types are
a
So
De CGe ade
“These basic types can aso be extended using the Following modifiers
Long, Shor, Sianed 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 ofF
2147483648 to 2147483647, afairvalue, you would agree,
Now, iFyou 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 = Oto 65,535
Signed Shi 32768 to 32767
Long int =-2147483647 to 2147483647
‘Signed Long int =-2147483647 to 2147483647
Unsigned Long int = to 4284967295
Naturally you can get away with using the basic type without the
moaifer, as there's plenty of range provided with each data type
However, it's considered good C++ programming practise to use the
‘modifiers when possible.
“There are issues when using the modifiers though. Double
represents a double-floating point value, which you can use for
incredibly accurate numbers but those numbers are only accurate
Upto the fifteenth decimal place. There's also the problem when
displaying such numbers in C+ using the cout function, in that cout
by default only outputs the first five decimal places. You can combat
that by adding a cout precision () function and adding a value inside
the brackets, but even then you're stil imited by the accuracy of the
double data type. For example, try this code:
#include
using namespace std
double PI = 3.1415926535897932384632
se main
cout << PIs
1 include
i
1592653589793238463;
using namespace
double PI = 3
int main)
(cout precision (22):
cout << PIs
Starthere _% DataTypescpp
ere
using namespace std;
double FI = 6 6
cout precision (22);
cont << PI:
‘Again, build and run the code; as you can see from the command,
line window, the number represented by the variable Ps ifferent
tothe number you've told C++ to use in the variable. The output
reads the value of Pas 3.1418926535897931 15998, wth the
numbers going awry from the Fifteenth decimal place.
Cateulator ce
Scientific D
15.142857142857142857142857142857
Dec HYP ORE
Memes
x a sin cos tan
V1 og Mod
+ | ce] c +
tr
i
ON WO
‘hiss mainly due to the conversion from binary in the compiler
and that the IEEE 754 double precision standard occupies 64-its
of data, of which 52-bits are dedicated to the significant (the
significant digits ina Floating-point number) and roughly 3.5-bits
are taken holding the values Oto 9. IF you divide 53 by 3.5, then you
arrive at 15.142857 recurring, whichis 1S-cigts of precision.
Tobe 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++ asthe
Connective tissue between the bwo languages.
You can create your own data types, using an aliascike system called
typedet: For example:
aod
#include
using namespace stdi
typedef int metres;
int main)
metres distance:
distance = 15
cout << “distance in metres is
This code when executed creates a new int data type called metres.
‘Then, in the main code block, there's @ new variable called distance,
\hich isan integer; so you're basicaly telling the compiler that
there's another name forint. We assigned the value 15 to distance
and displayed the output: distance in metres 15.
Itmight sound alittle confusing to begin with but the more you use
C++ and create your own code, the easier it becomes.BD einsvance)
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
language, and are still supported by C++.
To create a string you use the char function. Open a
new C++ file and begin with the usval header:
Si
Hinelude
using namespace std
int main 1)
pert
S8)o> + oom
[resell ICE ©
Finclude
using namespace stdy
Its easy to confuse a string with an array. Here's an
artay, which can be terminated with a nul character:
int main 0)
1
char greet [a] = (0W", "2",
sor}
‘cout << greet << “\n"y
S108
Build and run the code, and Welcome’ appears,
on the screen, While thisis perfectly Fine it's
nota string. Astring is a class, which defines objects that can be
represented as astream of characters and doesn't need to be
terminated like an array. The code can therefore be represented 2s:
‘include
using namespace std
int main ()
‘
char greet} = “welcore",
cout << great << *\n"7
Int there's alsoa string Function, which works in
_much the same way. Using the greeting code again,
STEP 4
you can enter:
Hnclude
using namespace std
int main 0)
‘
string greet = “Welcome”;
cout << greet << "\n"?PEPER) There are also many different operations that you
can apply withthe string Function For instance, to
getthe length ofa string you can use:
ti
using namespace stdi
dude
int main 1)
{
string greet = “Helcone”:
cout << “Me length of the string
cout << grect.size() << “\n"
You can see that we used areet size) to output the
lenath, the number of charactersthere are, of the
contents ofthe string. Naturally, if you call your string something
other than greet, then you need to change the command to reflect
this, k's always stringname.operation. Build and un the code to see
the results
Hinclude
using namespace stdi
You can of course add strings together, or rather
combine them to form longer strings:
int main 4)
(
string greet3 = greet] + greet2;
cout << greets << "\n"y
)
example, we created int length, which stores the result of string.
size() an
Hci:
int ma
nl
eu
sei
Siar)
Just as you might expect, you can mixin aninteger,
{and store something to do withthe string, In this
outputs i to the user:
de
namespace std:
e engths
ring greet = “Hello”;
ring greet2 =“, world!
ring greet = greetl + 91
egth = grest3.oize();
wot <€ “the length of the combined strii
<< length << *\n"?
Using the avalable operations that come with the
string function, you can manipulate the contents of
string. For example, ta remave characters from a string you could se!
finciu:
using
Ant ma
string
strg
inthe st
right, so
theresul
namespace std;
ng eteg ("Here Se a long sentence in a
aa
<< etrg ce ‘nly
erase (10,5);
<< stig << ‘aly
erase (strg.begin() +8)
<< strg << ‘nl
erase (strg.begin()+9, strgvend()=9);
<< strg << "\at?
It'sworth spending some time playing around with
the numbers, which ae the character postions
ing. Occasionally, it can be hit and miss whether you get i
practice makes perfect. Take a look atthe screenshot to see
tof the code.C++ Maths
Oe Sette en en Me aed cao
built-in scope for some quite intense maths. C++ has a lot to offer someone who's
Pray) ale ae Ma nn eel Maer (a eo ali meee ma ee] oR TT eo) aol
rota eluaTe om
C++ = MC?
‘The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the Cr+
Math Library, you can also calculate square roots, powers, trig and more.
ESTERID C**’smathematical operations follow the ESTEE DD Multipiation and division can be applied as suc:
same patterns as those taughtin school, that
multiplication and civision take precedence over adcition and es
subtraction. You can alter that though. For now, create anew Fle ares
and enter: int main ()
(
Hinclude
aoe eee ee) float numbers = 1007
numbers = nurbers * 107 // Tais multiplies 100
int main 0)
by 10
i Y
float nunbers = 100; cout << numbers << “\n"y
numbers“ nunbers + 10; // This adds 10 to the numbers = nunbers / 10; // And this divides
initial 100 1000 by 10
cout << numbers << “\n"s cout << numbers << “\n"?
nonbers = numbers = 107 // This subtracts 10)
from the new 110
cout ce mumbere
#include
using namespace sta
int main ()
ES TeeRD St2rt by getting the square root of a number:
finelude
finclude
using namespace stdi
int main)
t
float number = 1347
cout << “the square root of * << nunbor << *
ist” << sqrt (number) << “\n"7
BETISE RD ere we created a new fat called number and
sed the sart(aumber) Function to display the
square root of 134, the value ofthe variable, number. Build and run
the code, and your answer reads 11.5758,
PETER) The interesting maths content comes when you call
‘pon the C++ Math Library, Within this header are
FERED calculating powers of numbers can be done with
Hinclude
#include
using namespace std;
int main 0
i
float number = 127
cout << nunber << * to the power of 2 is ™
2) << “\n"s
nunber <<" to the power
3)
#include
using namespace std:
int main 0
i
double area, radius = 1.51
area = M.pr* radius * radiuay
cout << area << ™\n"s