an introduction to c++ a complete beginners guide - michael oliver

126

Upload: cttvl

Post on 17-Jul-2015

257 views

Category:

Education


8 download

TRANSCRIPT

Page 1: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 2: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 3: An Introduction to C++ A complete beginners guide - Michael Oliver

C++ProgrammingEssentials

KeyWords

break

case

char

default

do

double

else

float

for

goto

if

int

long

operator

signed

static

switch

unsigned

void

while

DataTypes

char

Asinglecharacter

int

Anintegerisawholenumber

float

Afloatingpointnumber,correcttosixdecimalplaces

double

Afloatingpointnumber,correcttotendecimalplaces

bool

ABooleanvalueoftrue(1)orfalse(0)

string

Agroupofcharacters

Page 4: An Introduction to C++ A complete beginners guide - Michael Oliver

LibraryClasses

<iostream>

Readsandwritestotheconsole

<iomanip>

Manipulatesinputandoutput

<fstream>

Readsandwritestoatextfile

<string>

Storesandmanipulatestextstreams

<sstream>

Convertsstringstootherdatatypes

<vector>

Storesandmanipulatesdatainvectorarrayelements

<stdexcept>

Reportslogicerrorsandruntimeerrors

<ctime>

Reportsdateandtime

Page 5: An Introduction to C++ A complete beginners guide - Michael Oliver

IntroductiontoC++

CreatingyourfirstC++projectinVisualstudio2013

Understandingyour1stC++Program

SolvingErrorsinC++

AnnotatingYourCode

AddingMultipleLineofCode

IntroductiontoVariables

UsingIntegersandCharactersinC++

UsingfloatsinC++

Usingstrings

GettingUserInput

VariableArithmetic

Globalandlocalvariables

Introconditionalstatements

LogicalOperatorsandConditionalstatements

Creatingacalculatorusingconditionalstatements

NestingIf/Elsestatements

IntroductiontoSwitchStatements

Nestingswitch/casestatements

IntroductiontoLoops

Whileloops

Do…WhileLoops

ForLoops

IntroductiontoFunctions

IntroductiontoArrays

ExtensionActivities

TheASCIITable

ASCIITable(Binaryvalues31-127)

Glossary

FurtherReading

Page 6: An Introduction to C++ A complete beginners guide - Michael Oliver

IntroductiontoC++C++wasdevelopedbyBjarneStroustrupofAT&TBellLaboratoriesintheearly1980’s,andisbasedontheClanguage.Thenameisapun-“++”isasyntacticconstructusedinC (to increment a variable), andC++ is intended as an incremental improvement ofC.MostofC isasubsetofC++,so thatmostCprogramscanbecompiled(i.e.convertedintoaseriesoflow-levelinstructionsthatthecomputercanexecutedirectly)usingaC++compiler.

C++isconsideredtobeamultiparadigmlanguage,asthewayitcanbeimplementedcanvary. This book will cover C++ as a procedural language, and conforms to the ANSI(American national standard institute) and ISO (International standards organisations).This means that you can take all the source code from this book, and run it in anycompiler.

Tobeabletosuccessfullyrunthesourcecodeinthisbookyouwillneedthefollowing:

Acomputer(Windows,OSx,Linux)AnIDE(Integrateddevelopmentenvironment)

Windows(VisualStudio)OSx(Xcode)Linux(CodeBlocks)

Forafreeversionofthissoftware,thenpleasevisitwww.bcotcomputing.co.uk

AllsourcecodeinthisguidehasbeenimplementedusingVisualStudio2013professionalandcanbefoundon theschool’swebsite.Thissoftwarehasbeen installedonallof themachinesintheschoolofcomputerofscience.Itcanalsobedownloadedforfreeusingyourdreamssparkaccountbyclickingthislink

Page 7: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 8: An Introduction to C++ A complete beginners guide - Michael Oliver

CreatingyourfirstC++projectinVisualstudio2013This guide has been created to show how to setup, create and compile your first C++program“Helloworld”.

Before you begin to code your program, you will need to load up an IDE (Integrateddevelopmentenvironment)Todothisclickthestarticon ,andtypevisual.Youshouldseethefollowing:

Click “Visual Studio 2013” and the Visual Studio loading screen will appear on yourdesktop:

Aftertheloadingscreen,theVisualStudiostartpageshouldload.Inthisscreenyoucancreate new projects, open existing projects or even access guidance and resources. Tocreateanewprojectweneedtoclick“newproject”.

Onceyouclickonnewproject,youwillbepresentedwithanewwindow(Seebelow)inthelefthandpaneyouwillaseriesofprogramminglanguages.BydefaultvisualC++will

Page 9: An Introduction to C++ A complete beginners guide - Michael Oliver

be displayed as themain language.Under visualC++ youwill see an option “win32”,click this option to be presentedwith “win32 console application”. Click this and giveyourprojectthenameof“helloworld”

Page 10: An Introduction to C++ A complete beginners guide - Michael Oliver

Once you have named the project, click next and you will be presented with a win32Applicationwizard.Toproceedclicknext.

On this screenyouneed toensure the radiobuttoncalled“consoleapplication” ischeckedand thecheckbox“emptyproject”isalsochecked.Oncethishasbeencompleted,clickfinish.Ifyoufailtodothispartcorrectlyyouwillhavetostartyourprojectagain.

Yourwizardwillhaveclosed,andyouwillhavebeenbroughttothemainscreenwhichshowsyou,yourprojectfiles.Atthemoment,wehaven’tgotanyactiveC++files.Soyouwillneedtocreateonebeforewecanbegincoding.

Page 11: An Introduction to C++ A complete beginners guide - Michael Oliver

Clickfile>new>file,toaddanewfiletoyourC++project,orpressctrl+N.

Page 12: An Introduction to C++ A complete beginners guide - Michael Oliver

Youwillcometoanewwindowthatwillrequireyoutochoosethefiletypeneededaspart of your project.ChoosevisualC++ in the left handpane (Default) and then select“C++file”.Thenclickopen,whichwillcreateanewfileandopeninyourproject.

Your nearly there, your file has nowbeencreated,butweneedtosaveittotherightlocationotherwiseanycodeplacedinsideyourfilewillnotwork.

Tomovethefiletothecorrectlocation,clickfile,andatthebottomofthemenuwillbeanoption called “Move source1.cpp into”, move your mouse over this option and a newmenu,willappearcalled“1HelloWorld”.SelectthisoptiontomoveyourC++fileintothecorrectlocation.

Page 13: An Introduction to C++ A complete beginners guide - Michael Oliver

Youwill be prompted to name yourC++ file before you save it.Give it a name that’srelevanttoyourprogram,butdonotgiveitthesamenameasyourprojectasyoucouldrunintoanerrorswhencompilingit.

Welldone,youhavenowsuccessfully setupyourC++ file, and it’snow ready tocode.Youwillhavenoticedthatthefilestructureinthelefthandsidepane,willnowhaveyournewlynamedC++fileinit.

NowyouarereadytocodeandcompileyourfirstC++Program

Now let’s codeyour firstprogram inC++.Using theC++sourcecodebelow, copy thecodeintoyourownHelloWorldProject.

//MyfirstC++program

#include<iostream>

usingnamespacestd;

intmain()

{

cout<<“Helloworld”<<endl;

return0;

}

Page 14: An Introduction to C++ A complete beginners guide - Michael Oliver

Onceyouhaveenteredthiscodewearereadytocompiletheprogram.Thiscanbedonebypressingctrl=F5andclickingokinthedialogboxthatappears.

Page 15: An Introduction to C++ A complete beginners guide - Michael Oliver

Oncethisisdonethentheconsolescreenwilldisplaywithyourfirsthelloworldprogram.

WelldoneyouhavesuccessfullycompletedyourfirstC++program.Gotanerrorortheprogramdidn’trun.Checktheerrorboxandreviewtheerrormessages.

Theerrorboxcanbefoundinbyusingthetoolbaratthetop,view>

Allerrorswill appear in theerror list,whichwill automaticallyappearandgiveyouanerrormessage.Inthiscasetheerrorisonline9,whichismissingthe;afterthe<<endlcode.

Page 16: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 17: An Introduction to C++ A complete beginners guide - Michael Oliver

Understandingyour1stC++ProgramNowthatyouhavesuccessfullycreatedyourfirstC++programcalled“HelloWorld”,let’slook at the structure of your program, and break down the code bit by bit. Letslook atthe“HelloWorld”programbelow.

//MyfirstC++program

#include<iostream>

usingnamespacestd;

intmain()

{

cout<<“HelloWorld”<<endl;

return0;

}

//MyfirstC++program

Thisisasinglecommentlinewhichhasnotaffectontheperformanceofaprogram.Weusecommentstoannotateourcode,toexplainwhattheprogramdoes.Therearetwowaystodisplaycomments (//) is used for a single line.Towrite a descriptionof a particularprogramorsourcecode,youmaywishtogooverseverallinesofcode.Todothisweuse(/**/)

#include<iostream>

Inprogrammingweuseadirective that tells thecompiler (Visual studio)how it shouldprocess its input.Directivescanvaryfromcompiler tocompilerand behavedifferentlyandareprocessedbyapre-processor.Apre-processorisaprogramthatprocessesitsinputdata, to produce an output. Different languages use different pre-processor, but in Clanguages,themostcommonispre-processor,takeslinesstartingwith#asdirectives.Theabove#include<iostream>tellsthepre-processorofthecompilertoincludetheiostreamstandardfile.Thisfileincludesthefundamentaldelectationsoftheinput-outputlibraryinC++.WithoutthisyourC++wouldnotcompile.

usingnamespacestd;

All the elements of the standard C++ library are declared within what is called anamespace, thenamespacewith thenamestd.So inorder toaccess its functionalitywe

Page 18: An Introduction to C++ A complete beginners guide - Michael Oliver

declarewiththisexpressionthatwewillbeusingtheseentities.ThislineisveryfrequentinC++programsthatusethestandardlibrary.

intmain()

This linecorresponds to thebeginningof thedefinitionof themain function.ThemainfunctionisthepointbywhereallC++programsstarttheirexecution,independentlyofitslocationwithinthesourcecode.Itdoesnotmatterwhetherthereareotherfunctionswithothernamesdefinedbeforeor after it - the instructions containedwithin this function’sdefinitionwillalwaysbethefirstonestobeexecutedinanyC++program.Forthatsamereason,itisessentialthatallC++programshaveamainfunction.

Thewordmainisfollowedinthecodebyapairofparentheses(()).Thatisbecauseitisafunctiondeclaration:InC++,whatdifferentiatesafunctiondeclarationfromothertypesofexpressionsaretheseparenthesesthatfollowitsname.Optionally,theseparenthesesmayenclosealistofparameterswithinthem.

Rightaftertheseparentheseswecanfindthebodyofthemainfunctionenclosedinbraces({}).Whatiscontainedwithinthesebracesiswhatthefunctiondoeswhenitisexecuted.

cout<<“HelloWorld”<<endl;This line is aC++ statement.A statement is a simpleor compound expression that canactually produce some effect. In fact, this statement performs the only action thatgenerates a visible effect in our first program. cout is the name of the standard outputstream in C++, and the meaning of the entire statement is to insert a sequence ofcharacters(in thiscase theHelloWorldsequenceofcharacters) into thestandardoutputstream (cout, which usually corresponds to the screen). cout is declared inthe iostreamstandardfilewithin thestdnamespace,so that’swhyweneeded to includethatspecificfileandtodeclarethatweweregoingtousethisspecificnamespaceearlierinourcode.

Notice that the statement endswith a semicolon character (;). This character is used tomarktheendofthestatementandinfactitmustbeincludedattheendofallexpressionstatementsinallC++programs(oneofthemostcommonsyntaxerrorsisindeedtoforgettoincludesomesemicolonafterastatement).<<endl;isusedaftertheoutputstatementtomove any other statements onto its own separate line of the output window. As seemaboveintheoutputwindow“Pressanykeytocontinue”isonitsownseparateline.Ifthe<<endl;wasremovedthentheoutputstatement“helloworld”wouldbeonthesamelineas“pressanykeytocontinue”.

return0;

The return statement causes themain function to finish. Returnmay be followed by areturncode(inourexampleisfollowedbythereturncodewithavalueofzero).Areturncodeof0forthemainfunctionisgenerallyinterpretedastheprogramworkedasexpectedwithoutanyerrorsduringitsexecution.ThisisthemostusualwaytoendaC++console

Page 19: An Introduction to C++ A complete beginners guide - Michael Oliver

program.

Page 20: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 21: An Introduction to C++ A complete beginners guide - Michael Oliver

SolvingErrorsinC++

WhenyoubegincodinginC++,youwillnoticethatyoumaymakeseveralerrorsinyourcode,suchasmissingthesemi-colon(;)orusinguppercaseletterswheninfactyoushouldbeusinglowercase.Thebestwaytobecomefamiliarwithanylanguageistopracticerectifyingerrorsinthecode.

Activity2:Solvingerrors

Below is aC++ program,which has 7 errors. Create a new project and copy the codebelow intoyournewproject and resolve the issues.HINT:use the code fromyour firstprogramtohelp.Onceyouhavefinished,saveandcompileyourprogram.

#include<Iostream>usingnamespacestd;intMain(){Cout<“PleaseFixmyErrors“<<endlReturn0;};

ToviewyourerrorsinC++,youcanusethebuiltinerrortool,whichtellsyouwheretheerrors have occurred within your program. To access this tool, click view on the toptoolbarandselecterrorlist.Doubleclickoneacherrorinthislisttobetakentothelineofcodewheretheerrorhasoccurred.

Page 22: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 23: An Introduction to C++ A complete beginners guide - Michael Oliver

AnnotatingYourCode

When you code in any programming language, it’s extremelyimportant that you use comments to explain what is happening. This is so that otherprogrammers,canunderstandyourcodeandwhatyourprogramistryingtoachieve.

Activity3:Annotatingyourcode

Below is a C++ program that shows you how to use comments. Create a new projectcalled“comments”andcopythebelowprogram,saveandcompilethecode.

#include<iostream>

usingnamespacestd;

intmain()

{

//Thisishowyouaddacommentontoasingleline

/*Thisishowtoaddacommentovermultiplelines.Thecompilerwillnotreadthis.Commentsareusedtoannotateyourcode*/

cout<<“HelloWorld”;

return0;

}

Itwillbeexpectedthatasyouprogressthroughtheworkbook,thatyouwillberequiredtoannotateallofyourprograms.

Page 24: An Introduction to C++ A complete beginners guide - Michael Oliver

YouhaveseenthreeC++programs,nowit’stimetotryityourself.CreateaC++programthatprintsoutyournameontothescreen.Youcanusethepreviousprogramsasaguide,buttrydoingwithoutlooking.

Don’tforgettoannotateyourcodeusingyourcomments!!

Page 25: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 26: An Introduction to C++ A complete beginners guide - Michael Oliver

AddingMultipleLineofCodeNowthatyouhavecodedyourfirstsimpleC++program,let’slookatmakingitabitmorecomplex,byaddingmorelinesofcode.

Activity4:AddingMultiplelinesofcode

CreateanewC++projectcalled“multiplelines”,andusingthecodebelow,copythecodeintoyourprogram,thensaveandcompileyourprogram.

#include<iostream>

usingnamespacestd;

intmain()

{

cout<<“Thisisline3”<<endl;//endlisusedtoplacethecodeonanewline

cout<<“Thisisline5\n”;//\nisanotherwayofputtingthecodeontoanewline

return0;

}

You will have noticed that you have used (/n) and (<<endl) toprintthecodeontoanewline.AsyoucontinuetolearnC++youwillchooseamethodthatissuitedtoyourprogrammingstyle.Thereisnowrongorrightway,justthewaythatsuitsyou.

Thisbookwilluse<<endlthroughout,butyoucanchangethistosuityourneeds.

Page 27: An Introduction to C++ A complete beginners guide - Michael Oliver

Nowthatyouknowhowtoprintcodeonseparateline,createaC++programthattellsthestoryofthethreelittlepigsandthebigbadwolf.

Yourcode,willneedtocompileandyouwillneedtoannotatethekeypartstoyourcode.

Page 28: An Introduction to C++ A complete beginners guide - Michael Oliver

IntroductiontoVariablesVariablesare temporarystorage thatexistas longas theyneed to, thenaredisposedof.Imagineacalculator,thenumbersyouinputarestoredinthecalculatoruntilyouusetheclearbuttonorturnthecalculatoroff,thenthevaluesaregone.Variablesarestoredinthemain memory of a computer system, and given a unique address so that they can beaccessedbythecompileratanytime.

Variables aredeclaredby the typeof data to be expected, such as number, a letter or asentence.Declaring thedata type is essential to ensure that the correctmachinecode isgeneratedbythecompilertobeusedbytheCPU(CentralprocessingUnit).

WhatDatatypescanavariablehold?Integers(int)Anintisshortforanintegerwhichisawholenumbersuchas0,1,2,3,4,5,6,7,8,9etc.Theycan be both signed (negative) and unsigned (positive). Integers can range in sizedependingonthetypeofintegerthatisbeingused.

Characters(char)A charwhich is short of character is a data type that can hold single letter, symbol ornumbersuchas‘A’,‘b’,‘@‘,‘$’,‘1’etc.Asimplecharwilluseatleast1byte(8bits)ofstoragespace.

Float(Decimal)Afloat,whichisshortforfloatingpointnumberisawayofstoringanumber,whichhasadecimalplacesuchas3.2,6.8,7.1etc.Dependingonthetypeoffloatusedwilldependontheir precision. There are two types of floating point numbers which are Floats anddoubles.DoubleshaveagreaterprecisionandgenerallythepreferabledatatypetobeusedwithinaC++program.

StringsStrings are very powerful and used to not only store words, but are used to store acombination of words and numbers. Strings are useful when you want to captureinformationsuchas thefullnameof theperson(Firstnameandsurname)streetaddressetc.

Boolean

BooleaninC++isknownasbool,whichisrepresentedineithertwostates;trueorfalse.Youmaysee that thisdata type isusedwithbinarynumbers, thisagainreflects the twostatesofBoolean.0=falseand1=true.

Page 29: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 30: An Introduction to C++ A complete beginners guide - Michael Oliver

DeclaringVariablesinC++

To declare a variable in C++, we need to declare the type of data that we expect thevariabletohold,thiscanbedonebytypingthedatatypenamein,asshownbelowinthetable:

Datatype’s:Howtodeclare

Integer

int

Float

double

Character

char

string

string

Float

float

Boolean

bool

WhenyoutypethedatatypeinC++,youwillnoticethatthetextwillchangecolour,thisistoshowthatitwillbeusedbythecompilerforavariableassignment.

Onceyouhavechosenthedatatypeforyourvariable,youwillneedtoassignitaname.Youcannamethevariableanythingyoulike,aslongasyoufollowtherules:

VariableNameRules

Whenvariablesarecreated,yougivethemanamesuchasnum1,housename,fname,etc.Variablesareveryflexiblewithnames,however therearesomegoldenrules tocreatingthem:

AVariable name consists of any combination of alphabets, digits and underscores.Somecompiler allowsvariablenameswhole length couldbeup to247characters.Stillitwouldbesafertosticktotheruleof31characters.Pleaseavoidcreatinglongvariablenameasitaddstoyourtypingeffort.Allvariablenamesmustbeginwithaletterofthealphabetoranunderscore(_).Forbeginningprogrammers,itmaybeeasiertobeginallvariablenameswithaletterofthealphabet.ThefirstcharactermustnotbeanumberoranyspecialsymbolAfterthefirstinitialletter,variablenamescanalsocontainlettersandnumbers.Nospacesorspecialcharacters,however,areallowed.Uppercase characters are distinct from lowercase characters. Using all uppercaselettersisusedprimarilytoidentifyconstantvariables.YoucannotuseaC++keyword(reservedword)asavariablename.

Examplesofvariablesbeingassignedintnum1;//num1isthevariablenameIhavechosenwhichexpectsanintgerdatatype.floatnum2;//num2isthevariablenamechosenwhichexpectsafloatdatatype.

Page 31: An Introduction to C++ A complete beginners guide - Michael Oliver

charletter;//letteristhevariablenamechosenwhichexpectsachardatatype

stringname;//nameisthevariablenamechosenwhichexpectsastringormorethanone.

Page 32: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 33: An Introduction to C++ A complete beginners guide - Michael Oliver

UsingIntegersandCharactersinC++Inthispartof theprogramwearegoingtocreateaC++programthat isusedtostoreasimplewhole number (Integer) in the program.Wewill declare a variable that uses anintegerdatatype,andinitialiseitwithapresetvalue.

Activity5:UsingIntegers

CreateanewC++programbelowcalled“myfirstvariable”andenterthefollowingcode:

To savelinesofcode,youcandeclareandinitialiseavariableonthesamelineofcodeasshownbelow:intnum=10;//variablethathasbeendeclaredandinitialised

Activity5b:UsingCharacters

Now thatyouhavecreatedaprogram thatuses avariable integerhowabout creatingavariablethatusesachar(character).BelowisanotherC++programthatshowsyouhowtodeclareachar inC++.CreateanewC++programcalled“Mysecondvariable”, andenterthebelowcode:

#include<iostream>

usingnamespacestd;

intmain()

{

charletter=‘A’;//charvariabledeclaredandinitalised

cout<<“Myletteris:”<<letter;//printsoutmyletter

return0;

}

Page 34: An Introduction to C++ A complete beginners guide - Michael Oliver

Didyounotice,thatwedeclaredandinitialisedtheletter‘A’onthesameline?Againthisreducestheamountofcodeyourprogramhas.DidyoualsonoticethatA,wasinitialisedinsinglequotationmarks(‘A’).ThistellsthecompilertousetheASCIIvalueofA,IfyoutrytodeclareAwithoutthesinglequotationmarksitwillpresentyouanderrorasitsseenasan“Undeclaredidentifier”.

TheASCIItablewillplayahugepart inyourC++andcanbefoundat thebackofthisbook.

Sofar,youhavebeenable todeclareand initialisean integerandachar inC++.UsingthesetwodatatypesonlycreateaC++programthatstoresavarietyofcharsandintegersinseveraldifferentvariables.

Thisprogramisentirelyup toyouhowyoustructure it,but itmustcompileandall thecodemustbeannotated.

Page 35: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 36: An Introduction to C++ A complete beginners guide - Michael Oliver

UsingfloatsinC++WearenowgoingtolookatFloatsinC++andseehowtheycanbeimplemented.Floatsareused toshownumbersafter thedecimalplace.Dependingon the typeof floatused,will depend on the precision (how many numbers are after the decimal point). ForexampleusingthefloatinC++canshowupto7placesafterthedecimalpoint,whereadoublecanshowupto16.Thetwoprogramsdemonstratethis.

Activity6

Create a new C++ program called “My Float” andcopythecodebelow,compileandrun.

#include<iostream>

usingnamespacestd;

intmain()

{

floatnumber1=3.123456789;

doublenumber2=3.123456789;

cout<<number1<<endl;

cout<<number2<<endl;

return0;

}

Furtherreadingandonfloatingpointnumberscanbefoundhere

Activity7–UsingMultiplevariables

Page 37: An Introduction to C++ A complete beginners guide - Michael Oliver

CreateanewC++called“MultipleVariables”andcopythebelowcode:

#include<iostream>

usingnamespacestd;

intmain()

{

charletter;letter=‘A’;//declaredvariableandtheninitialised

intnumber;number=100;//declaredvariableandtheninitialised

floatdecimal=7.5;//declaredandinitialised

doublepi=3.14159;//declaredandinitialised

boolisTrue=false;//declaredandinitialised

cout<<“Charletter:“<<letter<<endl;

cout<<“intnumber:“<<number<<endl;

cout<<“floatdecimal:“<<decimal<<endl;

cout<<“doublepi:“<<pi<<endl;

cout<<“BoolisTrue:“<<isTrue<<endl;

return0;

}

Page 38: An Introduction to C++ A complete beginners guide - Michael Oliver

UsingstringsStringsareusedwhenyouneedtostoredatathatcontainsmorethanonecharactersuchasaname,emailaddress,orpostcode.StringsaredifferenttoallotherdatatypesinC++,asyouhavetocallanewprogramminglibrary.

Activity8–UsingStrings

In this program you are going to create your first C++ program that displays “Helloworld”inastringvariable.CreateanewC++programcalled“introtostrings”,enterthecodebelowandcompiletheprogram.

#include<iostream>

#include<string>//thenewstringheaderhastobeusedorstringwillnotwork.

usingnamespacestd;

intmain()

{

stringhello=“HelloWorld”;

cout<<“Pleaseenteryourfirstname:“<<endl;

cout<<hello<<”WelcometoC++”<<endl;

return0;

}

Ifyouwanted tostoreacombinationofwordsand letters into thesamevariable, ratherthanusingastring,youcoulduseaCharArray.ArraysarecoveredtowardstheendofthisguideandisthestartofintermediateC++.

Another program below has been included to show how two separate strings can beconcatenatedtogethertoformonestring.

#include<iostream>

#include<string>

usingnamespacestd;

intmain()

{

Page 39: An Introduction to C++ A complete beginners guide - Michael Oliver

stringfirstname=“Frodo“;

stringsecondname=“Baggins”;

stringfullname;

fullname=firstname+secondname;//exampleofconcatenation

cout<<“Firstname:“<<firstname<<endl;

cout<<“Secondname:“<<secondname<<endl;

cout<<“Yourfullnameis:“<<fullname<<endl;

return0;

}

Page 40: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 41: An Introduction to C++ A complete beginners guide - Michael Oliver

GettingUserInputTherewillbetimeswhereyouwillneedtogettheusertoinputsomeformofdataintoyourprogram,thatyoucanuseeitheruseforconditionalstatementsandloopsorifyourwritecertaininstructionsoutontothescreen.

To gather input we need to use the “cin>>” command followed by the name of thevariablethatwillbeholdingthedata.Forexamplecin>>name;

Activity7–Userinput(Integer)

In this program you are going to create a C++ program that allows a user to input anumberanddisplaythatnumberbackoutonthescreen.CreateanewC++projectcalled“intgerinput”andenterthebelowcode,compileandrun.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum;

cout<<“Pleaseenteranumber”;

cin>>num;

cout<<“Youentered“<<num<<endl;

return0;

}

Activity8–Userinput(String)

In the belowprogramyouwill create a program thatwill allowa user to enter a name(withoutspaces)anddisplayitbackouttotheuser.Enterthecodebelow,save,compileandrun.

#include<iostream>

#include<string>//thenewstringheaderhastobeusedorstringwillnotwork.

usingnamespacestd;

intmain()

{

stringname;

Page 42: An Introduction to C++ A complete beginners guide - Michael Oliver

cout<<“Pleaseenteryourfirstname:“<<endl;

cin>>name;

cout<<“Hello“<<name<<”WelcometoC++”<<endl;

return0;

}

Page 43: An Introduction to C++ A complete beginners guide - Michael Oliver

Nowthatyouknowhowtodeclarevariables,allowuserdatainputanddisplaytheresultsback out to the user it’s time to create your own C++ program that captures userinformation.Yourprogramwillneedtocapturethefollowingdata:

Firstname,Surname,Age,Housenumber,1stlineofaddress,CityStatePostcode

Youcanusepreviousexercisestohelpyoudesignthisprogram.Inthisprogramyouwillexpectedtodothefollowing:

UsecommentstoexplainyourcodeIndentyourcodecorrectlyUsethecorrectvariabletypeandappropriatevariablenames

Asanextensiontothisexerciseconcatenatethetwostringvariablesusedtoholdthefirstandsecondnameintoonestring,sothatitcanbeprintedoutononeline.

Page 44: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 45: An Introduction to C++ A complete beginners guide - Michael Oliver

VariableArithmeticVariableArithmetic:What is arithmetic?Arithmetic ismath, calculating the sumof arangeofnumbers.Forexampleyoucanaddtwovariablestogetherandstoretheanswerinanewvariable.

Activity9-Addition

InthisactivityyouwillbecreatingaC++programthataskstheusertoentertwonumbersandtheprogramwilladdthenumberstogetherandproducethetotalamount,whichwillbedisplayedonthescreen.Createaprojectcalled“VariableMaths”save,compileandrunthebelowcode.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum1,num2,sum;

//additionprogram

cout<<“Pleaseenteryourfirstnumbertoadd:“;

cin>>num1;

cout<<“Pleaseenteryoursecondnumbertoadd:“;

cin>>num2;

sum=num1+num2;//addvariablenum1andnum2,andstorenewnumberinvariablesum

cout<<num1<<“+”<<num2<<“=”<<sum;

return0;

}

Activity10-Multiplication

Thebelowprogram,isamultiplicationprogramthatmutliplystwonumberstogether,anddisplaystheresult.Createanewprojectcalled“Multiplication”andcode,save,compilethebelowcode.

#include<iostream>

usingnamespacestd;

Page 46: An Introduction to C++ A complete beginners guide - Michael Oliver

intmain()

{

intnum1,num2,sum;

cout<<“Pleaseenteryourfirstnumbertoadd:“;

cin>>num1;

cout<<“Pleaseenteryoursecondnumbertoadd:“;

cin>>num2;

sum=num1*num2;//timesvariablenum1and2,andstorenewnumberinvariablesum

cout<<num1<<“x”<<num2<<“=”<<sum;

return0;

}

Activity11–PeasinaPod

Createanewprojectcalled“PeasandPods”andenterthebelowcode.

Enter the following program, making sure that intentional errors introduced arecorrected.Thecaseofalllettersmustbecopiedasshown.

Save,compileandruntheprogram.

#include<iostream>

usingnamespacestd;

intmain()

{

intnumber_of_pods;

intpeas_per_pod;

inttotal_peas;

cout<<“Enterthenumberofpods:\n”;

cin>>number_of_pods;

cout<<“Enterthenumberofpeasinapod:\n”;

cin>>peas_per_pod;

total_peas=number_of_pods*peas_per_pod;

cout<<“Ifyouhave“;

Page 47: An Introduction to C++ A complete beginners guide - Michael Oliver

cout<<number_of_pods;

cout<<”peapods\n”;

cout<<“and“;

cout<<peas_per_pod;

cout<<”peasineachpod,then\n”;

cout<<“youhave“;

cout<<total_peas;

cout<<”peasinallthepods.\n”;

return0;

}

Now that you have successfully compiled the aboveprogram, youwill need to try and shorten the program, by reducing the lines of code.Based on previous examples shown in the guide so far, shorten the code above onto afewerlinesaspossible.

Page 48: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 49: An Introduction to C++ A complete beginners guide - Michael Oliver

GlobalandlocalvariablesWe know how to use variables, but so far you have bene using local variables. Localvariables are variables that are declared within side a function, and are made onlyavailable to that function. The other type of variable is a Global Variable, which isdeclaredoutsideafunctionandismadeavailabletoallfunctionsinaC++program.

Global variables are useful, but the value they hold can easily be manipulated by thedifferent functions that use them. Many developers avoid using global variables andinsteadpassdatafromonefunctiontoanothertoavoidthedatabeinglost.

Activity12–GlobalandLocalVariables

Inthisprogram,wearegoingtodeclareoneglobalvariable,andtwolocalvariables.Oneof these variableswill be a standard local variable and the otherwill be declared as aconstant.A constant is a variable thatmust have a value initialised before the programruns, and its valuewill remain the same throughout the program.Constants can’t havetheirvaluechangedatruntime.

#include<iostream>

usingnamespacestd;

intnum1;//Iamaglobalvariable,IcanbeusedbyanyfunctionwithinC++

intmain()

{

constintnum2=5;//Iamaconstantlocalvariable.Icanbeusedwithinthisfunctiononlyandmyvaluewillneverchange.

intnum3;//Iamalocalvariableandcanonlybeusedwithinthe“main”function

cout<<“Pleaseenteranumberforglobalvariablenum1:“;

cin>>num1;

cout<<“Wearegoingtoadd“<<num1<<“toourconstantvariable,whichhasthevalueof5”<<endl;

cout<<num1<<”+“<<num2<<”=“<<(num3=num1+num2)<<endl;

return0;

}

Page 50: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 51: An Introduction to C++ A complete beginners guide - Michael Oliver

IntroconditionalstatementsConditional Statements: A condition statement in C++ is when we check to see if acertainconditionhasbeenmet.Conditionstatementsaregreat,whenyouwanttodisplaydifferent resultsdependingonwhat theuserselects. Inprogrammingacondition isalsoknownasif/elsestatements.Inthisexerciseyouwillcoverif/elsestatements.

Theyarealsoagreatwaytochangethedirectiondependingonwhattheuserselects.Inprogramming a condition is also known as if/else statements. In this exercise youwillcover if/elsestatements.Conditional statementscanhavemultipleconditions,whicharetestedinorder.

Anexampleofanconditionalstatementis:

IfJoshuaeatsallhisdinner,thenhecangooutandplay.Ifnotthenhemustgotidyhisroom.DependingontheresultofJoshuaeatinghisdinnerwithdependontheoutcome.

IFJoshua=EatAlldinner

Thengooutandplay

Thisiscondition1

ElseIFJoshua=doesn’teathisdinner

ThenTidyyourroom

Thisiscondition2

In this section of C++ you will be introduced to new symbols that you will need tofamiliariseyourselfwith.Thetablebelowexplainsthesesymbols.

==

Equaltoo

&&

and

!=

NotEqualtoo

||

Or

>

GreaterThan

>=

Morethanandequaltoo

<

Lessthan

<=

Lessthanandequaltoo

Page 52: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 53: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity13:

Inthisactivitywearecreatingasimpleifstatementwhereauserispromptedtoenteranumberbetweenunder10.Thisprogramhas twooutcomes/condition,dependingon thenumberthattheuserenterswilldependonwhatconditionbecomestrue.

CreateanewC++projectandcall it“conditionstatements”.Enter thebelowcode,saveandcompiletheprogram.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum;

cout<<“Pleaseenteranumberunder10:“;

cin>>num;

if(num<=10)//outcome1

cout<<“Yournumberwas10orless”;

else//outcome2

cout<<“Yournumberwasgreaterthan10”;

return0;

}

WelldoneyouhavejustcreatedyourfirstC++programthatusesaconditionstatements.

In the next exercise youwill learn how to code a C++withmore than two outcomes,whichcandevelopasolutioniftheuserentersanumberof10.

CreateaC++programthatusesaconditionalstatementforateacherwhowantstoknowwhat action shouldbe taken for a studentwhohas not completed their homework.Theprogramwillneedtobecalled“TeacherProgram”andhavetwoconditions:

Page 54: An Introduction to C++ A complete beginners guide - Michael Oliver

The1stconditionbeingifthestudentdoesthehomeworkThe2ndconditionbeingifthestudenthasn’tdonetheirhomework.

Note:ThisprogramwillneedtouseaChardatatypetochecktheconditionnotaninteger

Page 55: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity14

InthisactivityyouaregoingtocreateaC++programthat testsformultipleconditions,using ifandelse ifstatement’s.CreateanewC++Projectandcall it“else ifstatement”andEnterthefollowingcodebelow,save,compileandrun.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum;

cout<<“Pleaseenteranumberbetween1and5:“;

cin>>num;

if(num==1)

{

cout<<“Yourenteredthenumber1”<<endl;

}

elseif(num==2)

{

cout<<“Yourenteredthenumber2”<<endl;

}

elseif(num==3)

{

cout<<“Yourenteredthenumber3”<<endl;

}

elseif(num==4)

{

cout<<“Yourenteredthenumber4”<<endl;

}

elseif(num==5)

{

cout<<“Yourenteredthenumber5”<<endl;

}

Page 56: An Introduction to C++ A complete beginners guide - Michael Oliver

return0;

}

Using theabovecodeasaguidecreateaprogramthat tells theuser that theypressedaspecificsetofletters‘Q’,‘W’,‘E’,‘R’,‘T’,‘Y’.

RememberthatwhenusinglettersinC++thathaveanimpactonthestateoftheprogramthattheyneedtobeinsinglequotationmarks,asseenabove.

Page 57: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 58: An Introduction to C++ A complete beginners guide - Michael Oliver

LogicalOperatorsandConditionalstatementsThe logical operators&& and || are usedwhen evaluating two expressions to obtain asingle relational result. The operator && corresponds with Boolean logical operationAND.Thisoperationresultstrueifbothitstwooperandsaretrueandfalseotherwise.Thefollowingpanelshowstheresultofoperator&&evaluatingtheexpressiona&&b:&&(AND)OPERATOR

a ba

&&b

true true true

The&&operatorisusedifyouwanttocheckifmultipleconditionshavebeenmet.Forexample.IfJoshuaeatshisdinner(A)anddoeshishomework(B)hecangooutandplay.

UnlessbothAandBaretrue,thenthestatementisfalse

true false False

false true False

false false False

Theoperator||correspondswithBooleanlogicaloperationOR.Thisoperationresultstrueifeitheroneofitstwooperandsistrue,thusbeingfalseonlywhenbothoperandsarefalsethemselves.Herearethepossibleresultsofa||b:||(OR)OPERATOR

a b a||b

true true true

The||operatorisusedtocheckifanyconditionhasbeenmet,despitetheotherstatements.Forexample.IfJoshuaeatshisdinner(A)ordoeshishomework(B)thenhecangooutandplay.

IfAorBistruethen,thenthestatementistrue.

true false True

false true True

false false False

TheOperator!istheC++operatortoperformtheBooleanoperationNOT,ithasonlyoneoperand, locatedat its right, and theonly thing that itdoes is to inverse thevalueof it,producingfalseifitsoperandistrueandtrueifitsoperandisfalse.Basically,itreturnstheoppositeBooleanvalueofevaluatingitsoperand.Forexample:

!(5==5)//evaluatestofalsebecausetheexpressionatitsright(5==5)istrue.

!(6<=4)//evaluatestotruebecause(6<=4)wouldbefalse.

!true//evaluatestofalse

!false//evaluatestotrue.

Page 59: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 60: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity15–OROperator

Inthisactivitywewillusethe||(or)operatorssowecantestforeitheroftheconditionsbeingtrue.CreateanewC++projectcalled“ORoperator”andenterthebelowcode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

charanswer;

cout<<“PleaseentertheletterA:“;

cin>>answer;

if((answer==‘A’)||(answer==‘a’))

//herewehavethe==(equal)andthe||(or)inC++

{

cout<<“welldoneyouenteredtheletterA”;

}

else

{

cout<<“YoudidnotentertheletterA”<<endl;

}

return0;

}

Inthisprogram,wecheckedagainstaletteroranumberwehavetousesinglequotation‘A’markstoidentifywhatletterornumberwearelookingfor.Intheaboveprogramwehaveusedthe||(or)operand.Thereasonwehaveusedthisiswearecheckingfor‘A’and‘a’whicharetwodifferentconditions.C++iscasesensitiveso‘A’isdifferentto‘a’.Wehaveusedbracketstoshowtheprogramthedifferentconditionswearechecking.

//condition1OR//condition2

if((answer==‘A’)||(answer==‘a’))

Page 61: An Introduction to C++ A complete beginners guide - Michael Oliver

CreateaC++programthatcheckstheconditionofanumberentered,asktheusertoenteranumbersuchas5OR10.

Ensurethatyourprogramcompilesandrunsthatallcodeisannotated.

Page 62: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity16-ANDOperator

In this activitywewill use the&&operators so you can see howwe can test for bothconditionsbeingtrue.

CreateanewC++Projectandcallit“AndOperators”andenterthefollowingcodebelow:

#include<iostream>

usingnamespacestd;

intmain()

{

intnum1,num2;

cout<<“Pleaseenterthenumber5:“;

cin>>num1;

cout<<“Pleaseenterthenumber3:“;

cin>>num2;

if((num1==5)&&(num2==3))//ifnumber5and3areenteredthenthisstatementisTrue

{

cout<<“Welldoneyouenteredthenumber5and3”;

}

else

{

cout<<“Oopsyoudidntdoasyourtold”<<endl;

}

return0;

}

In this activitywe are checking both conditions to be true.The conditions are the userenteringnumber5and3. If theuserentersnumber5,butenters2 then thestatement isfalse,becausetheyneedtoenterbothnumbers.

//condition1ANDcondition2

Page 63: An Introduction to C++ A complete beginners guide - Michael Oliver

if((num1==5)&&(num2==3))

Page 64: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity17:UsingNotOperators

Inthisactivityweusethe!(NOT)operatorsoyoucanseehowwecantestforaconditionthatisnottrue.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum1;

cout<<“Pleaseenteranynumber,otherthan5:“;

cin>>num1;

if(num1!=5)//ifnumberisNOT5

{

cout<<“Welldonyournumberwasnot5”<<endl;

}

else//ifnumberis5

{

cout<<“Yournumberwas5”<<endl;

}

return0;

}

Youhavecreatedaseriesofprogramthatusesavarietyofconditionalstatements.Nowit’s time to take what you have learnt and put it into practice! Design and build thefollowingprogram:

Youneedtocreateagradingprogramingwherethelecturercanputinagradepercentageandtheprogramwillstatewhatgradethestudentgot.Theoutputscouldbesomethinglikethis

Page 65: An Introduction to C++ A complete beginners guide - Michael Oliver

Excellentyougot90%,yougotDistinctionWelldoneyougot75%,yougotaMeritYougot60%,yougotapass.TryHarder!

Youwillneedtocompileandrunyourprogram,aswellasannotateallyourcode.

Page 66: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 67: An Introduction to C++ A complete beginners guide - Michael Oliver

Creatingacalculatorusingconditionalstatements

Activity18-Creatingacalculator

In this C++youcodeasimplecalculatortoperformanycalculation,copythebelowcodeintoanewprojectcalled“Calculator”,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

floata,b,c;

charm;

cout<<“Doyouwanttoadd(+),subtract(-),multiply(x),ordivide(/)?:”;

cin>>m;

cout<<“Enteranumber:“;

cin>>a;

cout<<“Enterasecondnumber:“;

cin>>b;

cout<<“Theansweris:“;

if(m==‘+’)

{

cout<<(c=a+b)<<endl;

}

elseif(m==‘-‘)

{

cout<<(c=a-b)<<endl;

}

elseif(m==‘x’)

{

cout<<(c=a*b)<<endl;

Page 68: An Introduction to C++ A complete beginners guide - Michael Oliver

}

elseif(m==‘/’)

{

cout<<(c=a/b)<<endl;

}

else

{

cout<<“InvalidSymbol”<<endl;

}

return0;

}

Page 69: An Introduction to C++ A complete beginners guide - Michael Oliver

NestingIf/ElsestatementsNestingisatermwhenweinsertoneobjectinsideanother.Forexampleyoumightcreatea conditional statement and insert a loop or another conditional statement. This is verycommonandsomethingyouwilldoinfutureexercisestocome.

Activity19-NestingConditionalStatements

Inthisactivitywearegoingtobenestingaconditionalstatementinsideanother.CreateanewC++projectandcallit“nestingconditionalstatements”.Copythebelowcode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum1,num2;

cout<<“Pleaseenteranumberbetween0-100“<<endl;

cin>>num1;

if((num1>=0)&&(num1<=50))

{//bracketsmustbeusedasthereismorethanonelineofcodeinthisstatement

cout<<“Yournumberwasbetween0-50”<<endl;

cout<<“Pleaseenteranewnumberunder50”<<endl;

cin>>num2;

if((num2>=0)&&(num2<=50))

cout<<“Welldoneyournumberwasbelow50”<<endl;

else

cout<<“Yournumberwasover50,youdidntlisten”<<endl;

}

elseif((num1>=51)&&(num1<=100))

{

cout<<“Yournumberwasbetween51-100”;

cout<<“Pleaseenteranewnumberbetween50-100”<<endl;

cin>>num2;

if((num2>=50)&&(num2<=100))

cout<<“Welldoneyournumberwasbetween50-100”<<endl;

else

cout<<“Yournumberwasunder50,youdidntlisten”<<endl;

Page 70: An Introduction to C++ A complete beginners guide - Michael Oliver

}

else

cout<<“InvalidNumber”;

return0;

}

If/else statements are not the onlyway to look for acertaincondition.Theotherisoptionistouseaswitch.Thesearecoveredinthenextfewactivities.

Page 71: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 72: An Introduction to C++ A complete beginners guide - Michael Oliver

IntroductiontoSwitchStatementsAswitch statementwhich is also known as a case statement is used to test a conditionagainst a list of values.Each value is called a case.A switch statement is a lot like anif/elsestatementthatyouhaveusedbefore.Switchstatementsaremoreefficientandfastertousethanif/elsestatements.Switchstatementsareidealfortheuseofmenusystems.

Activity20:Creatingyourfirstswitchstatement

Inthisprogramwearegoingtocreateasimplegradingprogramwhereagradeisenteredacomment isoutputted to theuser.CreateanewC++projectcalled“Grade”,enter thebelowcode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

chargrade;

cout<<“PleaseentertheStudentsgrade“;

cin>>grade;

switch(grade)

{

case‘A’:

cout<<“Excellent!”<<endl;

break;

case‘B’:

cout<<“Welldone”<<endl;

break;

case‘C’:

cout<<“Youpassed”<<endl;

break;

case‘D’:

cout<<“Bettertryagain”<<endl;

break;

default:

cout<<“Invalidgrade”<<endl;

}

Page 73: An Introduction to C++ A complete beginners guide - Michael Oliver

cout<<“Yourgradeis“<<grade<<endl;

return0;

}

Tryenteringthevalue‘A’intoyourprogram.Whatwasyourresult?Nowtrytypingthevalue‘a’intotheprogram.Didyougetaninvalidreponse?

Rememberthevalue‘A’andthevalue‘a’arecompletelydifferent.Lets=gobackandamendthecodewehavecreated.

Page 74: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity21:Checkingmultiplecharhctersinaswitchstatement

Usingthepreviousprogram,amendyourcodetolooklikethenewcodebelow.Save,andcompiletheprogram.

#include<iostream>

usingnamespacestd;

intmain()

{

chargrade;

cout<<“PleaseentertheStudentsgrade“;

cin>>grade;

switch(grade)

{

case‘A’:case‘a’:

cout<<“Excellent!”<<endl;

break;

case‘B’:case‘b’:

cout<<“Welldone”<<endl;

break;

case‘C’:case‘c’:

cout<<“Youpassed”<<endl;

break;

case‘D’:case‘d’:

cout<<“Bettertryagain”<<endl;

break;

default:

cout<<“Invalidgrade”<<endl;

}

cout<<“Yourgradeis“<<grade<<endl;

return0;

}

Page 75: An Introduction to C++ A complete beginners guide - Michael Oliver

Tryre-enteringthevalues‘A’and‘a’inagain.Didyounoticethatyougotthesameresult?Well done you have compared the value you have entered against the case of yourprogram.

Activity22:Creatingamenuusingswitchstatements

In this activity youwill use integers to create a simplemenu for a café. Create a newprogramcalled“CaféMenu”andenterthebelowcode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

intchoice;

cout<<“Option1:EatBreakfast”<<endl;

cout<<“Option2:Washupthedishes”<<endl;

cout<<“Option3:Makeadrink”<<endl;

cout<<“Whatwouldyouliketoeat?Pleaseenteranumbertomakeyourchoice“;

cin>>choice;

switch(choice)

{

case1:

cout<<“BaconBap”<<endl;

break;

Page 76: An Introduction to C++ A complete beginners guide - Michael Oliver

case2:

cout<<“Sausageroll”<<endl;

break;

case3:

cout<<“Bowlofporridge“<<endl;

break;

default:

cout<<“invalidchoice”<<endl;

break;

}

return0;

}

So you now have used case statements for both chars and integers, but somethingwasmissingfrombothprograms thatcan improve the readabilityofbothprograms,didyouknow what? To improve the readability and prevent the chances of something goingwrongweshoulduseparentheses{}foreachcase.Soeachcaseshouldlooklikethis:case1:

{

//codehere

break;

}

Go back through both of your programs that use switch statements and place theparenthesesin,ensurethatyoucompileandtesteachprogramtoensurethattheywork.

Page 77: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 78: An Introduction to C++ A complete beginners guide - Michael Oliver

Nestingswitch/casestatementsNestingswitches it’sexactly thesameasnesting if/elsestatements it’saswitch insideaswitch.

Activity23–Nestingswitchstatements

In this program you will create a C++ program that has a nested switch for a cinemasystem.Createanewprogramcallednestingswitch,copythecode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

intchoice,film;

cout<<“1.ViewPrices”<<endl;

cout<<“2.ViewTimes“<<endl;

cout<<“3.ViewFilms”<<endl;

cin>>choice;

switch(choice)

{

case1:

{

cout<<“Youhavechossentoviewprices”;

cout<<“Student:£5.59”;

cout<<“Adult:£7.00”;

cout<<“Concession:£5.40”;

break;

}

case2:

{

cout<<“whatfilmwouldyouliketowatch?”<<endl;

cout<<“1.TheHobbit:TheBattleofFiveArmies“<<endl;

cout<<“2.TheImitationGame”<<endl;

cout<<“3.Frozen”<<endl;

cin>>film;

switch(film)

{

case1:

{

Page 79: An Introduction to C++ A complete beginners guide - Michael Oliver

cout<<“TheHobbit:TheBattleofFiveArmies”<<endl;

cout<<“1.Monday”<<endl;

cout<<“2.Tuesday”<<endl;

cout<<“3.Wednesday”<<endl;

cout<<“4.Thursday”<<endl;

cout<<“5.Friday”<<endl;

break;

}

case2:

{

cout<<“TheImitationGame”<<endl;

cout<<“1.Monday”<<endl;

cout<<“2.Tuesday”<<endl;

cout<<“3.Wednesday”<<endl;

cout<<“4.Thursday”<<endl;

cout<<“5.Friday”<<endl;

break;

}

case3:

{

cout<<“Frozen”<<endl;

cout<<“1.Monday”<<endl;

cout<<“2.Tuesday”<<endl;

cout<<“3.Wednesday”<<endl;

cout<<“4.Thursday”<<endl;

cout<<“5.Friday”<<endl;

break;

}

default:

{

cout<<“Youhaveenteredaninvalidmenuchoice”<<endl;

cout<<“Pleasetryagain”<<endl;

break;

}

}

Page 80: An Introduction to C++ A complete beginners guide - Michael Oliver

break;

}

case3:

{

cout<<“TheHobbit:TheBattleoffivearmies”<<endl;

cout<<“TheImitationGame”<<endl;

cout<<“Frozen”<<endl;

break;

}

default:

{

cout<<“Youhaveenteredaninvalidmenuchoice”<<endl;

cout<<“Pleasetryagain”<<endl;

break;

}

}

return0;

}

Important! Nesting switches can get confusing andmostoftheerrorsyouwillencounterwillbebecauseyouhaven’tclosedyourcaseusingparentheses{}.Pleaseensurethatyoucheckthatyoucloseallyourcases.

Youwillhavenoticedtheaboveprogramwiththenestedswitchdoesnotcontainthetimesforeachfilm,onlythedays.Youwillneedtocreateanothernestedstatementforeachforfilm.Thismeansthatyourprogramwillcontain3nestedswitches.

Page 81: An Introduction to C++ A complete beginners guide - Michael Oliver

IntroductiontoLoopsInprogrammingweuse loops to repeatanaspectofaprogramuntilacertainconditionhasbeenmet.Everypassthroughtheloopisknownasiteration,whichisoneofthebasicthreestructuresofprogramming(sequence, selectionand iteration). Inprogrammingweusethreetypesofloopswhite,for,anddo.While.

WhileLoopsWhileloopswillrepeatastatementwhileaconditionistrue.Thisloopistheonlyloopthatwilltesttheconditionbeforetheloopcommandisexecuted.Theflowdiagramtotheleftshowshowawhileloopworks.

WhileloopsarebasedonBooleanconditions,justlikeconditionalstatements

while(true)

{

//dostuff

}

Do..WhileLoopsAdo..whileloopistheoppositetoawhileloopasthiswillchecktheconditionafterthecodehasbeenexecuted.Unlikeawhileloop,ado..whileloopisguaranteedtobeexecutedatleastonce.Theflowcharttotheleftshowshowadowhileloopworks.

do{

//dostuff

}while(condition);

Page 82: An Introduction to C++ A complete beginners guide - Michael Oliver

ForLoopsForloopsaredesignedtobeexecutedanumberoftimesandareidealifyouwantaspecificofcodetoberepeated.Forexampleforloopsarecommonlyassociatedwitharraysasweareabletoprintmultipleelementsofanarrayinonego.

for(INITIALIZATION;CONDITION;AFTERTHOUGHT)

{

//Codefortheforloop’sbody

//goeshere.

}

for(inti=0;i<100;i++){

//codehere

}

LoopcountersAloopcounterisusedtocontroltheamountofiterationsaloopperforms.Loopcounterscanbeusedtoincrementtheiterationsofaloopdenotedby++orcanbedecrementaloop—.AcommonidentifierforcountersareusedwithvariablenamescalledI,j,andKetc.

Page 83: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 84: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 85: An Introduction to C++ A complete beginners guide - Michael Oliver

WhileloopsThewhileloopisthesimplestkindofloopthatyoucanuseinC++.Thewhileloopwillrepeat the statement whilst the condition is true. When the loop is executed, if theconditionwastochangetofalse,thentheloopwillnolongerrun.

Activity24–Whileloops(decrementcounter)

CreateaC++program,called“Liftoff”andcopythebelowcode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain(){

intnum=10;

while(num>0)//repeatwhilenumislessthan0

{

cout<<num<<“,“;

—num;//decrementalcounter.Everytimethelooprepeatsnum-1.

}

cout<<“liftoff!\n”;

return0;

}

Activity25–Whileloop(Incrementcounter)

CreateaC++programcalled“counting”andcopythebelowcode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum=0;

Page 86: An Introduction to C++ A complete beginners guide - Michael Oliver

while(num<10)//repeatwhilenumislessthan10

{

cout<<num<<“,“;

num++;//incrementalcounter

}

cout<<“finished\n”;

return0;

}

Createagradingprogram that asks theuser to enter agrade.While thegradeisbelow70%displaythemessage“That’snotgoodenoughtryagain”.

Page 87: An Introduction to C++ A complete beginners guide - Michael Oliver

Do…WhileLoopsThedo..whileloopisguaranteedtoexecutethecodecontainedinsideatleastonce,astheconditionoftheloopischeckedattheend.Iftheconditionistrue,theloopwillrunagain,ifnotthentheloopwillnotrun.

Activity26–DoWhile.

Inthisprogram,weasktheusertoenteranumbergreaterthan10,iftheyenteranumberbelow10,theywillbepromptedtoenteranothernumber.Copythecodebelowintoanewprojectcalled“Dowhile”saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum;

do

{

cout<<“Pleaseenteranumbergreaterthan10:“;

cin>>num;

}while(num<10);

return0;

}

Activity27–Dowhile,withNOToperation

CreateanewC++programenterthebelowsourcecode,thensaveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

intnum;

booldone=false;

do{

system(“cls”);//clearsthescreendown

cout<<“Pleaseenteranumber:“;

cin>>num;

Page 88: An Introduction to C++ A complete beginners guide - Michael Oliver

cout<<num<<endl;

system(“pause”);

intnum=0;

}while(!done);

return0;

}

Inactivity23,youwereaskedtocodeaC++programwhichhadnestedswitchstatements.Usingthesamecodeforthatprogram,wrap the entire code in a do while loop, to allow the user torepeattheprogramagainwithoutexitingoutofit.

Activity26-Fixtheerrors

Below isaC++program thathas several errors in,usingwhatyouhave learnt createanewC++projectcalled“ErrorswithLoops”,copythebelowcodeandfixtheerrors.Saveandcompiletoensureallerrorshavebeenresolved.

#include<iostream>

usingnamespacestd;

main()

{

intnum1,num2;

charagain;

do

cout<<“Enteranumber:“;

cin>>num1;

cout<<“Enteranothernumber:“;

cin>>num2;

cout<<“Theirsumis“<<(num1+num2)<<endl;

cout<<“Doyouwanttodothisagain?“;

cin>>again;

while(again==‘y’||again++‘Y’);

return0;

}

Page 89: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity27:Whywillisthisloopstilllooping?

In thebelowcode, isaprogramthatcompiles,butwehavesomethingcalledaninfiniteloop.Aninfiniteloopisaloopthatoncestarted,willcontinuetoloopandnotbreak.Yourtaskistofindwheretheinfinitelooptakesis,andresolveit:

#include<iostream>

#include<string>

usingnamespacestd;

stringfirst,DoB;

chargender;

intmain()

{

intchoice,info,loop=1;

do{

while(choice=2)

{

cout<<“Enterfollowinginformationisinputted:”<<endl;

cout<<“1.Name:“<<first<<”“<<last<<endl;

cout<<“2.DateofBirth:“<<DoB<<endl;

cout<<“3.Gender:“<<gender<<endl;

Page 90: An Introduction to C++ A complete beginners guide - Michael Oliver

cout<<“4.Completeapplication.”<<endl;

cin>>info;

switch(info)

{

case1://name

{

cout<<“Pleaseenteryoufirstname:“<<endl;

cin>>first;

break;

}

case2://age

{

cout<<“Pleaseenteryourdateofbirth(DD/MM/YYYY):”<<endl;

cin>>DoB;break;

}

case3://gender

{

cout<<“Pleaseenteryourgender(M/F):”<<endl;

cin>>gender;break;

}

case4://completeapplication

{

choice=0;

break;

}

default:“notavalidoption”;

break;

}

}

}while(loop=1);

return0;

}

Page 91: An Introduction to C++ A complete beginners guide - Michael Oliver

Youhavenowlearnedtwotypesofloops,createaprogramofyourchoice,thatusesbothawhileandado..Whileloop.Youcanusepreviousprogramstohelpyoustructureyourloops.

Activity28:

Belowisaprogramthatcalculatesyourage,basedonyouryearandmonthofbirthandcomparesittothecurrentmonthandyear.Adaptthisprogramforanofflicensethatwhiletheuser’sageisbelow18theusercan’thaveanyalcohol.

#include<iostream>

usingnamespacestd;

intmain()

{

intbirthmonth,birthyear;

intcurrentmonth,currentyear;

intagey,agem;

cout<<”TheAgeCalculator”<<endl;

cout<<“EnterYourBirthYear(Eg:1993):”<<endl;

cin>>birthyear;

cout<<“EnterYourBirthMonth(Eg:5):”<<endl;

cin>>birthmonth;

Page 92: An Introduction to C++ A complete beginners guide - Michael Oliver

if(birthmonth>12||birthmonth<1)

return1;

cout<<“EnterTheCurrentMonth(Eg:7):”<<endl;

cin>>currentmonth;

cout<<“EnterTheCurrentYear(Eg:2010):”<<endl;

cin>>currentyear;

agey=currentyear-birthyear;

agem=12-birthmonth;

cout<<“YourAgeis“<<agey<<”YearsAnd“<<agem<<”Months“<<endl;

return0;

}

Page 93: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 94: An Introduction to C++ A complete beginners guide - Michael Oliver

ForLoopsAforloopisaspecialtypeofloopthatwillloopaspecificamountoftypes,unlikeawhileanddowhilewhichwillonlyloopifaconditionistrue.Forloopsareparticularlyusefulwhendealingwithdatastructureslikearrays,whichwillbecoveredlaterinthisguide.

Activity28

Inthisprogram,wearegoingtocounthowmanyloopiterationshavetakenplace.Aloopiteration is known as howmany times a loop is executed. Create a newC++ programcalled“forloops”enterthebelowcode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

inti;

for(i=1;i<11;i++)

{

cout<<“loopiteration:“<<i<<endl;

}

return0;

}

Howmany iterationsdidyouget? If coded correctlyyouwouldhavegotten10. If youchange the number 11 in the above program to another number you will get (n-1) ofiterations.Giveitatryandseewhatyouget.

Activity29

In thisactivitywehavechanged the rulesof the for loop tocountdownfrom10ratherthancountup.Comparetheconditionsandthecounterfromthepreviousprogram.CreateanewC++projectcalled“countdown”,copythecode,saveandcompile.

Page 95: An Introduction to C++ A complete beginners guide - Michael Oliver

#include<iostream>

usingnamespacestd;

intmain()

{

inti;

for(i=10;i>0;i—)

{

cout<<“loopiteration:“<<i<<endl;

}

return0;

}

Understandingthesyntaxofaforloop

Activity30(NestingLoops)

Inthisprogramyouaregoingtocreateaprogramthatusesnestedforloops.Createanewprojectcalled“nestedforloops”,copythecodebelow,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

Page 96: An Introduction to C++ A complete beginners guide - Michael Oliver

inti,j;

for(i=1;i<4;i++)

{

cout<<“loopiteration:“<<i<<endl;

for(j=1;j<4;j++)

{

cout<<”Innerloopiteration:“<<j<<endl;

}

}

return0;

}

Page 97: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 98: An Introduction to C++ A complete beginners guide - Michael Oliver

IntroductiontoFunctions

Functions are dedicated blocks of code thatperform a specific task. They are used to break code into smaller chunks making theprogram easier to understand. Functions promote reusability and are useful for savingspaceintheprogram.

Theactivitiesbelowshowthedifferenttypesoffunctions,andhowtheyareusedwithintheC++environment.

Activity31

In thisprogram,wecaregoing tocreateasimple function thatuses the typevoid.Voidshouldonlybeusedwhena functiondoesnot returnanyvalue.Forexamplea functionthatonlyprintsout statements (like theonebelow)willonlyneed touse thevoid type.Createanewprogramcalled“Myfirstfunction”,copythebelowcode,compileandrun.

#include<iostream>

usingnamespacestd;

voidbanner()//codefunctionhere

{

cout<<“Iamasimplefunction”<<endl;

}

intmain()

{

banner();//callfunctionhere

return0;

}

Page 99: An Introduction to C++ A complete beginners guide - Michael Oliver

Createaprogramthatusesthevoidfunctionthatyouhavelearntfromtheprevious program.Your programwill need to at least call this functions three times indifferentlocationsofyourprogram.

Page 100: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity32

Inthisprogram,weareusingfunctionstopassdatabetweeneachother.ThismethodisinreplacementofGlobalvariables,andisthebestpracticeforallowingspecificfunctionstoaccess certain data, without compromising its integrity. The program below, has afunctioncalled“add”thatisresponsibleforaddingtwovaluestogetherandreturningthesumofthesetwovaluestothe“main”function,whichisthenprintedouttothescreen.

Createaprogramcalled“FunctionAddition”,copythecodebelowandcompile.

#include<iostream>

usingnamespacestd;

intadd(intnum1,intnum2)//codefunctionherewithparameters

{

intsum=num1+num2;//

returnsum;//valueofsumisthenumberthatisreturnedtomain

}

intmain()

{

intresult=add(2,3);//passthevaluesof2and3totheaddfunction

cout<<“Theresultis“<<result<<endl;//

}

Understandingwhattheprogramisdoinglinebyline.

This program has two functions, one called “add”, and the other called “main”. Thesefunctionshavebothbeendeclaredastypeintegers,astheyarebothdealingwithnumbers.

intadd(intnum1,intnum2)

Inthisline,wearecreatingafunctioncalled“add”thatisoftypeinteger,whichhastwoparameters.A parameter is a variable that expects data to be passed to it from anotherfunction, these areknownas arguments.This functionhas twoparameters bothof typeintegercallednum1andnum2.

intsum=num1+num2;

A local variable called sum, has been created to add the values of num1 and num2together.Thisissomethingyoushouldbecomfortablewithbynow,asyouhaveusedthistypeofdeclarationinpreviousC++activities.

returnsum;

Page 101: An Introduction to C++ A complete beginners guide - Michael Oliver

Likereturn0;thisendsthe“addfunction”,butinsteaditcarriesthetotalvalueofnum1andnum2.Thevaluewilltransferredtothefunctionthatcalledthe“add”function.Inthisprogramthatvaluewouldbepassedtothe“main”function.

intresult=add(2,3);

Inthislineofcodewecreateanewvariablecalledresultthatusestypeinteger.Wealsocalloutfunction“add”andwepasstwoargumentstothatfunction.

Theseargumentsarethevalues2and3,whicharestoredinthevariablesnum1andnum2inour“add”function.Inthelastlineofcodereturnsumthetotalof2and3whichis5,isreturnedtothemainfunction.Thevalueof5isstoredinourvariablecalledintresult.Thisresultisthenprintedtothescreen.

Youhavebeenshowed,how tocreate two typesof function,oneasimple function thatusestypevoidandtheotherthatusestypeinteger.InthisactivityyouwillneedtocreateaC++programthatusestwofunctions.Theprogramwillneedtoasktheusertoentertwonumbers,whichwillmultiplythemtogetheranddisplaythefinalsumoutput.

Page 102: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 103: An Introduction to C++ A complete beginners guide - Michael Oliver

IntroductiontoArraysArraysarea typeofdata structure that storesa setofaparticulardata,whichhasbeenplacedincontagiousmemorylocation.Arraysshouldbelookedatmorethanjustasetofdata, but a set of variables of the samedata type.Each piece of data stored in array isknownasanelementandhisitsownuniqueidentifier.Regardlessonthelengthortypeofarraythatisusedthefirstelementisalwaysa0.Takealookbelowatthebelowexample.

Intheaboveexample,wehave5blockswhichcanstore5setsofdataofthesametype.Whenwedeclareanarray,wedeclareitlikeavariableaswehavetogiveadatatypeandaname,butwealsohavetodeclarehowmanyelementsweexpectourarraytohold.Wedothisbyusingsquarebrackets[]withanumberinside.Basedontheexampleaboveourarrayshas5elements[5].BelowisanexampleofhowasimplearrayisdeclaredinC++:

intnumbers[5];Like variables arrays can either be initialised with predefined values when they aredeclared.Toinitialiseanarraywithasetofvalues,weneedtouseaset{}tostorethatdata.Basedontheexampleswehaveusedsofar,thisishowyouwouldinitialiseanarray:

intnumbers[5]={11,22,33,44,55};Aswe have initialised all elements of our array, this is how our arraywould look likebasedonthefirstexampleabove:

Youmayfindyourselfinsituation,whereyouonlyneedtoinitialiseafewelementsofthearray,forexampleyoumayinitialisethearraylikebelow:

intnumbers[5]={11,22,33};Byinitialisingthefirst3elementsofthearray,theotherelementshavebeenleftundefinedandasaresult,willdefaulttothevalueof0.Seethebelowexample.

Activity33:Myfirstarray

Page 104: An Introduction to C++ A complete beginners guide - Michael Oliver

Inthisprogramwearegoingtocreatetheexactarraythatwehavebeenworkingwithintheexampleabove,andwearegoingtoprintallourelementsouttothescreen.Toprintouteachelementofthearray,weneedtocyclethroughitusingaforloop.Createanewprojectcalled“MyFirstArray”copythebelowcode,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

intnumbers[5]{11,22,33,44,55};//arraydeclaredandinitialised

for(inti=0;i<5;i++)//forloopcreatedwithcorrectloopiterations

{

//loopiterationsi,willprintthecorrectelementofthearray

cout<<numbers[i]<<endl;

}

return0;

}

Inthisprogramtheforloopisthekeytotheworkingofthearray.Wehavecreatedanewvariablecalledintiwhichisusedtohelpuslocatewhichelement in the array needs to be printed, once the for loop completes its iteration thecounterthengoestothenextelementofthearray.

Page 105: An Introduction to C++ A complete beginners guide - Michael Oliver

Activity34:EnteringDataintoanarrayatruntime

Inthisactivitywearegoingtodeclareanewintegerarrayandinitialisethevalueofthearrayatruntime.Createanewprojectcalled“ArrayInput”,enterthecodebelow,saveandcompile.

#include<iostream>

usingnamespacestd;

intmain()

{

intnumbers[5];

inti;//intideclaredheresobothloopscanaccessthedatastored

cout<<“Pleaseenter5numbers:“;

for(i=0;i<5;i++)//forloopcreatedtogetinput

{

cin>>numbers[i];

}

cout<<“Thenumbersyouenteredare:“;

for(i=0;i<5;i++)//forloopcreatedtodisplayoutput

{

cout<<numbers[i]<<”“;

}

cout<<endl;

return0;

}

Have you noticed that in this program that thevariable“i”weusedfortheloops,wasdeclaredoutsideoftheforloop?Thisisbecause

Page 106: An Introduction to C++ A complete beginners guide - Michael Oliver

whencodingyoushouldconsidermemoryspace,andeither thoughyouaresavingonlyseveralbytes,inalargerprogramitcouldsavemuchmore.

Youknowhowtocreateabasicarraythatstoresavarietyofintegers.CreateaprograminC++,whichusesachararraythathasthecorrectamountofelementstostoreyourentirename.Trytoaimtoprintyournameoutononeline.

Page 107: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 108: An Introduction to C++ A complete beginners guide - Michael Oliver

ExtensionActivitiesBelowisaseriesofextensionactivates,withgivenscenarios.Createaseparateprogramforeachscenario.

ExtensionActivity1

TheRentCoCarRentalCompanyrentscarsfor£35perdayplus10pencepermile.Writea program for the rental company so that the user can enter the date that the car wasrented,thenumberofdaysitwasrentedfor,themileagewhenthecarwasrented,andthemileagewhenthecarwasreturned.Calculatethetotalchargesanddisplaytheresults.

ExtensionActivity2

Asimpleaddressbooksystemholdsnames,addressesandtelephonenumbersforfriendsandfamily.Thesystemstores:

SurnameandfirstnameTwolinesoftheaddressandapostcodeTelephonenumberDateofbirthEmailaddress

Writeaprogramtoallowtheusertoinputthesedetailsandthendisplaythemonscreen.

ExtensionActivity3

Temperatures can be converted from Fahrenheit to Centigrade. Research the formularequiredtoconvertatemperaturefromFahrenheittoCentigrade.WriteaprogramtoinputaFahrenheittemperatureandoutputtheequivalenttemperatureinCentigrade.

ExtensionActivity4

Writeaprogramtoworkoutyourpocketmoneyspendingbycarryingoutthefollowingsteps:

Inputavariablepocketmoneytotheamountofmoneyyougeteachmonth.

Outputthetitle‘PocketMoney’

Outputthenumberofpoundsatthestartofthemonth

Inputthenumberofpoundsspentonfood

Inputthenumberofpoundsspentonyourmobilephone

Page 109: An Introduction to C++ A complete beginners guide - Michael Oliver

Outputtheamountofpocketmoneyleft

ExtensionActivity5

Write a program to calculate the area of a circle.Youwill have to research formula tocalculatetheareaofacirclebasedontheradius.

Assignthevalue3.14159toavariablecalledpi.

Inputtheradiusofthecircle

Outputtheareaofacircle

ExtensionActivity6

Enter the length,width and depth of a rectangular swimming pool.Write a program tocalculatethevolumeofwaterrequiredtofillthepoolandoutputthevolume.

Page 110: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 111: An Introduction to C++ A complete beginners guide - Michael Oliver

TheASCIITableComputers can only understand one language, which is binary. Computers can’tunderstandcharacterssuchas‘@’or‘y’,theycanonlyunderstandtheirbinaryequivalent.

The ASCII (American standard code of information interchange) table shows thenumericalrepresentationofacharacter indecimal,whichis thenconvertedtobinarybythecompilersinterpreter.

Charactercodes0–31oftheASCIItablearenon-printingcharacters.Charactercodes32-127areprintablecharactersandcharacter’sCharactercodes128-255aretheextendedASCIIcodesforprintablecharacters.

TheASCII table isextremelyimportantas ithelpsusunderstandthatnotwovaluesarethesame.Seethebelowexample:

Thecharacter ‘A’and ‘a’ tohumanshave the samemeaning (obviouslyone is a capitalletter). But to a computer system they are completely different with two differentmeanings.

‘A’hasthevalueof65whichinbinaryis:01000001

‘a’hasthevalueof97whichinbinaryis:01011101

It’simportantthatweunderstandthatthesevaluesaredifferentandtheCPUhandlesthesevaluesinadifferentway.

Page 112: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 113: An Introduction to C++ A complete beginners guide - Michael Oliver

ASCIITable(Binaryvalues31-127)Below is the ASCII table for values 31-127. The table shows the decimal, octal,hexadecimalandHTMLvalueofeachcharacterwithintheaboverange.

DEC

OCT

HEX

BIN

Symbol

HTMLNumber

HTMLName

Description

32

040

20

00100000

&#32;

Space

33

041

21

00100001

!

&#33;

Exclamationmark

34

042

22

00100010

&#34;

&quot;

Doublequotes(orspeechmarks)

35

043

23

00100011

#

&#35;

Number

36

044

24

00100100

$

&#36;

Dollar

37

045

25

00100101

%

&#37;

Procenttecken

38

046

26

00100110

&

&#38;

&amp;

Ampersand

39

047

27

00100111

&#39;

Singlequote

40

050

28

00101000

(

&#40;

Openparenthesis(oropenbracket)

41

051

29

00101001

)

&#41;

Closeparenthesis(orclosebracket)

42

052

2A

00101010

*

&#42;

Asterisk

43

053

2B

00101011

+

&#43;

Plus

Page 114: An Introduction to C++ A complete beginners guide - Michael Oliver

44

054

2C

00101100

,

&#44;

Comma

45

055

2D

00101101

-

&#45;

Hyphen

46

056

2E

00101110

.

&#46;

Period,dotorfullstop

47

057

2F

00101111

/

&#47;

Slashordivide

48

060

30

00110000

0

&#48;

Zero

49

061

31

00110001

1

&#49;

One

50

062

32

00110010

2

&#50;

Two

51

063

33

00110011

3

&#51;

Three

52

064

34

00110100

4

&#52;

Four

53

065

35

00110101

5

&#53;

Five

54

066

36

00110110

6

&#54;

Six

55

067

37

00110111

7

&#55;

Seven

56

070

38

00111000

8

&#56;

Eight

57

071

39

00111001

9

&#57;

Nine

58

072

3A

00111010

:

&#58;

Colon

Page 115: An Introduction to C++ A complete beginners guide - Michael Oliver

59

073

3B

00111011

;

&#59;

Semicolon

60

074

3C

00111100

<

&#60;

&lt;

Lessthan(oropenangledbracket)

61

075

3D

00111101

=

&#61;

Equals

62

076

3E

00111110

>

&#62;

&gt;

Greaterthan(orcloseangledbracket)

63

077

3F

00111111

?

&#63;

Questionmark

64

100

40

01000000

@

&#64;

Atsymbol

65

101

41

01000001

A

&#65;

UppercaseA

66

102

42

01000010

B

&#66;

UppercaseB

67

103

43

01000011

C

&#67;

UppercaseC

68

104

44

01000100

D

&#68;

UppercaseD

69

105

45

01000101

E

&#69;

UppercaseE

70

106

46

01000110

F

&#70;

UppercaseF

71

107

47

01000111

G

&#71;

UppercaseG

Page 116: An Introduction to C++ A complete beginners guide - Michael Oliver

72 110 48 01001000 H &#72; UppercaseH

73

111

49

01001001

I

&#73;

UppercaseI

74

112

4A

01001010

J

&#74;

UppercaseJ

75

113

4B

01001011

K

&#75;

UppercaseK

76

114

4C

01001100

L

&#76;

UppercaseL

77

115

4D

01001101

M

&#77;

UppercaseM

78

116

4E

01001110

N

&#78;

UppercaseN

79

117

4F

01001111

O

&#79;

UppercaseO

80

120

50

01010000

P

&#80;

UppercaseP

81

121

51

01010001

Q

&#81;

UppercaseQ

82

122

52

01010010

R

&#82;

UppercaseR

83

123

53

01010011

S

&#83;

UppercaseS

84

124

54

01010100

T

&#84;

UppercaseT

85

125

55

01010101

U

&#85;

UppercaseU

86

126

56

01010110

V

&#86;

UppercaseV

Page 117: An Introduction to C++ A complete beginners guide - Michael Oliver

87 127 57 01010111 W &#87; UppercaseW

88

130

58

01011000

X

&#88;

UppercaseX

89

131

59

01011001

Y

&#89;

UppercaseY

90

132

5A

01011010

Z

&#90;

UppercaseZ

91

133

5B

01011011

[

&#91;

Openingbracket

92

134

5C

01011100

\

&#92;

Backslash

93

135

5D

01011101

]

&#93;

Closingbracket

94

136

5E

01011110

^

&#94;

Caret-circumflex

95

137

5F

01011111

_

&#95;

Underscore

96

140

60

01100000

`

&#96;

Graveaccent

97

141

61

01100001

a

&#97;

Lowercasea

98

142

62

01100010

b

&#98;

Lowercaseb

99

143

63

01100011

c

&#99;

Lowercasec

100

144

64

01100100

d

&#100;

Lowercased

101

145

65

01100101

e

&#101;

Lowercasee

Page 118: An Introduction to C++ A complete beginners guide - Michael Oliver

102

146

66

01100110

f

&#102;

Lowercasef

103

147

67

01100111

g

&#103;

Lowercaseg

104

150

68

01101000

h

&#104;

Lowercaseh

105

151

69

01101001

i

&#105;

Lowercasei

106

152

6A

01101010

j

&#106;

Lowercasej

107

153

6B

01101011

k

&#107;

Lowercasek

108

154

6C

01101100

l

&#108;

Lowercasel

109

155

6D

01101101

m

&#109;

Lowercasem

110

156

6E

01101110

n

&#110;

Lowercasen

111

157

6F

01101111

o

&#111;

Lowercaseo

112

160

70

01110000

p

&#112;

Lowercasep

113

161

71

01110001

q

&#113;

Lowercaseq

114

162

72

01110010

r

&#114;

Lowercaser

115

163

73

01110011

s

&#115;

Lowercases

Page 119: An Introduction to C++ A complete beginners guide - Michael Oliver

116

164

74

01110100

t

&#116;

Lowercaset

117

165

75

01110101

u

&#117;

Lowercaseu

118

166

76

01110110

v

&#118;

Lowercasev

119

167

77

01110111

w

&#119;

Lowercasew

120

170

78

01111000

x

&#120;

Lowercasex

121

171

79

01111001

y

&#121;

Lowercasey

122

172

7A

01111010

z

&#122;

Lowercasez

123

173

7B

01111011

{

&#123;

Openingbrace

124

174

7C

01111100

|

&#124;

Verticalbar

125

175

7D

01111101

}

&#125;

Closingbrace

126

176

7E

01111110

~

&#126;

Equivalencysign-tilde

127

177

7F

01111111

&#127;

Delete

ToseethefullASCIItablefrom0-255thenvisitwww.ascii-code.com

Page 120: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 121: An Introduction to C++ A complete beginners guide - Michael Oliver

GlossaryBelowissomeofthekeyterminologythatisusedinprogramming,itisessentialthatyoufamiliariseyourselfwiththis,asitwillbeusedinlesson.

Algorithm

Asetofunambiguousstepstosolveagivenproblem

ASCII

AmericanStandardcodeforinformationinterchangeisacharacterencodingschemebasedontheEnglishalphabet,whichencodes128charactersinto7bitbinarynumbers.

Array

Agroupofdataobjectsthathavethesamesizeanddatatype,inacontagiouslocationinmemory.

Boolean

Abinaryvariablethatcanhaveoneoftwopossiblestates,trueorfalse.

Character

Asingleunitofdatathatcouldbealetter,symbolornumber.

Compiler

Acompilerisresponsibleforturningaprogramminglanguageintomachinecode(binary)tobeexecutedbytheCPU.RemembertheCPUdoesnotunderstandanythingbutbinary.

Float

Afloatisadatatypethatisa

Function

Ablockofcodedecimatedtoperformaparticulartask.

IDE

Integrateddevelopmentenvironmentisasetoftoolstobeabletodevelopsoftwareusingaparticularprogramminglanguage.Normallytheycontaintheirowncompiler.

Integer

Awholenumberthathasnodecimalplaces.

Page 122: An Introduction to C++ A complete beginners guide - Michael Oliver

Iteration Istheactofrepeatingaparticularaction

Loop

Seedefinitionofiteration

Parameter

Aparameterisavariablethatispartofafunctionthatreceivesanargumentfromanotherfunction.

Selection

Alsoknownadecision,isatypeoflogicstructurethatdependingontheconditionwilldependontheactionthatisperformed

Sequence

Asequenceisasetofstepsthatgoinaparticularorder.Makingacupofteaisanexampleofasequenceofsteps.

String

Adatatypeusedtostoreacollectionofcharacters,includingsymbolsandnumbers.

Variable

Storesaparticulartypeofdata,usedbyacomputerprogram.Dependingontheconditionsdatacanchangewithinsidethevariable.

Page 123: An Introduction to C++ A complete beginners guide - Michael Oliver
Page 124: An Introduction to C++ A complete beginners guide - Michael Oliver

FurtherReadingTohelpaidyouinyourexperienceanddevelopmentofC++,aresomeseveralbooksandwebsitesthatcanhelpyou.

http://www.tutorialspoint.com/

http://www.learncpp.com/

http://www.cplusplus.com/

https://www.daniweb.com/

https://isocpp.org/

http://stackoverflow.com/

C++programmingineasysteps

ISBN:978-1840784329

Now,initsfourthedition,C++ProgrammingineasystepsbeginsbyexplaininghowtodownloadandinstallafreeC++compilersoyoucanquicklybegintocreateyourownexecutableprogramsbycopyingthebook’sexamples.ItdemonstratesalltheC++languagebasicsbeforemovingontoprovideexamplesofObjectOrientedProgramming.Thebookconcludesbydemonstratinghowyoucanuseyouracquiredknowledgetocreateprogramsgraphically.

BeginningprogrammingwithC++fordummies.

ISBN:978-0470617977

C++isanobject–orientedprogramminglanguagecommonlyadoptedbywould–beprogrammers.ThisbookexploresthebasicdevelopmentconceptsandtechniquesofC++andexplainsthe“how”and“why”ofC++programmingfromthegroundup.Assumingnopriorexperience,BeginningProgrammingwithC++ForDummiesisafunandfriendlyguidetolearningtheC++language.

TeachYourselfC++in24hours

ISBN:978-0672333316

Fromthecompulsoryexplanationofbasicsyntaxanddatatypes

Page 125: An Introduction to C++ A complete beginners guide - Michael Oliver

throughtoobject-orientation,polymorphismandmorethisisameasuredtreatmentofthesubjectathandwhichiswritteninanengagingwaymakingitapleasure,ratherthanachore,toread.Thetimeestimateofonehourperlessonseemsalittleontheconservativesideandespeciallylatterchapterscouldbenefitfromrathermorethan60minutesofstudy,butthisisaminorcriticismattheendoftheday.

Notes

Page 126: An Introduction to C++ A complete beginners guide - Michael Oliver

TableofContentsIntroductiontoC++

CreatingyourfirstC++projectinVisualstudio2013

Understandingyour1stC++Program

SolvingErrorsinC++

AnnotatingYourCode

AddingMultipleLineofCode

IntroductiontoVariables

UsingIntegersandCharactersinC++

UsingfloatsinC++

Usingstrings

GettingUserInput

VariableArithmetic

Globalandlocalvariables

Introconditionalstatements

LogicalOperatorsandConditionalstatements

Creatingacalculatorusingconditionalstatements

NestingIf/Elsestatements

IntroductiontoSwitchStatements

Nestingswitch/casestatements

IntroductiontoLoops

Whileloops

Do…WhileLoops

ForLoops

IntroductiontoFunctions

IntroductiontoArrays

ExtensionActivities

TheASCIITable

ASCIITable(Binaryvalues31-127)

Glossary

FurtherReading