an introduction to c++ a complete beginners guide - michael oliver
TRANSCRIPT
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
LibraryClasses
<iostream>
Readsandwritestotheconsole
<iomanip>
Manipulatesinputandoutput
<fstream>
Readsandwritestoatextfile
<string>
Storesandmanipulatestextstreams
<sstream>
Convertsstringstootherdatatypes
<vector>
Storesandmanipulatesdatainvectorarrayelements
<stdexcept>
Reportslogicerrorsandruntimeerrors
<ctime>
Reportsdateandtime
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
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
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
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”
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.
Clickfile>new>file,toaddanewfiletoyourC++project,orpressctrl+N.
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.
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;
}
Onceyouhaveenteredthiscodewearereadytocompiletheprogram.Thiscanbedonebypressingctrl=F5andclickingokinthedialogboxthatappears.
Oncethisisdonethentheconsolescreenwilldisplaywithyourfirsthelloworldprogram.
WelldoneyouhavesuccessfullycompletedyourfirstC++program.Gotanerrorortheprogramdidn’trun.Checktheerrorboxandreviewtheerrormessages.
Theerrorboxcanbefoundinbyusingthetoolbaratthetop,view>
Allerrorswill appear in theerror list,whichwill automaticallyappearandgiveyouanerrormessage.Inthiscasetheerrorisonline9,whichismissingthe;afterthe<<endlcode.
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
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
program.
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.
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.
YouhaveseenthreeC++programs,nowit’stimetotryityourself.CreateaC++programthatprintsoutyournameontothescreen.Youcanusethepreviousprogramsasaguide,buttrydoingwithoutlooking.
Don’tforgettoannotateyourcodeusingyourcomments!!
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.
Nowthatyouknowhowtoprintcodeonseparateline,createaC++programthattellsthestoryofthethreelittlepigsandthebigbadwolf.
Yourcode,willneedtocompileandyouwillneedtoannotatethekeypartstoyourcode.
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.
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.
charletter;//letteristhevariablenamechosenwhichexpectsachardatatype
stringname;//nameisthevariablenamechosenwhichexpectsastringormorethanone.
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;
}
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.
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
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;
}
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()
{
stringfirstname=“Frodo“;
stringsecondname=“Baggins”;
stringfullname;
fullname=firstname+secondname;//exampleofconcatenation
cout<<“Firstname:“<<firstname<<endl;
cout<<“Secondname:“<<secondname<<endl;
cout<<“Yourfullnameis:“<<fullname<<endl;
return0;
}
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;
cout<<“Pleaseenteryourfirstname:“<<endl;
cin>>name;
cout<<“Hello“<<name<<”WelcometoC++”<<endl;
return0;
}
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.
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;
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“;
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.
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;
}
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
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:
The1stconditionbeingifthestudentdoesthehomeworkThe2ndconditionbeingifthestudenthasn’tdonetheirhomework.
Note:ThisprogramwillneedtouseaChardatatypetochecktheconditionnotaninteger
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;
}
return0;
}
Using theabovecodeasaguidecreateaprogramthat tells theuser that theypressedaspecificsetofletters‘Q’,‘W’,‘E’,‘R’,‘T’,‘Y’.
RememberthatwhenusinglettersinC++thathaveanimpactonthestateoftheprogramthattheyneedtobeinsinglequotationmarks,asseenabove.
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.
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’))
CreateaC++programthatcheckstheconditionofanumberentered,asktheusertoenteranumbersuchas5OR10.
Ensurethatyourprogramcompilesandrunsthatallcodeisannotated.
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
if((num1==5)&&(num2==3))
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
Excellentyougot90%,yougotDistinctionWelldoneyougot75%,yougotaMeritYougot60%,yougotapass.TryHarder!
Youwillneedtocompileandrunyourprogram,aswellasannotateallyourcode.
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;
}
elseif(m==‘/’)
{
cout<<(c=a/b)<<endl;
}
else
{
cout<<“InvalidSymbol”<<endl;
}
return0;
}
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;
}
else
cout<<“InvalidNumber”;
return0;
}
If/else statements are not the onlyway to look for acertaincondition.Theotherisoptionistouseaswitch.Thesearecoveredinthenextfewactivities.
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;
}
cout<<“Yourgradeis“<<grade<<endl;
return0;
}
Tryenteringthevalue‘A’intoyourprogram.Whatwasyourresult?Nowtrytypingthevalue‘a’intotheprogram.Didyougetaninvalidreponse?
Rememberthevalue‘A’andthevalue‘a’arecompletelydifferent.Lets=gobackandamendthecodewehavecreated.
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;
}
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;
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.
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:
{
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;
}
}
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.
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);
ForLoopsForloopsaredesignedtobeexecutedanumberoftimesandareidealifyouwantaspecificofcodetoberepeated.Forexampleforloopsarecommonlyassociatedwitharraysasweareabletoprintmultipleelementsofanarrayinonego.
for(INITIALIZATION;CONDITION;AFTERTHOUGHT)
{
//Codefortheforloop’sbody
//goeshere.
}
for(inti=0;i<100;i++){
//codehere
}
LoopcountersAloopcounterisusedtocontroltheamountofiterationsaloopperforms.Loopcounterscanbeusedtoincrementtheiterationsofaloopdenotedby++orcanbedecrementaloop—.AcommonidentifierforcountersareusedwithvariablenamescalledI,j,andKetc.
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;
while(num<10)//repeatwhilenumislessthan10
{
cout<<num<<“,“;
num++;//incrementalcounter
}
cout<<“finished\n”;
return0;
}
Createagradingprogram that asks theuser to enter agrade.While thegradeisbelow70%displaythemessage“That’snotgoodenoughtryagain”.
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;
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;
}
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;
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;
}
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;
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;
}
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.
#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()
{
inti,j;
for(i=1;i<4;i++)
{
cout<<“loopiteration:“<<i<<endl;
for(j=1;j<4;j++)
{
cout<<”Innerloopiteration:“<<j<<endl;
}
}
return0;
}
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;
}
Createaprogramthatusesthevoidfunctionthatyouhavelearntfromtheprevious program.Your programwill need to at least call this functions three times indifferentlocationsofyourprogram.
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;
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.
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
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.
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
whencodingyoushouldconsidermemoryspace,andeither thoughyouaresavingonlyseveralbytes,inalargerprogramitcouldsavemuchmore.
Youknowhowtocreateabasicarraythatstoresavarietyofintegers.CreateaprograminC++,whichusesachararraythathasthecorrectamountofelementstostoreyourentirename.Trytoaimtoprintyournameoutononeline.
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
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.
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.
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
 
Space
33
041
21
00100001
!
!
Exclamationmark
34
042
22
00100010
”
"
"
Doublequotes(orspeechmarks)
35
043
23
00100011
#
#
Number
36
044
24
00100100
$
$
Dollar
37
045
25
00100101
%
%
Procenttecken
38
046
26
00100110
&
&
&
Ampersand
39
047
27
00100111
’
'
Singlequote
40
050
28
00101000
(
(
Openparenthesis(oropenbracket)
41
051
29
00101001
)
)
Closeparenthesis(orclosebracket)
42
052
2A
00101010
*
*
Asterisk
43
053
2B
00101011
+
+
Plus
44
054
2C
00101100
,
,
Comma
45
055
2D
00101101
-
-
Hyphen
46
056
2E
00101110
.
.
Period,dotorfullstop
47
057
2F
00101111
/
/
Slashordivide
48
060
30
00110000
0
0
Zero
49
061
31
00110001
1
1
One
50
062
32
00110010
2
2
Two
51
063
33
00110011
3
3
Three
52
064
34
00110100
4
4
Four
53
065
35
00110101
5
5
Five
54
066
36
00110110
6
6
Six
55
067
37
00110111
7
7
Seven
56
070
38
00111000
8
8
Eight
57
071
39
00111001
9
9
Nine
58
072
3A
00111010
:
:
Colon
59
073
3B
00111011
;
;
Semicolon
60
074
3C
00111100
<
<
<
Lessthan(oropenangledbracket)
61
075
3D
00111101
=
=
Equals
62
076
3E
00111110
>
>
>
Greaterthan(orcloseangledbracket)
63
077
3F
00111111
?
?
Questionmark
64
100
40
01000000
@
@
Atsymbol
65
101
41
01000001
A
A
UppercaseA
66
102
42
01000010
B
B
UppercaseB
67
103
43
01000011
C
C
UppercaseC
68
104
44
01000100
D
D
UppercaseD
69
105
45
01000101
E
E
UppercaseE
70
106
46
01000110
F
F
UppercaseF
71
107
47
01000111
G
G
UppercaseG
72 110 48 01001000 H H UppercaseH
73
111
49
01001001
I
I
UppercaseI
74
112
4A
01001010
J
J
UppercaseJ
75
113
4B
01001011
K
K
UppercaseK
76
114
4C
01001100
L
L
UppercaseL
77
115
4D
01001101
M
M
UppercaseM
78
116
4E
01001110
N
N
UppercaseN
79
117
4F
01001111
O
O
UppercaseO
80
120
50
01010000
P
P
UppercaseP
81
121
51
01010001
Q
Q
UppercaseQ
82
122
52
01010010
R
R
UppercaseR
83
123
53
01010011
S
S
UppercaseS
84
124
54
01010100
T
T
UppercaseT
85
125
55
01010101
U
U
UppercaseU
86
126
56
01010110
V
V
UppercaseV
87 127 57 01010111 W W UppercaseW
88
130
58
01011000
X
X
UppercaseX
89
131
59
01011001
Y
Y
UppercaseY
90
132
5A
01011010
Z
Z
UppercaseZ
91
133
5B
01011011
[
[
Openingbracket
92
134
5C
01011100
\
\
Backslash
93
135
5D
01011101
]
]
Closingbracket
94
136
5E
01011110
^
^
Caret-circumflex
95
137
5F
01011111
_
_
Underscore
96
140
60
01100000
`
`
Graveaccent
97
141
61
01100001
a
a
Lowercasea
98
142
62
01100010
b
b
Lowercaseb
99
143
63
01100011
c
c
Lowercasec
100
144
64
01100100
d
d
Lowercased
101
145
65
01100101
e
e
Lowercasee
102
146
66
01100110
f
f
Lowercasef
103
147
67
01100111
g
g
Lowercaseg
104
150
68
01101000
h
h
Lowercaseh
105
151
69
01101001
i
i
Lowercasei
106
152
6A
01101010
j
j
Lowercasej
107
153
6B
01101011
k
k
Lowercasek
108
154
6C
01101100
l
l
Lowercasel
109
155
6D
01101101
m
m
Lowercasem
110
156
6E
01101110
n
n
Lowercasen
111
157
6F
01101111
o
o
Lowercaseo
112
160
70
01110000
p
p
Lowercasep
113
161
71
01110001
q
q
Lowercaseq
114
162
72
01110010
r
r
Lowercaser
115
163
73
01110011
s
s
Lowercases
116
164
74
01110100
t
t
Lowercaset
117
165
75
01110101
u
u
Lowercaseu
118
166
76
01110110
v
v
Lowercasev
119
167
77
01110111
w
w
Lowercasew
120
170
78
01111000
x
x
Lowercasex
121
171
79
01111001
y
y
Lowercasey
122
172
7A
01111010
z
z
Lowercasez
123
173
7B
01111011
{
{
Openingbrace
124
174
7C
01111100
|
|
Verticalbar
125
175
7D
01111101
}
}
Closingbrace
126
176
7E
01111110
~
~
Equivalencysign-tilde
127
177
7F
01111111

Delete
ToseethefullASCIItablefrom0-255thenvisitwww.ascii-code.com
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.
Iteration Istheactofrepeatingaparticularaction
Loop
Seedefinitionofiteration
Parameter
Aparameterisavariablethatispartofafunctionthatreceivesanargumentfromanotherfunction.
Selection
Alsoknownadecision,isatypeoflogicstructurethatdependingontheconditionwilldependontheactionthatisperformed
Sequence
Asequenceisasetofstepsthatgoinaparticularorder.Makingacupofteaisanexampleofasequenceofsteps.
String
Adatatypeusedtostoreacollectionofcharacters,includingsymbolsandnumbers.
Variable
Storesaparticulartypeofdata,usedbyacomputerprogram.Dependingontheconditionsdatacanchangewithinsidethevariable.
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
throughtoobject-orientation,polymorphismandmorethisisameasuredtreatmentofthesubjectathandwhichiswritteninanengagingwaymakingitapleasure,ratherthanachore,toread.Thetimeestimateofonehourperlessonseemsalittleontheconservativesideandespeciallylatterchapterscouldbenefitfromrathermorethan60minutesofstudy,butthisisaminorcriticismattheendoftheday.
Notes
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