Академический Документы
Профессиональный Документы
Культура Документы
1.10bHowtodesignyourfirstprogramsLearnC++
1.10bHowtodesignyour
firstprograms
BYALEXO NSEPT EMBER5T H,2009| LAST MO DIF IEDBY
ALEXO NJ ULY30T H,2016
Nowthatyouvelearnedsomebasicsaboutprograms,lets
lookmorecloselyathowtodesignaprogram.Whenyousit
downtowriteaprogram,generallyyouhavesomesortof
problemthatyoudliketosolve,orsituationthatyoudlike
tosimulate.Newprogrammersoftenhavetroublefiguring
outhowtoconvertthatideaintoactualcode.Butitturns
out,youhavemanyoftheproblemsolvingskillsyouneed
already,acquiredfromeverydaylife.
Themostimportantthingtoremember(andhardestthingto
do)istodesignyourprogrambeforeyoustartcoding.Inmanyregards,programmingislikearchitecture.Whatwould
happenifyoutriedtobuildahousewithoutfollowinganarchitecturalplan?Oddsare,unlessyouwereverytalented,
youdendupwithahousethathadalotofproblems:wallsthatwerentstraight,aleakyroof,etcSimilarly,ifyoutry
toprogrambeforeyouhaveagoodgameplanmovingforward,youlllikelyfindthatyourcodehasalotofproblems,
andyoullhavetospendalotoftimefixingproblemsthatcouldhavebeenavoidedaltogetherwithalittlethinking
ahead.
Alittleupfrontplanningwillsaveyoubothtimeandfrustrationinthelongrun.
Step1:Definetheproblem
Thefirstthingyouneedtofigureoutiswhatproblemyourprogramisattemptingtosolve.Ideally,youshouldbeableto
statethisinasentenceortwo.Forexample:
Iwanttowriteaphonebookapplicationtohelpmekeeptrackofmyfriendsphonenumbers.
Iwanttowritearandomdungeongeneratorthatwillproduceinterestinglookingcaverns.
IwanttowriteaprogramthatwillreadinformationaboutstocksfromtheinternetandpredictwhichonesI
shouldbuy.
Althoughthisstepseemsobvious,itsalsohighlyimportant.Theworstthingyoucandoiswriteaprogramthatdoesnt
actuallydowhatyou(oryourboss)wanted!
Step2:Defineyourtools,targets,andbackupplan
Whenyouareanexperiencedprogrammer,therearemanyotherstepsthattypicallywouldtakeplaceatthispoint,
including:
Understandingwhoyourtargetusersareandwhattheywant.
Definingwhattargetarchitectureand/orOSyourprogramwillrunon.
Determiningwhatsetoftoolsyouwillbeusing.
Determiningwhetheryouwillwriteyourprogramaloneoraspartofateam.
Collectingrequirements(adocumentedlistofwhattheprogramneedstodo).
Definingyourtesting/feedback/releasestrategy.
Determininghowyouwillbackupyourcode.
However,asanewprogrammer,theanswerstothesequestionsaretypicallysimple:Youarewritingaprogramforyour
ownuse,alone,onyourownsystem,usinganIDEyoupurchasedordownloaded,andyourcodeisprobablynotused
byanybodybutyou.Thismakesthingseasy.
Thatsaid,ifyouaregoingtoworkonanythingofnontrivialcomplexity,youshouldhaveaplantobackupyourcode.
Itsnotenoughtojustziporcopythedirectorytoanotherlocationonyourmachine(thoughthisisbetterthannothing).
Ifyoursystemcrashes,youllloseeverything.Agoodbackupstrategyinvolvesgettingacopyofthecodeoffofyour
systemaltogether.Therearelotsofeasywaystodothis:Emailittoyourself,copyittoDropboxoranothercloud
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
1/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
service,FTPittoanothermachine,copyittoanothermachineonyourlocalnetwork,oruseaversioncontrolsystem
residingonanothermachineorinthecloud(e.g.github).Versioncontrolsystemshavetheaddedadvantageofnotonly
beingabletorestoreyourfiles,butalsotorollthembacktoapreviousversion.
Step3:Breakhardproblemsdownintoeasyproblems
Inreallife,weoftenneedtoperformtasksthatareverycomplex.Tryingtofigureouthowtodothesetaskscanbe
verychallenging.Insuchcases,weoftenmakeuseofthetopdownmethodofproblemsolving.Thatis,insteadof
solvingasinglecomplextask,webreakthattaskintomultiplesubtasks,eachofwhichisindividuallyeasiertosolve.If
thosesubtasksarestilltoodifficulttosolve,theycanbebrokendownfurther.Bycontinuouslysplittingcomplextasks
intosimplerones,youcaneventuallygettoapointwhereeachindividualtaskismanageable,ifnottrivial.
Letstakealookatanexampleofthis.Letssaywewanttowriteareportoncarrots.Ourtaskhierarchycurrently
lookslikethis:
Writereportoncarrots
Writingareportoncarrotsisaprettybigtasktodoinonesitting,soletsbreakitintosubtasks:
Writereportoncarrots
Doresearchoncarrots
Writeoutline
Fillinoutlinewithdetailedinformationaboutcarrots
Addtableofcontents
Thatsmoremanageable,aswenowhavesubtasksthatwecanfocusonindividually.However,inthiscase,Do
researchoncarrotsissomewhatvague,sowecanbreakitdownfurther:
Writereportoncarrots
Doresearchoncarrots
Gotolibraryandgetbookoncarrots
Lookforinformationaboutcarrotsoninternet
Takenotesonrelevantsectionsfromreferencematerial
Writeoutline
Informationaboutgrowing
Informationaboutprocessing
Informationaboutnutrition
Fillinoutlinewithdetailedinformationaboutcarrots
Addtableofcontents
Nowwehaveahierarchyoftasks,noneofthemparticularlyhard.Bycompletingeachoftheserelativelymanageable
subitems,wecancompletethemoredifficultoveralltaskofwritingareportoncarrots.
Theotherwaytocreateahierarchyoftasksistodosofromthebottomup.Inthismethod,wellstartfromalistof
easytasks,andconstructthehierarchybygroupingthem.
Asanexample,manypeoplehavetogotoworkorschoolonweekdays,soletssaywewanttosolvetheproblemof
getfrombedtowork.Ifyouwereaskedwhattasksyoudidinthemorningtogetfrombedtowork,youmightcome
upwiththefollowinglist:
Pickoutclothes
Getdressed
Eatbreakfast
Drivetowork
Brushyourteeth
Getoutofbed
Preparebreakfast
Getinyourcar
Takeashower
Usingthebottomupmethod,wecanorganizetheseintoahierarchyofitemsbylookingforwaystogroupitemswith
similaritiestogether:
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
2/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Getfrombedtowork
Bedroomthings
Getoutofbed
Pickoutclothes
Getdressed
Bathroomthings
Takeashower
Brushyourteeth
Breakfastthings
Preparebreakfast
Eatbreakfast
Transportationthings
Getinyourcar
Drivetowork
Asitturnsout,thesetaskhierarchiesareextremelyusefulinprogramming,becauseonceyouhaveataskhierarchy,
youhaveessentiallydefinedthestructureofyouroverallprogram.Thetopleveltask(inthiscase,Writeareporton
carrotsorGetfrombedtowork)becomesmain()(becauseitisthemainproblemyouaretryingtosolve).The
subitemsbecomefunctionsintheprogram.
Ifitturnsoutthatoneoftheitems(functions)istoodifficulttoimplement,simplysplitthatitemintomultiplesub
items/subfunctions.Eventuallyyoushouldreachapointwhereeachfunctioninyourprogramistrivialtoimplement.
Step4:Figureoutthesequenceofevents
Nowthatyourprogramhasastructure,itstimetodeterminehowtolinkallthetaskstogether.Thefirststepisto
determinethesequenceofeventsthatwillbeperformed.Forexample,whenyougetupinthemorning,whatorderdo
youdotheabovetasks?Itmightlooklikethis:
Getoutofbed
Pickoutclothes
Takeashower
Getdressed
Preparebreakfast
Eatbreakfast
Brushyourteeth
Getinyourcar
Drivetowork
Ifwewerewritingacalculator,wemightdothingsinthisorder:
Getfirstnumberfromuser
Getmathematicaloperationfromuser
Getsecondnumberfromuser
Calculateresult
Printresult
Thislistessentiallydefineswhatwillgointoyourmain()function:
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
getOutOfBed();
pickOutClothes();
takeAShower();
getDressed();
prepareBreakfast();
eatBreakfast();
brushTeeth();
getInCar();
driveToWork();
}
Orinthecaseofthecalculator:
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
3/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
// Get first number from user
getUserInput();
// Calculate result
calculateResult();
// Print result
printResult();
}
Notethatifyouregoingtousethisoutlinemethodforconstructingyourprograms,itsagoodideatocommenteach
oftheseoutuntilyouactuallywritethem,andthenworkonthemoneatatime,testingeachasyougo.Thatwaythe
compilerwontcomplainaboutthemnotbeingdefined.
Step5:Figureoutthedatainputsandoutputsforeachtask
Onceyouhaveahierarchyandasequenceofevents,thenextthingtodoisfigureoutwhatinputdataeachtaskneeds
tooperate,andwhatdataitproducesasaresult(ifany).Ifyoualreadyhavetheinputdatafromapreviousstep,that
inputdatawillbecomeaparameter.Ifyouarecalculatingoutputforusebysomeotherfunction,thatoutputwill
generallybecomeareturnvalue.
Whenwearedone,weshouldhaveprototypesforeachfunction.Incaseyouveforgotten,afunctionprototypeisa
declarationofafunctionthatincludesthefunctionsname,parameters,andreturntype,butdoesnotimplementthe
function.
Letsdoacoupleexamples.getUserInput()isprettystraightforward.Weregoingtogetanumberfromtheuserand
returnitbacktothecaller.Thus,thefunctionprototypewouldlooklikethis:
1
int getUserInput();
Inthecalculatorexample,thecalculateResult()functionwillneedtotake3piecesofinput:Twonumbersanda
mathematicaloperator.Weshouldalreadyhaveallthreeofthesebythetimewegettothepointwherethisfunctionis
called,sothesethreepiecesofdatawillbefunctionparameters.ThecalculateResult()functionwillcalculatetheresult
value,butitdoesnotdisplaytheresultitself.Consequently,weneedtoreturnthatresultasareturnvaluesothatother
functionscanuseit.
Giventhat,wecouldwritethefunctionprototypelikethis:
1
Step6:Writethetaskdetails
Inthisstep,foreachtask,youwillwriteitsactualimplementation.Ifyouhavebrokenthetasksdownintosmall
enoughpieces,eachtaskshouldbefairlysimpleandstraightforward.Ifagiventaskstillseemsoverlycomplex,
perhapsitneedstobebrokendownintosubtasksthatcanbemoreeasilyimplemented.
Forexample:
1
2
3
4
5
6
7
8
9
10
11
12
int getMathematicalOperation()
{
std::cout << "Please enter which operator you want (1 = +, 2 = -, 3 = *, 4 = /): ";
int op;
std::cin >> op;
return op;
}
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
4/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Step7:Connectthedatainputsandoutputs
Finally,thelaststepistoconnectuptheinputsandoutputsofeachtaskinwhateverwayisappropriate.Forexample,
youmightsendtheoutputofcalculateResult()intoaninputofprintResult(),soitcanprintthecalculatedanswer.This
willofteninvolvetheuseofintermediaryvariablestotemporarilystoretheresultsoitcanbepassedbetweenfunctions.
Forexample:
1
2
3
4
Thistendstobemuchmorereadablethanthealternativecondensedversionthatdoesntuseatemporaryvariable:
1
Thisisoftenthehardeststepfornewprogrammerstogetthehangof.
Afullycompletedversionoftheabovecalculatorsamplefollows.Notethatitusesafewmoreconceptswehavent
coveredyet:
ifstatementsletyouexecutealineofcodeifagivenconditionistrue
the==operatorletsyoucomparetwoitemstoseeiftheyareequivalent
Youarenotexpectedtounderstandtheseatthistime(wellcovertheseinmoredetaillater).Focusmoreontheoverall
flowoftheprogram,andhowdatamovesbetweenthefunctions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
int getUserInput()
{
std::cout << "Please enter an integer: ";
int value;
std::cin >> value;
return value;
}
int getMathematicalOperation()
{
std::cout << "Please enter which operator you want (1 = +, 2 = -, 3 = *, 4 = /): ";
int op;
std::cin >> op;
return op;
}
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
5/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// note: This isn't a good way to handle errors, since -1 could be returned as a legi
timate value
}
int main()
{
// Get first number from user
int input1 = getUserInput();
// Print result
printResult(result);
}
Wordsofadvicewhenwritingprograms
Keepyourprogramssimpletostart.Oftennewprogrammershaveagrandvisionforallthethingstheywanttheir
programtodo.Iwanttowritearoleplayinggamewithgraphicsandsoundandrandommonstersanddungeons,witha
townyoucanvisittoselltheitemsthatyoufindinthedungeonIfyoutrytowritesomethingtoocomplextostart,you
willbecomeoverwhelmedanddiscouragedatyourlackofprogress.Instead,makeyourfirstgoalassimpleas
possible,somethingthatisdefinitelywithinyourreach.Forexample,Iwanttobeabletodisplaya2dfieldonthe
screen.
Addfeaturesovertime.Onceyouhaveyoursimpleprogramworkingandworkingwell,thenyoucanaddfeaturesto
it.Forexample,onceyoucandisplayyour2dfield,addacharacterwhocanwalkaround.Onceyoucanwalkaround,
addwallsthatcanimpedeyourprogress.Onceyouhavewalls,buildasimpletownoutofthem.Onceyouhavea
town,addmerchants.Byaddingeachfeatureincrementallyyourprogramwillgetprogressivelymorecomplexwithout
overwhelmingyouintheprocess.
Focusononeareaatatime.Donttrytocodeeverythingatonce,anddontdivideyourattentionacrossmultiple
tasks.Focusononetaskatatime,andseeitthroughtocompletionasmuchasispossible.Itismuchbettertohave
onefullyworkingtaskandfivethathaventbeenstartedyetthansixpartiallyworkingtasks.Ifyousplityourattention,
youaremorelikelytomakemistakesandforgetimportantdetails.
Testeachpieceofcodeasyougo.Newprogrammerswilloftenwritetheentireprograminonepass.Thenwhenthey
compileitforthefirsttime,thecompilerreportshundredsoferrors.Thiscannotonlybeintimidating,ifyourcode
doesntwork,itmaybehardtofigureoutwhy.Instead,writeapieceofcode,andthencompileandtestitimmediately.
Ifitdoesntwork,youllknowexactlywheretheproblemis,anditwillbeeasytofix.Onceyouaresurethatthecode
works,movetothenextpieceandrepeat.Itmaytakelongertofinishwritingyourcode,butwhenyouaredonethe
wholethingshouldwork,andyouwonthavetospendtwiceaslongtryingtofigureoutwhyitdoesnt.
Mostnewprogrammerswillshortcutmanyofthesestepsandsuggestions(becauseitseemslikealotofworkand/or
itsnotasmuchfunaswritingthecode).However,foranynontrivialproject,followingthesestepswilldefinitelysave
youalotoftimeinthelongrun.Alittleplanningupfrontsavesalotofdebuggingattheend.
Thegoodnewsisthatonceyoubecomecomfortablewithalloftheseconcepts,theywillstartcomingnaturallytoyou
withouteventhinkingaboutit.Eventuallyyouwillgettothepointwhereyoucanwriteentirefunctionswithoutanypre
planningatall.
1.11Debuggingyourprogram(steppingandbreakpoints)
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
6/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Index
1.10aHeaderguards
Sharethis:
PR IN TTH ISPOST
140commentsto1.10bHowtodesignyourfirstprograms
Milten
September6,2009at1:29pmReply
Verywelldone!
Btw:Thankyouverymuchforyourgreattutorial!
Freacky
September7,2009at9:30amReply
Ithinkyouexchangedthearrowswithnext/previoussteps.
Ithinkthisisaverygoodandnoobfriendlytutorialtoo,goodjob).
[Thanksforthenoteaboutthearrows.Fixed!Alex]
WilliamManson
September20,2009at12:30pmReply
Itriedtomakeaprogramthatdoessimpleoperations,butitdoesntseemtowork.
Thepieceinparticular:
1
2
3
4
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
7/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Thecompiler(code::blocks)givestheerror,error:expectedbeforechOperationanderror:expectedbefore
nInput2
Imtryingtomakethefunctionreturnanoperation,e.g.3+5or4/14or14%8,isthisnothowIwouldaccomplish
this?
Deyan
November13,2009at3:00pmReply
Thereturnfunctioncanonlyreturnonevalueatatime.Thusthecompilerisexpectingtosee
aafternInput1.
Ifyoureallymustreturnmorethanonevalue,youmaywanttotryusingglobalvariables.
GoodLuck.
Alex
February9,2015at4:10pmReply
chOperationisacharacter,notanoperator,andtheresnowaytodirectlyconvertonetothe
other.
YoullhavetouseifstatementstoconverteachvalueofchOperatorintotherespectiveoperator(if
chOperatoristhe+character,thendotheplusoperation)
tartan
January19,2010at11:15amReply
Thankyouverymuchforthistutorial.Seemstobethebestonlinecpptutorialsofar,andIfindthis
partandyourcommentsoncodingstyleofasgreatimportanceasexplanationofcommands,
functionsetc.
LawrenceG
February1,2010at10:34amReply
Fantasticguide,Ihavebeentryingtowritethiscarrotreportformonthsyoursimplebreakdownmade
itpossible.
Merv
April27,2016at2:53amReply
Hahametoo!Notjustthosepeskycarrotreports,gettingdressedandreadyforworkwasa
realchallengeforme,butnowIhavethisamazingtutorialathand.
User1
April8,2010at7:24pmReply
IrecentlydecidedtoteachmyselfC++becauseIwouldliketogetintogameprogrammingandwellI
amgladIfoundthiswonderfultutorial.Iunderstanditwilltaketimeandamwillingtodogivetime,but
ImcuriousifIwillbeabletomakea2DWorld(asstatedinthisarticle)soonseeingasIamonChapter2atthe
momentandamabitconfusedhowtoputgraphicstoprogram.
kurt
September25,2010at12:36pmReply
Puttinggraphicsintoaprogramusuallyusesseparatelibrariesthatincorporatec++toteach
thegraphicstoreact/acttooneanother.
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
8/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Itisalottounderstandifyouwanttomakegameswithc++,IamtakingaGameDesign+Development
courseandc++ismoreusedforlargerscalegamesthatrequireateamtoimplementit.
Ifyouwanttocreateindiegames(gamescreatedbyyou,yourself)youmaywanttostartcodingwith
anotherprogramlikeFlashAS3(ActionScript)orjava.
Thisisareallygoodtutorialonc++thoughfromalltheonline/bookinstructionsIhavecomeacross(which
isalot)andc++isreallyimportanttoknowonanycodingscale.Iwouldrecommendgooglinggraphics
programmingandseewhatcomesup.CheckoutDirectXorSDLwhicharec++graphicrelatedlibrariesand
thereareprobablymore,thosearetheonlytwoIknowaboutandsomewhatknowhowtouse.DirectXisa
veryLARGElibrarythoughandcanbekindofoverwhelming.OpenGLisanothergraphicsrelatedone,butI
amnotsureifituseswindowsprogramming(whichisstillc++thelibrariesarejustdifferent)
CorrectmeifIamwronganybody,opentoanycritiscm.
Thanksforthegreattutorial!
armian
May31,2010at1:33pmReply
Thankyoualotforthismagicaltutorial!!!
Ihaveaquestion:HowcanIcompilemyprogramifIhaventfinishedityet?
Whenicompiletoseeifihaveanyerrortillhere,myBloodshedDevC++saysthatihavetoomanymistakes!
Thanksalotagain!
Alex
February9,2015at4:15pmReply
Ideally,youshouldneverendupinthissituationifyouwriteonepieceatatime,andtestit,
youshouldneverhaveatonofcodethatwontcompile,ormorethanafewerrors.
Butifyoudoendupinthiscase,onethingthatcanbehelpfulistocommentoutasmuchcodeas
necessaryuntilyourprogramcompiles.Thenyoucanstartuncommentingthings(inanorderthatmakes
sense)andfixingerrorsalongtheway.
Johnny
September17,2010at9:06amReply
Amazinglysimpleawesomeworkthanks!!YoudefinitelyusedKISS(keepitsimplestupid)LOL
Again,thanks!!
Eric
September23,2010at8:27amReply
Imustsay,Iabsolutelyloveyourtutorials!
Itsextremelyeasytounderstand,andisfuntoo!
Ivebeendoingprogrammingforseveralyearsnow.
Sofar,Iknowthefollowing:HTML,CSS,JS,PHP,VB.Net&GML.
Iwantedtoexpandmycodingknowledge,andbeginwritingPCgamesinC++.
Sadly,Iwasntabletofindanygood,fulltutorials.
Thatis..UntilIfoundyours!
Yourtutorialsarethebestontheweb,andIthankyouforthat!
Thanks,
Eric
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
9/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Phil
October20,2010at11:14amReply
Hey!
Ihavereadthroughallthestuffbeforeitnow,andithinkthisisanidealmomenttosaythanksfor
theseamazingguides!Ijustwrotemyfirstprogramallmyself,(basicbutitmakesmelookclevertomyfriends)),
itbasicllyjustaddstonumberstogether,findmultiples,althoughididmanagetouseaIFthingy,(ilookedatthe
laterchapter).SoYEAH!Justshowshowwellyouhavewroteyourguides
Thankssooomuch
Imgonnabereadingallofthisnomatterwhatsowatchoutformoreofmyposts.
~Phil
Leo
October22,2010at1:40amReply
Usuallyintutorialstheytalkaboutthelanguage,andnotaboutthiskindofstuff.Thisisawesome!
jlovejoy
April5,2011at1:11pmReply
Thisismysecondtimereadingthroughthischapterandoneparticularissuethatcaughtmyeyeis
thatinsection0.1,yousayWewillalsoavoidthetwinevilsandtheunexplainednewconcept,
whereanewconceptthatisintegraltotheexampleisintroducedwithoutanymentionofwhatitisorhowit
works
However,insection1.10a,youusethecommandcharwithouthavingeverintroducedit,oritsfunctionanywhere
inthetutorial.Iwasabletoeventuallypickuponwhatitdid,butstillveryconfusingforfirsttimeprogrammers.
Alex
February9,2015at4:30pmReply
Guiltyascharged.
Ifindmyselfinatoughpositionhere.Inordertoreallymakethepointofthislessonstick,itsnecessaryto
useanontrivialexample.ButIcouldntthinkofanontrivialexamplethatdidntuseatleastoneconceptI
haventintroducedyet.
Iveupdatedtheexampletoremovetheuseofchar,buttheuserofifandoperator==stillremain.Ive
addedalittlebitofadditionaldescriptionaroundthesetohopefullymakeiteasierforreaderstounderstand
whattheyaredoing.
Lakshya
June23,2011at12:08amReply
verynicetutorial
Maksism
August20,2011at10:40pmReply
1
2
3
4
5
6
7
#include "stdafx.h"
#include <iostream>
int GetNumber1()
{
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
10/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
char GetMathOperation()
{
cout << "Please enter + - * /";
char cOp;
cin >> cOp;
return cOp;
}
int GetNumber2()
{
cout << "Please type in number ";
int nY;
cin >> nY;
return nY;
}
return 0;
}
Finallygotit
Cleverlegs
February29,2012at5:45amReply
Verynice,butrememberthatyoudontneedtwodifferentfunctionstogetnumbers.i.e
GetNumber1()andGetNumber2()canbereplacedwithGetNumber().Sincetheyredoingthe
exactsamething
GVeyron217
April4,2012at1:40pmReply
Needsomehelpwiththecalculatorcode.Iwroteitandcompiledit.Itworked,withsmallnumbers
andadding/subtracting.IuseditinmyotherprogrambutwhenIgotsomeonetotestittheyusedbig
numbers.Itworksbutgiveswronganswer.Andifitsareallybignumberthenitjustshowsthe3outputsatthe
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
11/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
sametime,askingforoperator,newnumberandresult,inthesamerowandgivesresultas0.
Thisiswhathappens:
Pleaseenteranumber:586565730854226435643
Pleaseenteranoperator(+,,*,/):Pleaseenteranumber:Yourresultis:0
IcantworkoutwhereIwentwrong.
artxworks
July11,2012at1:30amReply
inthaslimitstryusingdouble
int=signed:2147483648to2147483647
unsigned:0to4294967295
double=+/1.7e+/308(~15digits)
Ollie999
June13,2012at7:46amReply
Greattutorialsthanksandsomegoodadviceinthissection.
Iwouldjustliketopointoutthatitsnotonlynewprogrammerswhomakethemistakeofnotbotheringwithanypre
planningbeforetheystartcoding.Iveworkedinsoftwaredevelopmentformanyyearsandquiteahighproportionof
theexperienceddevelopersIworkwithrepeatedlymakethismistakeoneveryprojectandthenwonderwhythey
spendmostoftheirworkinglifedebuggingtheircode.Iwouldurgeanyonenewtoprogrammingtoheedtheadvice
hereandputsometimeintoplanningoutprogramsinsomedetailbeforeyoustartcoding.Thiswillavoidalotof
debuggingandIcanconfirmfromexperiencethatdebuggingbadlywrittencodeisprobablythemostmind
numbinglytediousactivityIveevercomeacross.
artxworks
July11,2012at1:42amReply
SointhisexampleIcanactuallyasktheusertogiveme3numbersbyusingonly1intgetNumber()
function.thencallitwheneverIwantanewuserinputbychangingthevariable.
intuser1=getNumber()
intuser2=getNumber()
intuser3=getNumber()
etc
thenjusttweakthecorrespondingequationsinthecalculateandresultfunctions..thatsnice..wowIjust
startedyesterdayandImgettingreallyhookedonC++.well,yourwayofexplainingthingsisreallyeasyto
understand.thanksAlex.
DDrum
February11,2015at11:52amReply
Ithinkthearrowstothelinkstonextorpreviouschapterareswitched.Idisplaysanarrowtotheleft
forthenextchapterandanarrowtotherightforthepreviouschapter.
Greattutorialbytheway.
Matthew
February11,2015at9:08pmReply
Hi,
everythingisgreat.Butattheveryendtheredirectionarrowsarewrong=P
Notthatit'ssoimportantbutit'sharmlesstofixit.
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
12/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Regards,
Matthew
Alex
February12,2015at9:05amReply
Fixed!Thanksfortheheadsup.
Jay
February16,2015at9:33pmReply
Hey,Ijustwantedtosaythanksforthisawesometutorial,Ihopethatonceyoureachapointwhere
youaresatisfied.Thatyoupublishthisworkinbook.I'vereadmanybooksonC++,butnonehave
hadthislevelofclaritytothem.You'redoinggreatwork.
TwistedCode
April1,2015at3:42pmReply
"
Thatsamoremanageable,aswenowhavethreetasksthatwecanfocusonindividually.However,
inthiscase,Doresearchoncarrotsissomewhatvague,sowecanbreakitdownfurther:
"
idontthinkthisisformattedproperly
Sandro
April1,2015at11:13pmReply
Helpplez.Itsaisthatinmain,thatCalculateResultisnomatchingoperator.
Usingc++xCode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
int getValueFromUser()
{
using namespace std;
return a;
}
int getOperator()
{
using namespace std;
cout << " Enter wanted operator 1 = +, 2 = -, 3 = *, 4 = / :" << endl;
int a;
cin >> a;
return a;
}
int CalculateResult()
{
int nx;
int ny;
using namespace std;
if (getOperator() == 1)
return nx + ny;
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
13/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
if (getOperator() == 2)
return nx - ny;
if (getOperator() == 3)
return nx * ny;
if (getOperator() == 4)
return nx / ny;
return -1;
}
int main()
{
using namespace std;
return 0;
Alex
April2,2015at4:24pmReply
Online26,youhave:
1
int CalculateResult()
Notethatthisfunctiontakesnoparameters.
Online57,youhave:
1
Notethatyouretryingtopass3parameterstothisfunction.
Consequently,theresamismatchbetweenthefunctiondefinitionandthefunctioncall.
YourfunctioncalltoCalculateResult()iscorrect.YourdefinitionofCalculateResult()needssomework.
ScottMatejka
April23,2015at8:50amReply
HiAlex,
ImreallyhavingtroublewiththeuserfriendlinessoftheIDEs.Imcurrentlytryingtousevisualstudio.AndIgeta
FatalErrorC1083for#include"stdafx.h".
ImopeninganewemptyprojectinC++.
DoIneedtodownloadthatdirectoryfromsomewhere?
WhatamIdoingwrong?
Alex
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
14/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
April23,2015at4:38pmReply
ErrorC1083meansthefilecantbefound.
Isuspectyourmain.cpphasalinethatlookslikethis:
1
#include <stdafx.h>
Butstdafx.hhasntbeenincludedaspartofyourproject.
Twosuggestions:
1)MakesureyourprojectisaWin32consoleapplicationinsteadofanemptyproject
2)Youcancreatestdafx.hifitdoesntexistandaddittoyourproject.Thefilecanbeempty,solongasitexists.
ScottMatejka
April24,2015at8:24amReply
Ithinkvisualstudioistooadvanced.Thefunctionsandeventabsarequiteintimidating.
Asawin32consoleapplicationitloadsawalloftextthatisGreektomesofar.Icantgetagriponwhere
toinsertanythinganditspossibleinteractionswiththestufftheyalreadyhaveup.
IsthereanIDEfornewbies/idiots?
Tito
April24,2015at1:38pmReply
IamusingEclipseIDEandfinditsimpleenough.
David
April25,2015at10:40amReply
IuseCode::Blocksandyeah,itsveryeasytouse.
Alex
April25,2015at10:43amReply
PersonallyIfoundVisualStudioeasiertousethanEclipseorCode::Blocks.Itdoeshave
alotofcomplexity,butyoulllearntoignoremostofit,asitsnotrelevant.VisualStudio
hasafantasticintegrateddebuggeraswell.
SinceyourefindingVisualStudiocomplicated,youcouldtryCode::BlocksorEclipse,butIsuspect
youwontfindthemtoomuchdifferent.
obwan02
July19,2015at9:59pmReply
onmyvisualstudioituses
#include"stdafx.h"
inteadof<stdafx.h>maybethatmightmakeadifference
David
April25,2015at7:30amReply
OkaysoImadeaprogrammthatissuposedtoconvertusdtoeurosoreurostousd.ButIcantgetit
towork.Despitingmyinput,italwaysconvertsdollarstoeuros.Whatdidgowrong?
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
15/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
#include<iostream>
#include<string>
usingnamespacestd
intgetEur()
{
intx
cout<<"Enterammountofeurostoconvert"
cin>>x
returnx//xistheeuros(ifwanted)theusertypedin.
}
intgetUsd()
{
inty
cout<<"Enterammountofdollarstoconvert"
cin>>y
returny//yisthedollars(ifwanted)theusertypedin.
}
intconvertEU()
{
inta=getEur()//attempttogeteuros
return(a*1.08735)//conversiontodollars
}
intconvertUE()
{
intb=getUsd()//attempttogetdollars
return(b*0.91966)//conversiontoeuros
}
intchoose()
{
cout<<"Typethecurrencyyourvalueuses.(usd/eur)"
stringinput
cin>>input//readtheuserscurrrentcurrency.
intx=1
inty=2
if(input=="usd"){//returnxifitaredollars
returnx
}
elseif(input=="eur")//returnyifitareeuros
returny
}
intmain()
{
inta=choose()
if(a=1){//convertusdtoeurosifchoosesreturningwas1
cout<<"Theenteredvalueequals:"<<convertUE()<<"euros"<<endl
}
elseif(a=2){//converteurostousdifchoosesreturningwas2
cout<<"Theenteredvalueequals:"<<convertEU()<<"usd"<<endl
}
}
IdidntknowwhotoaskorwheretoputitandIhopeyoucanhelpmelol.
Jeremy
May6,2015at6:46pmReply
OKsoIfoundanothertypoin"Step2"theresaperiodmissingafterthebulletedsentence:
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
16/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Alex
May8,2015at1:32pmReply
Fixed.Thanksfortheheadsup.
Odgarig
June8,2015at6:47amReply
Great.
JoeriVandenAbeele
June9,2015at11:46amReply
Hello.Canyouexplainthispleace?HowdoestheprogramlinksthenInput1andthenInput2tothe
nXandnY?YoutellhimtoreturnnXnOperatorandnY,tothemain.
1
2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if (nOperator
return nX
if (nOperator
return nX
if (nOperator
return nX
if (nOperator
return nX
return -1; //
}
== 1)
+ nY;
== 2)
- nY;
== 3)
* nY;
== 4)
/ nY;
//
//
//
//
//
//
//
//
if user
execute
if user
execute
if user
execute
if user
execute
Alex
June9,2015at4:59pmReply
WhenCalculateResult()iscalled,thevalueofnInput1iscopiedintoparameternX,thevalueof
nOperatoriscopiedintoparameternOperator,andthevalueofnInput2iscopiedintoparameter
nY.
Thefunctioncodedetermineswhichvalueisreturnedtothecaller.Thisreturnvalueisthenassignedto
variablenResult.
JoeriVandenAbeele
June10,2015at12:39amReply
ThxAlex!
crelm
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
17/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
June15,2015at10:50amReply
Hi.Iwasjustwonderingiftherewasanywaytocreateanerrormessageforthecalculator,asfrom
whatIcanunderstanditwillonlyreturn1ifyouinputanumbergreaterthan4.
Alex
June15,2015at1:17pmReply
Inthisprogram,notreally.Theproblemhereisthat1couldbeanerrorvalueoralegitimate
value,andtheresnowaytotellthedifference.
Therearemanywaystofixthisproblem.OneoftheeasiestwouldbetowriteavalidateOperator()function
thatreturnstrueifoperatorisvalidandfalseotherwise.Thenyoucoulddosomethinglikethis:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// There are better ways to write this function but I haven't introduced those co
ncepts yet
int validateOperator(int op)
{
if (op == 1)
return 1;
if (op == 2)
return 1;
if (op == 3)
return 1;
if (op == 4)
return 1;
return 0;
}
// Print result
printResult(result);
}
else
// print an error
std::cout << "operator was invalid";
Todd
June16,2015at6:32amReply
Anotherquickgrammaticalfix(userTwistedCodealludedtothis):
"Thatsamoremanageable.However,inthiscase,Doresearchoncarrotsissomewhatvague"
shouldbe
"Thatsmoremanageable.However,inthiscase,Doresearchoncarrotsissomewhatvague"
(removeabeforemoreandendquotesaftercarrotsnotvague)
Thanksforhearingfeedback!
Todd
June16,2015at7:18amReply
Sorryforbeingapaininthebutt,butheresanothergrammaticalerror:
"Thiswillofteninvolvetheuseofintermediaryvariablestotemporarystoretheresult"
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
18/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
shouldbe
"Thiswillofteninvolvetheuseofintermediaryvariablestotemporarilystoretheresult"
(changetemporarytotemporarily)
Inthefuture,Illbesuretoconsolidatemyresponsesintoonecomment.
Alex
June16,2015at10:00amReply
Fixed,thanksfortheheadsup.
cpplx
June20,2015at10:32amReply
inmain()2variablesarenamedinput1andinput2.
incalculateResult()theyarenamedxandy.
isitmethatdonotunderstandoryoumadeanoversight?
if(op==1)
arethe()apartofthec++syntax?iveusedpythonbeforeandseemsoddtome
alsoIwonderwhatif=isusedinsteadof==,butImighttestthatmyselfsomeday.probablyitwillresultinanerror
sincetheoperatorsdodifferentthings.
Alex
June20,2015at8:13pmReply
Itsokayforfunctionparameterstohavedifferentnamesthanthevariablesbeingpassedin.In
theexampleabove,xwillbeassignedthevaluefrominput1,andywillbeassignedthevalue
frominput2.
Withifstatements,theparenthesisarepartofthesyntax.
Ifyouuse=insteadof==,youlldoanassignmentinsteadofacomparison.
Youssefabdelrahman
June22,2015at7:25amReply
Hello,whenicompiletheprogramitgivesme"fatalerrorLNK1120:1unresolvedexternals"and"error
LNK2019:unresolvedexternalsymbol_mainreferencedinfunction___tmainCRTStartup".Can
anyonepleasetellmehowtosolvethiserror?
Alex
June22,2015at4:36pmReply
Itsoundslikeyoudonthaveafunctionnamedmaininyourprogram.Ifyouhaveafunction
named_tmainoranythinglikethat,replaceitwithintmain().
Rand
July9,2015at2:46pmReply
Iwaswonderingiftherewasanywaytomakethisanymoreefficient?Orsmaller?
1
2
3
4
5
#include <iostream>
int main()
{
std::cout << "Please enter 1 for Add, 2 for Subtract, 3 for Divide, 4 for Multiply.
";
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
19/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
int x;
std::cin >> x;
int q;
int w;
if (x == 1) {
std::cout << "Please enter a number: ";
std::cin >> q;
std::cout << "Please enter a second number: ";
std::cin >> w;
std::cout << "The sum is: ";
std::cout << q + w << std::endl;
return 0;
}
else if (x == 2) {
std::cout << "Please enter a number: ";
std::cin >> q;
std::cout << "Please enter a second number: ";
std::cin >> w;
std::cout << "The diference is: ";
std::cout << q - w << std::endl;
return 0;
}
else if (x == 3) {
std::cout << "Please enter a number: ";
std::cin >> q;
std::cout << "Please enter a second number: ";
std::cin >> w;
std::cout << "The quotient is: ";
std::cout << q / w << std::endl;
return 0;
}
else if (x == 4) {
std::cout << "Please enter a number: ";
std::cin >> q;
std::cout << "Please enter a second number: ";
std::cin >> w;
std::cout << "The product is: ";
std::cout << q * w << std::endl;
return 0;
}
else {
std::cout << "You did not enter a valid response. Goodbye." << std::endl;
return 0;
}
}
Alex
July9,2015at3:53pmReply
Yes,anywhereyouhaveredundancy,theresprobablyawaytogetridofit.Idmove:
1
2
3
4
Beforetheif/elsestatements.
BobZ
July17,2015at9:15amReply
Hi,Alex:
Iamstuckthistimeonyour"Step6:Writethetaskdetails"
Inyourexample,itseemstomethatwearereturning1regardless.Howarewelimitingthattoonlywhentheuser
entersaninvalidcharacter?
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
20/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
+++++++++++++++++++++++++++++++++++++++++++++++++++
Myideaforaprogramistomakeacountdowntimer.Icouldreallyuseit!Probablytoodifficultjustnowwithmy
present(lackof)skillset.
Thanksagainforyourhelp.
Alex
July17,2015at10:16amReply
Yup,thatwasamistakeonmypart.Iupdatedtheexampleinstep6tobeconsistentwith
whatwasinstep7.
Justice
July28,2015at8:16pmReply
HeyAlex,VisualStudioisgivingmeaLink2019erroraboutunresolvedexternalerrors,butifIchange
voidprintResult()tointprintResult()itcompileswithnoerrors.
Isthisabadwaytodoit,oristhisfine?
Alex
July29,2015at9:26amReply
printResult()doesntreturnanything,soitshouldhaveareturntypeofvoid.Doyouhave
printResult()declaredmorethanonceinyourprogram?
Ashley
July29,2015at7:58pmReply
HeyAlex,
IhadthesamegetUserInput(),getMathematicalOperation(),andcalculateResult()functionsasyou,butinthemain
function,insteadofassigningeachvariabletheresultfromeachfunctionandthencallingthecalculateResult()
functionusingthosevariablesasarguments,Ididthis:
cout<<calculateResult(getUserInput(),getMathematicalOperation(),getUserInput())<<endl
butthismesseduptheanswersforsubtractionanddivision.Itflippedtheanswersoinsteadof10020=80,itgave
me80andinsteadof32/16=2,itgaveme0.ThenItriedwhatyoudidandthatworkedfine.Idontunderstandwhy
callingthefunctionsasargumentsdoesntwork.Ithoughtthevaluesreturnedfromthefunctionswouldserveas
argumentsforthecalculateResult()functionwhichwouldcopyoverintothecalculateResult()functionsparameters
inorder.
Alex
July29,2015at9:21pmReply
Itsoundslikeyourepresumingthefunctionargumentswillbeevaluatedfromlefttoright,butit
turnsoutthatC++doesntspecifywhetherfunctionargumentshouldbeevaluatedlefttoright
orrighttoleft.Yoursappeartobegoingrighttoleft.
Consequently,thefirstnumbertheuserentersisbecomingthethirdparameter,notthefirst.Andthesecond
numberisbecomingthefirstparameter,notthethird.Soinsteadof10020,youregetting20100.And
insteadof32/16,youregetting16/32(whichis0.5,whichgetstruncatedto0becauseweredealingwith
integershere).
Inshort,callinggetUserInput()twiceinsequencebeforecallingcalculateResult()guaranteesaparticular
ordering.UsinggetUserInput()asargumentsdoesnot.
Iapplaudyourcreativityandunderstandingofinputsandoutputs.YoujusthappenedtorunintooneofC++s
quirks.
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
21/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Matthew
August4,2015at8:46amReply
SoIhavethecodeprettymuchhowyouhaveitabove,yetwhenIenterintegersandoperators,it
alwaysdoesadditionnomattermychoice.IvetriedwritingviaVimandcompilingviacommandline
usingg++andviaCode::Blocks(Iknowitusesthesamecompiler),andithappensinVS15Community.
Mycodeis:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<iostream>
int getInteger()
{
std::cout << "Enter an integer:" << std::endl;
int value;
std::cin >> value;
return value;
}
int getOperator()
{
std::cout << "Please enter an operator (1 = +, 2 = -, 3 = *, 4 = /)" << std::endl;
int op;
std::cin >> op;
return op;
}
int main(void)
{
int input1 = getInteger();
int op = getOperator();
printResult(result);
}
Matthew
August4,2015at9:03amReply
Cleanedmycodeabit,sameproblem:
1
2
3
4
#include<iostream>
int getInteger()
{
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
22/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
int getOperator()
{
std::cout << "Please enter an operator (1 = +, 2 = -, 3 = *, 4 = /)";
int op;
std::cin >> op;
return op;
}
int main()
{
int input1 = getInteger();
int op = getOperator();
printResult(result);
}
Alex
August4,2015at12:46pmReply
Thisoneworksfineforme.
Matthew
August4,2015at9:44amReply
Oddlyenough,thisworksfine:
1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
int getTemp()
{
cout << "What is the temperature (integer only)" << endl;
int temp;
cin >> temp;
return temp;
}
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
23/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
int convert()
{
cout << "Are you convering to fahrenheit or celsius (1 = fahrenheit, 2 = cels
ius)?" << endl;
int conv;
cin >> conv;
return conv;
}
int main()
{
int input = getTemp();
int op = convert();
printResult(result);
}
Alex
August4,2015at12:45pmReply
1
2
if (op == 1);
return x + y;
Youhaveawaywardsemicolonafteryourfirstifstatement.Thisistheequivalentofwriting:
1
2
3
if (op == 1)
; // do nothing
return x + y;
Whichalwaysreturnsx+y.
JoaoLopes
August26,2015at1:52pmReply
Canyoutellmewhatyouthinkaboutthiscode.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "stdafx.h"
#include <iostream>
int getMathematicalOperation()
{
int mO;
cin >> mO;
return mO;
}
int getUserInput()
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
24/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
{
int input;
cin >> input;
return input;
}
return -1;
}
int main()
{
//Ask the user wich mathematical operation he wants to execute
cout << "Wich mathematical operation you want to execute?" << endl
<< "| 1 for addition | 2 for subtraction | 3 for multiplication | 4 for divisio
n |" << endl;
int mO = getMathematicalOperation();
//A code that forces the user to press Enter to close the program
cin.get();
cout << "Press Enter to exit";
cin.ignore(32767, '\n');
return 0;
}
Alex
August27,2015at9:05amReply
ItsexactlywhatIdexpectsomeonewhohasagoodgraspoftheconceptssofartowrite.
Niceuseoffunctions.
JoaoLopes
August26,2015at3:33pmReply
DidsomeresearchaboutrepeatingfunctionsetcandgotthismadeIthinkitsgoodimo.
CantellmewhatyouthinkaboutitsryforspammingIgotveryinterestedinc++programming,andI
dontcarryonuntilItryalmosteverythingthatcomestomymind.xD
1
2
3
4
5
6
7
8
9
#include "stdafx.h"
#include <iostream>
int getMathematicalOperation()
{
int mO;
cin >> mO;
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
25/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
if (mO == 1)
cout << "You choosed addition" << endl;
if (mO == 2)
cout << "You choosed subtraction" << endl;
if (mO == 3)
cout << "You choosed multiplycation" << endl;
if (mO == 4)
cout << "You choosed divison" << endl;
return mO;
}
//This will get the user input (still dont know how to ignore characters like abcd...)
int getUserInput()
{
int input;
cin >> input;
return input;
}
//This will calculate the result of the values that the user choosen.
int calculateTheResult(int mO, int x, int y)
{
if (mO == 1)
return x + y;
if (mO == 2)
return x - y;
if (mO == 3)
return x * y;
if (mO == 4)
return x / y;
return -1;
}
int main()
{
//Ask the user wich mathematical operation he wants to execute.
cout << "Wich mathematical operation you want to execute?" << endl
<< "| 1 for addition | 2 for subtraction | 3 for multiplication | 4 for divisio
n |" << endl;
int mO = getMathematicalOperation();
//If the user input is higher than 5 it means nothing the porgram will repeat it se
lf.
if (mO >= 5)
{
system("cls");
cout << "You choosed a wrong value repeating program..." << endl << endl;
main();
}
//A code that forces the user to press Enter to close the program
cin.get();
cout << "Press Enter to exit";
cin.ignore(32767, '\n');
return 0;
}
Alex
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
26/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
August27,2015at9:08amReply
Didyoutestwhathappenswiththisprogramifyouenteranumbergreaterthan5?
Forwhatitsworth,recursion(havingafunctioncallitself)usuallyisntthebestwaytodoa
loop.C++hasloopstructures(coveredinchapter5)forthis.Wehaventcoveredthemyet,sogladtosee
youexploring.
Joseph
September19,2015at6:22pmReply
HeyIbelieveIscrewedsomethingupincodeblocksandthisisrathertrivial.ButwhenIstartanew
projectnofilescomeupthepartofthescreenwherecodeiswrittenhasnothinginitandwhenI
createanewfileIamaskedtonameitandthereisafilenamedmainalreadythere.SoIdecidedtostartfromthe
beginning,createdanewproject,andopenedmaindirectlyfromthere.Icopyandpastedcodetocheckandwhen
builtandranIgetthehelloworldprogram.
IalsogetthatIhavemain()definedmorethanonceinmultifileprojects.anysuggestions?
Alex
September20,2015at5:22pmReply
Youcanonlyhaveonemain()functionperproject.Thatmeansifyouwanttochange
programs,youeitherneedtooverwriteyourcurrentmain(),oryouneedtocreateanewproject.
Daniel
October4,2015at3:39amReply
Hi,
TheresultsofadivisionarerarelyanintegersoItriedtochangetheoutputtoafloat
calculateResults.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
if (mathOperator == 1){
a = x+y;
return a;
}
if (mathOperator == 2){
a=x-y;
return a;
}
if (mathOperator == 3){
a=x*y;
return a;
}
if (mathOperator == 4){
a = x/y;
return a;
}
else return 9;
mymath.h
1
2
3
4
5
#ifndef ADD_H
#define ADD_H
#include<stdio.h>
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
27/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
6
7
8
9
10
11
12
#endif /* add_hpp */
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include "mymath.h"
int main() {
using namespace std;
int firstNumber;
firstNumber = getUserInput();
int mathOperator;
mathOperator = getMathOperator();
int secondNumber;
secondNumber = getUserInput();
float calculationResult;
calculationResult = calculateResult(firstNumber, secondNumber, mathOperator);
float testDecimal (3.141);
cout << "The result of the calculation is: " << calculationResult << endl;
cout << "The calculation result has a size of: " << sizeof(calculationResult) <<end
l;
cout << "TestDecimal is: " << testDecimal << endl;
return 0;
}
The(constant)variabletestDecimaloutputsasafloatbutcalculationresultsdoesnt.
WhatamIdoingwrong?
Alex
October4,2015at11:01amReply
Wewillcoverthisinthenextchapterwhenwediscussintegers,floats,anddivisioninmore
detail.Keepreading.
Daniel
October4,2015at11:39amReply
ThanksandGREATcoursebytheway
Goku
October4,2015at5:56pmReply
Greatadviceandtips,ThankYou
Alex(Sp)
October8,2015at11:21pmReply
SoIdecidedtoaddadowhilelooptoyourgetMathematicalOperationfunctiontocheckforthecorrect
value.InoticedthatIforgottoaddthereturnstatementattheendofthefunction,yeteverything
works?Idontunderstand.
1
2
3
4
int getMathematicalOperation()
{
int op;
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
28/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
5
6
7
8
9
10
11
12
13
do {
std::cout << "Please enter which operator you want (1 = +, 2 = -, 3 = *, 4 =
/): ";
std::cin >> op;
}
while (op != 1 && op != 2 && op != 3 && op != 4);
//return op;
}
Usingthisfunctionintheprogramwiththereturnstatementcommentedouttheprogramstillcompilesandexecutes
correctly.Howaremyotherfunctionsabletousethe"op"thatisdefinedinmain?
Devashish
October9,2015at5:13amReply
ExecutesCorrectly?Itwillcompilebecauseitsokayifanonvoidfunctionomitsreturn
statement,butifthecallerworkswiththedatareturnedbythefunction,itwillalwaysproduce
unexpectedresults.WhenIrunyourprogram,itgives1asresult.
Alex(Sp)
October9,2015at8:36amReply
YeahitsweirdIdontgetit.Ijustcompiledandranitagainanditalwaysworkscorrectly
formeevenwiththatreturncommentedout.Everytime.
Fullprogram:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
int getUserInput()
{
std::cout << "Please enter an integer: ";
int value;
std::cin >> value;
return value;
}
int getMathematicalOperation()
{
int op;
do {
std::cout << "Please enter which operator you want (1 = +, 2 = -, 3 =
*, 4 = /): ";
std::cin >> op;
}
while (op != 1 && op != 2 && op != 3 && op != 4);
//return op;
}
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
29/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
int main()
{
// Get first number from user
int input1 = getUserInput();
// Print result
printResult(result);
}
DoesntmakeanysensethatIalwaysgetthecorrectcalculation.
Alex
October9,2015at2:39pmReply
Afunctionwithanonvoidreturnvaluethatdoesnothaveareturnstatementis
invalidsyntax,andshouldnotevencompile.Thefactthatyourcompilerisnot
flaggingthisasanerrorisworrying.Whatcompilerareyouusing?
WithVisualStudio,Igetthiserroruponcompilation:
errorC4716:'getMathematicalOperation':mustreturnavalue
(Note:somecompilersdoallowyoutoomitareturntypeformainthisisntofficiallyallowedby
C++butsomecompilersdoitanyway.Thisdoesnotextendtoothernonmainfunctions).
Itsuncleartomewhetheryourcompilerisignoringthecommentinthiscase,orwhetheritsjust
workingcoincidentallyduetothewaythecompilerissettingupfunctioncall.
Alex(Sp)
October9,2015at10:38pmReply
IinstalledtheMinGWGCCsuite.EvenstrangeristhatIcanremovethe
commentedoutreturncompletelyanditstillworks.Imsuperconfused.
Alex
October10,2015at6:20pmReply
StackOverflowhassomethoughtsonwhatshappeninghere.See:
http://stackoverflow.com/questions/4644860/functionreturnsvalue
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
30/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
withoutreturnstatement.
Alex(Sp)
October11,2015at3:50pmReply
Gotcha!CompilingwithWallWerrorshowsmethecorrecterrorand
stopssoIcanactuallyfixeverything.
Amin
November17,2015at11:27pmReply
InthenameofGod
Hi,VerythanksofYouandyourtimeandkindness.
andthanksforsharingyourinformation,Studies,Lessons,Experiencesandallofotherthings.
GodBlessYou,
HopetoGod
Anthony
December27,2015at2:21amReply
HeyIstartedthislastnight,Ihavetosay,itsbeengreatsofar.Imwritingthisnowbecauseinstead
offollowingwhatyouputonthere,Idecidedtousemultiplepagesforthecalculator.Iendedup
runningintoanissueIneverfiguredouthowtofix,andthatwashavingavoidonaseparatepageforthe
printResult.Ifoundasolution,butitreallydidntappeasewhatIwastryingtodo.
Fix:movethevoidfunctionontomain.cppanddeleteprintResult.cpp
SoImaskingforfutureprojects,isitpossibletohaveavoidonaseparatepage?Isitbadpractice?
Forreference:Imadeonepageperfunction,honestlytotryandcreateerrorsthatIcouldtrytotroubleshootrather
thenfollowthecodegiventome.ItwasarandomthoughtbecauseImahandsonlearnerandIfigured
troubleshootingissueswouldhelpmesignificantlyinthelongrunbecauseIcouldgraspwhaterrorsoccuratwhat
stages.
Alex
December28,2015at3:34pmReply
ImnotsurewhatyoumeanbyhavingavoidonaseparatepagefortheprintResult?
Morgan
January11,2016at10:52amReply
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// // // // //
#include "stdafx.h"
#include <iostream>
#include <string>
// // // // //
int num();
void fin(int n);
int YN();
// // // // //
int main(int e)// main function, the int e is
for a return value of 0 when reuse is declined in the YN()
{
if (e == 5)
return 0;
using namespace std;
cout << "Calculator!" << endl;// Announce it to the world!
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
31/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
NevermindIspentlastnightfixingitandmakingitshine.
Alex
January11,2016at5:30pmReply
Imnotsureaboutthetext.Soundslikeghosts.
Asforyouruseofcomments,Ithinktheyrestilltoovague.Whatdoes//FirstNumbermean?Isitaskingthe
user?Readingitfromdisk?Getfirstnumberfromuserwouldbemoreinsightful.Theerrormessagecaseisclearly
anerrormessage,soitdoesntneedacomment.
Also,forwhatitsworth,yougenerallywontwantmain()tocallmain().Inthiscase,ifyoufirstinputis54321and
thenyoursecondinputisvalid,Ithinkyourprogramwillnotoperateasexpectedintermsofprintingtheresult.
Akanksha
January24,2016at11:18pmReply
thankyou..afteralongtimefoundsuchausefultutorial
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
32/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Pierre
February25,2016at6:30pmReply
Ifeelthatthereissomethingtobesaidaboutversioncontrol.Emailingsourcecodearoundisntbet
practice,keepingitinversioncontrolismuchbetter.Noneedtodivetoodeepintheexplanations
(therearetonsofverygoodtutorialsaboutgitforinstance)butmentioningthatitismuchmorepreferableto
emailingfilesaroundorcopyingdirectorieswouldmakesenseIMHO.
Thanksforthedetailsabouttopdownandbottomup,itsthroughlyexplained.
Chuck
April5,2016at4:42pmReply
Thismightbeveryconfusing,butwoulditresultinmoreoptimizedcode?
1
printResult(calculateResult(getUserInput(), getMathematicalOperation(),
getUserInput()));
Alex
April7,2016at11:58amReply
Possibly,dependingonwhetheryourcompileroptimizesitwellornot.Butyoushouldgenerally
bewritingyourprogramsforunderstandability,notforperformance.Youcanalwaysoptimize
later,ifyouneedto(mostofthetime,youwont).
Karl
April6,2016at5:52amReply
canyoupleasetellwhyweusedvoidherecantwesimplyprintthevalueusingcoutinmain?
1
2
3
4
Alex
April7,2016at12:10pmReply
Thefunctionreturnsvoidbecauseitdoesnotpassavaluebacktothecaller.Itjustdoesajob
(printsthestring)andreturns.
Wecouldhaveprintedthevalueinmain,butusingafunctionisoftenbetterbecauseitseasiertodebug,
modify,andcallmultipletimes.
Nyap
April11,2016at8:09amReply
Designingyourprogramandorganisingthecodeintomultiplefilesseemsprettyboringtome
Alex
April11,2016at12:22pmReply
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
33/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Itis,whichiswhymanypeopleskipit.Thiscanleadtopoorlystructuredcode,andalotofreworkdownthe
line.
Thegoodnewsisthatyoueventuallygetgoodatit,soitbecomessecondnature.
Liam
April16,2016at5:23pmReply
Pleasehelp,VS2015CistellingmethattheidentifierresultisundefinedwhenItryanduseitin
main.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "stdafx.h"
#include
int getVariable()
{
cout << "Give me a variable: " <> var;
return var;
}
int getOperator()
{
cout << "Chose an operator(1=+, 2=-, 3=*, 4=/): " <> op;
return op;
}
return -1;
}
int main()
{
int var = getVariable();
int op = getOperator();
int var2 = getVariable();
int calcResult = calculateResult(var, op, var2);
cin.clear();
cin.ignore(32767);
printResult(result); //An error is shown when using (result) here. The output is te
lling me: "identifier "result" is undefined"
cin.get();
}
Alex
April17,2016at2:54pmReply
Variableresultdoesnotexistinthescopeoffunctionmain.Theparameterresultthatyouve
definedinfunctionprintResult()onlyexistswithinfunctionprintResult()maincannotaccess
itdirectly.
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
34/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Infunctionmain,resultshouldprobablybecalcResult.
Cameron
May13,2016at3:29amReply
HiAlex,firstupthisisafantastictutorial,reallylikethewayyouexplainthereasoningbehinddoing
things.Iveputtogethercodeforthiscalculatorandmymultiplication/divisiontasksgiveme
addition/subtractionrespectively.Triedsteppingaheadandhavingacrackatdebuggingitandcouldntfigureitout.
CanyoutellmewhereIvegonewrong?(Noteoriginallyitwasinseparatefileswithaheaderfile,butitcompiled
finethatwayandwhenIcopieditallintoonefileIhadthesameproblem.Thanksinadvance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
int getUserInput()
cout << "Input a number: " << endl ; //asks user for a number
int value ; //creates storage for x
cin >> value ; //stores user input as x
return value ;//sends x to main()
int getMathematicalOperation()
cout << "Enter desired operator (1 = +, 2 = -, 3 = x, 4 = /):" << endl ; //asks for
integer to stand in for the operator
int op ; //creates y
cin >> op ; //stores input (operator) in y
return op ; //sends y to main()
{
if (op == 1) ;
return x + y ;
if (op == 2) ;
return x - y ;
if (op == 3) ;
return x * y ;
if (op == 4) ;
return x / y ;
return -1 ;
cout << "Answer = " << result << endl ; //prints answer
int main()
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
35/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//calculate result
int result = calculateResult(input1, op, input2) ;
//print result
printResult(result) ;
return 0 ;
Icantfigureouthowtotagmycodesorry,notagreatsignIguess.
Alex
May13,2016at2:20pmReply
Youhavesomeextraneoussemicolons:
1
2
Dothesameforyourotherifstatementsaswell.
Cameron
May14,2016at11:00pmReply
Ahright,thanksalot.
Alex_Rocks
May26,2016at3:01pmReply
Weirdquestionthatrequiressetup:
Itsinterestingtonotethatifyoucollapsethemain()intoonelinetheprogramwillstillrundespiteusingthesame
functioncalltwicewithoutstoringthevariables.
Itwillhoweveraskyoufortheinputsfromrighttoleft(thefunctioncallintheyargumentslotof
calculateResult(x,op,y)iscalled1st,thenopthenx).
1
printResult(calculateResult(getUserInput(), getMathematicalOperation(),
getUserInput()));
Question:
How/wheredoesitimplicitlystorethevaluesforthesefunctioncallsifIhaventexplicitlyassignedamemory
locationforthemviaadefinitionstatement(intvariable=function())?
Minorquestion:
HowdoImakepastedcodelookallprettywiththelinenumbersandformattingiseeinotherposts?
Alex_Rocks
May27,2016at1:13pmReply
Nevermindthatisprobablyacompilerspecificquestion(VisualStudio2015).
Alsotheminorquestiongotansweredwhentheeditclockranoutandthecodedisplayedcorrectly.
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
36/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
Sorrytobother,Thanksforreadinganyway.
Alex
May28,2016at11:32amReply
Theorderinwhichfunctionparametersareevaluatedisundefined.Itcouldbelefttoright,or
righttoleft.
Ifyouusethereturnvaluefromonefunctiondirectlyasanargumentforanotherfunction,thecompilerwill
createaanonymous(unnamed)variableforyoutofacilitatethehandoff.
Itlookslikeyoufiguredoutthecodeformattingalready.
Brent
June4,2016at4:25pmReply
WhenIusetheexamplecalculatorprograminthetutorial,whenIenterthesecondnumberitprints
theanswerandclosesreallyfast.
ThisonlyhappenswhenIusethe.exefile,whenIctrl+F5inMicrosoftVisualBasic2015itprintsPressEnterto
continue....
WhatisgoingwrongandwheredoesitgetthePressentertocontinue...?
Alex
June5,2016at7:11pmReply
TheIDEispausingyourconsoleapplicationattheend,soyoucanseeanyoutputbeforethe
consolewindowcloses.Ishowamethodtodoyourownpausinginlesson0.7.
strong
June13,2016at11:15amReply
inthisprogram:
main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std ;
#include "readInt.h"
#include "readOperand.h"
#include "doOperation.h"
int main()
{
int x= readInt();
int op = readOperand();
int y= readInt();
int result = doOperation(x,op,y);
cout << result ;
return 0 ;
}
readInt.cpp:
1
2
3
4
5
6
7
int readInt()
{
cout << "please enter Integer : ";
int a;
cin >> a;
return a;
}
readInt.h:
1
#ifndef READ_INT
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
37/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
2
3
4
#define READ_INT
int readInt();
#endif // READ_INT
andtherestoffileslikethis,whyIgetanerror:
||===Build:Debuginpractice3(compiler:GNUGCCCompiler)===|
/home/strong/Documents/C++/practice3/readInt.cpp||InfunctionintreadInt():|
/home/strong/Documents/C++/practice3/readInt.cpp|3|error:coutwasnotdeclaredinthisscope|
/home/strong/Documents/C++/practice3/readInt.cpp|5|error:cinwasnotdeclaredinthisscope|
||===Buildfailed:2error(s),0warning(s)(0minute(s),0second(s))===|
A1R
June15,2016at6:51amReply
Youshould
1
#include <iostream>
withinanyfilesusingcommandsfromtheiostreamlibrary.
Alsomakesureyouadd
1
tothetopofreadInt.cppsinceyourejustusingcout.
(Ibelievethiscanbedoneoutsideofthefunction?)
A1R
June15,2016at7:32amReply
Sayiwantedtoprintanerrormessagewhentheuserinsertedaninvalidnumberforoperator5or6
etc..
Howwouldigoaboutit?
1
2
3
4
5
6
7
8
9
10
11
12
13
Idontwanttoreturnanumberbecausethatonetimeanumberisthesameasthereturnvalueitllsaythesyntax
isinvalid.
1
2
3
4
5
6
7
Alex
June16,2016at4:55pmReply
Thisisaslightlymoreadvancedtopic,asthetechniquesusedtodothiskindofthinginvolve
additionalknowledgethatthetutorialhasntcoveredyet(sothistopiciscoveredinfuture
tutorials).Buttoenumeratesomepossibilities:
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
38/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
*Haveyourfunctionreturnaboolindicatingsuccess,andreturnthecalculatedvalueasareference
parameter.
*Assertoutiftheuserpassesinaninvalidoperation
*Throwanexceptioniftheuserpassesinaninvalidoperation
Dontworryiftheabovedoesntmakesenseyetwellcoverallthesethingsintime.
gurparkash
June25,2016at6:05amReply
Mycodeisthis.Andtheproblemisthatitfirstasksme"Enteranotherinteger"andtheasksme
"enteraninteger."Whatstheproblemhere?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
using namespace std ;
int value1()
{
cout << "Enter a number." << endl ;
int a ;
cin >> a ;
return a ;
}
int operator1()
{
cout << "Enter a mathematical operator." << endl ;
cout << "(1 = + , 2 = - , 3 = * , 4 = /)" << endl ;
int a ;
cin >> a ;
return a ;
}
int value2()
{
cout << "Enter another number." << endl ;
int a ;
cin >> a ;
return a ;
}
return -1 ;
}
/*void print()
{
cout << "The answer is:" << calculator(int x , int y , int z) ;
}*/
int main()
{
/*value1() ;
operator1() ;
value2() ;*/
cout << "The answer is:" << calculator(value1() , operator1() , value2()) ;
//print() ;
return 0 ;
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
39/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
56
Alex
June26,2016at11:03amReply
C++doesnotdefinetheorderinwhichfunctionargumentsareprocesseditcouldbeleftto
rightorrighttoleft.Inyourcase,itlookslikeitsrighttoleft,sovalue2()isgettingevaluated
beforevalue1().
gurparkash
June26,2016at5:44pmReply
Isthereanywaytocorrectthis,otherthantoofcourseinterchangetheirplaces?Andis
myprogramfine?Pleasetellmewhatimprovementscanbemade.
Alex
June27,2016at3:46pmReply
Youshouldntinterchangetheirplaces,becauseothermachinesmayuseadifferentorderof
evaluationthanyours.
Therightwaytofixthisistoexplicitlydefinetheorderinwhichthesearecalled:
1
2
3
int v1 = value1();
int v2 = value2();
cout << "The answer is:" << calculator(v1, operator1() , v2) ;
Thisway,theorderingisexplicitandunambiguous.
Andrew
June27,2016at11:27pmReply
"Thatsmoremanageable,aswenowhavesubtasksthatwecanfocusonindividually.However,in
thiscase,Doresearchoncarrotsissomewhatvague,sowecanbreakitdownfurther:"
ThefragmentisfromStep3andcontainsatypo.Shouldbe:
"Thatsmoremanageable,aswenowhavesubtasksthatwecanfocusonindividually.However,inthiscase,Do
researchoncarrotsissomewhatvague,sowecanbreakitdownfurther:"
P.S.Thanksforthetutorial!Sofarsogreat.
Alex
June28,2016at4:30pmReply
Fixed.Thanks!
TristanGybels
July1,2016at11:07amReply
1
2
3
4
5
6
7
8
#include "stdafx.h"
#include <iostream>
int GetNumber()
{
cout << "Enter your number: ";
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
40/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
int x;
cin >> x;
return x;
}
char GetMathOperator()
{
cout << "Choose one of these operators: '+', '-', '*' & '/': ";
char x;
cin >> x;
return x;
}
int main
{
int IntOne = GetNumber();
char CharOp = GetMathOperator();
int IntTwo = GetNumber();
int Result = GetResult(int IntOne, char CharOp, int IntTwo);
int PrintResult(Result);
}
Doessomeoneknowwhythiscodedoesntwannawork?
Alex
July1,2016at12:27pmReply
Twothingslookwrong:
1
2
int Result = GetResult(int IntOne, char CharOp, int IntTwo); // don't need int bef
ore IntOne, char before CharOp, or int before IntTwo
int PrintResult(Result); // don't need int before PrintResult
TristanGybels
July1,2016at2:23pmReply
Thankyou Ialsonoticedtheforgotten()aftermain.
TristanGybels
July1,2016at2:17pmReply
1
2
3
4
5
#include "stdafx.h"
#include <iostream>
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
41/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
int GetValue()
{
cout << "Enter your " << /*How to make it show 'first' during process 'one' and 'se
cond' during process 'two'?*/ " number: ";
int x;
cin >> x;
return x;
}
char GetOperator()
{
cout << "Enter an operator: ";
char x;
cin >> x;
return x;
}
int main()
{
int one = GetValue();
char op = GetOperator();
int two = GetValue();
int result = GetResult(one, op, two);
cout << one << " " << op << " " << two << " = " << result <<endl;
}
ReadThecommentonline9
Cansomeonehelpmehowtodothat?withoutaddingasecondGetValue?
Alex
July2,2016at3:05pmReply
TheeasiestwayrightnowistocreateagetFirstValue()functionandagetSecondValue()
function,andchangehowtheyprompttheuser.
Theotheroptionistopassinabooleanparameterindicatingwhetherthisisthefirstorsecondcall,anduse
ifstatementstodeterminewhattoprintbasedonthevaluethatparameterhas.Butwehaventcovered
booleansorifstatementsatthispointinthetutorial.
Priyanga
July24,2016at7:43pmReply
Thanksalot!Thisisveryhelpfulandarichtutorialandhashelpedmealot.Anditwillforalotof
people!
Josh
July25,2016at12:49amReply
Hello,Iexactlycopiedthecodeyoumadehere.Imusingvisualstudio2015version14update3.
Thankyoufortheinformativetutorial.ButImmissingsomething.Itdoesntwanttoshowtheresultonmyscreen.
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
42/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
InoticedIdonthavestdafx.handwhenI#includeit,italwaysgivesanerror.SoIincludedanemptyfileinstead.
Iwanttoprinttheresult,Iwanttoseitinthescreenbutitwontshow.Icanencodethenumbersfine,butafterthe
2ndnumber,itjustdisappears.ItriedtouseMaksismscodeaboveanditprintsuntilitgivesmetheresult,but
minedoesnt.Pleasehelp.
Mycodeis:
#include<iostream>
#include"stdafx.h"
usingnamespacestd
intgetUserInput()//askinputfromuser
{
cout<<"Pleaseenteraninteger"
intinput
cin>>input
returninput
}
intgetMathematicalOperation()//equateintegertooperator
{
cout<<"Pleaseselect1=+,2=,3=*,4=/"
intop
cin>>op
returnop
}
intcalculateResult(intx,intop,inty)
{
if(op==1)//ifuserchose#1
returnx+y
if(op==2)//ifuserchose#2
returnxy
if(op==3)//ifuserchose#3
returnx*y
if(op==4)//ifuserchose#4
returnx/y
return1//default"error"valueincaseuserpassedinaninvalidop
}
voidprintResult(intresult)
{
cout<<"Yourresultis"<<calculateResult<<endl
}
intmain()
{
//Getfirstnumberfromuser
intx=getUserInput()
//Getmathematicaloperationfromuser
intop=getMathematicalOperation()
//Getsecondnumberfromuser
inty=getUserInput()
//Calculateresult
intresult=calculateResult(x,op,y)
cout<<"Theresultis"<<result<<endl
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
43/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
//Printresult
printResult(result)
return0
}
Alex
July30,2016at6:06pmReply
ItsoundslikeyourIDEisclosingtheconsolewindowattheendoftheprogram,soyoucant
seetheoutput.Ishowasolutiontothisinlesson0.7.
MatthieuB.
July29,2016at12:09amReply
Youforgot"Getdressed"intheorganizedlistinstep3,whichisterriblyunimportantforthe
understandingoftherestofthistutorial.
Alex
July30,2016at10:56pmReply
Thanksforpointingthatout.Wewouldntwantyoutogotoworknaked.
Josh
July29,2016at8:19pmReply
Ok,soIcopiedmaksimsendcodefromthecin.cleartocin.get.Icanseetheresultnowbutmy
resultlookslikeacolorcodeinsteadofaninteger.a1+1equationgivesme0093146A.Whydoesit
dothis?Pleasehelp
Imusingvisualstudioversion14update3.stdafx.hisnotavailableandIincludedablankheaderassuggested.but
evenifIdelete#includestdafx.hitstillcompilesandrunsbutwiththesameequation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include "stdafx.h"
int getNumber2()
{
cout << "Please enter second number: "; //Getting second number
int y;
cin >> y;
return y;
}
int calculateResult(int x, int op, int y)
{
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
44/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
return 0;
}
Alex
July30,2016at11:30pmReply
BecauseprintResult()isprintingcalculateResultinsteadofresult.calculateResultisa
function,notavariable,soitsprintingtheaddressinmemorythatfunctioncalculateResult
livesat.
Satwant
August10,2016at8:18amReply
Aboveexampleusingheaderfile:XD~
//howToWriteaProgramEg.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "stdafx.h"
#include <iostream>
#include "writeprogrameg.h"
int main()
{
int value1 = getInput();
int value2 = getInput();
int op = getOperator();
int result = calculateResult(value1, op, value2);
printResult(result);
return 0;
}
//getinput.cpp
#include "stdafx.h"
#include <iostream>
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
45/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
int getInput()
{
using namespace std;
cout << "Please enter a Digit value : ";
int value;
cin >> value;
return value;
}
//getoperator.cpp
#include "stdafx.h"
#include <iostream>
int getOperator()
{
using namespace std;
cout << "Please enter a valid Digit between 1 and 4." << endl;
cout << "Press 1 for addition operation." << endl;
cout << "Press 2 for subtraction operation." << endl;
cout << "Press 3 for multiplication operation." << endl;
cout << "Press 4 for division operation." << endl;
int op;
cin >> op;
return op;
}
//calculateresult.cpp
#include "stdafx.h"
return -1;
//printresult.cpp
#include "stdafx.h"
#include <iostream>
int getInput();
int getOperator();
int calculateResult(int value1, int op, int value2);
void printResult(int result);
#endif
AhmedGurie
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
46/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
August11,2016at4:20amReply
IhavenoenoughwordstothankyouAlex,youaregreat
ObiWan
August12,2016at6:29amReply
Isimplyjustmadeitallintoonefunctioninmy2nd.cppfile.Isthereanydrawbacksfromdoingitthis
way?Also,Imstrugglingwithunderstandingtheusageofheaderfilesandusingprototypesandetc!
Butgreattutorialnonetheless,Imjustslow!Lol.AnywayhereisthecodeIfunctionImadeonmy2ndcpp.
#include"stdafx.h"
#include<iostream>
#include"add.h"
intadd(intx,inty)
{
returnx+y
}
intgetUserInput()
{
std::cout<<"Inputanumberhere"<<std::endl
inta=0
std::cin>>a
std::cout<<"Nextnumberis"<<std::endl
intb=0
std::cin>>b
std::cout<<"Last,pickanoperator.1=+,2=,3=*,4=/"<<std::endl
intc=0
std::cin>>c
if(c==1)
{
std::cout<<a+b<<std::endl
returna+b
}
if(c==2)
{
std::cout<<ab<<std::endl
returnab
}
if(c==3)
{
std::cout<<a*b<<std::endl
returna*b
}
if(c==4)
{
std::cout<<a/b<<std::endl
returna/b
}
}
Alex
August12,2016at5:27pmReply
Themaindrawbacksare:
*Yourfunctionislongerandmorecomplicatedthanitneedstobe.
*Yourfunctiondoesnthaveanyreusableparts(ifyouwantedtheusertoenteranumberforsomeother
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
47/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
reason,youdhavetoduplicatecodeorrefactoryouroriginalfunction).
*Yourenotpracticinggoodfunctioncomposition,whichishelpfullaterwhenwegetintomorecomplicated
examples.
Noneofthesearecriticalissues,morelikewarnings.
ObiWan
August12,2016at5:37pmReply
ThanksforthereplyAlex!Imgoingtotryandfollowyourinstructionsmoreclosely
throughout
ArjunSrivastav
August18,2016at11:16amReply
Hello.Thankyouforthesetutorials.Youmentionedforbeginnerstowriteasmallportionanddebug,
continuouslyuntiltheend.WhenIcompileandtheneditmyprogram,myIDECode::Blocksdoesnot
allowittobecompiled.Whyisthatso?
Alex
August18,2016at8:34pmReply
Ihavenoidea.Youcancompileyourprogramonce,butthenwhenyoumodifytheprogram,
youcantcompileitagain?Isitgivingyouanyerrormessages?
ArjunSrivastav
August20,2016at4:18amReply
HiAlex.Iamtryingtowriteacompoundinterestcalculator.Theproblemis:itisnotcompiling.what
maybetheproblem.Hereisthecode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cstdio>
#include <cstdlib>
int InterestRate;
cout << "Please enter the interest rate as a decimal";
cin >> InterestRate<<endl;
int InterestDensity;
cout << "Please enter the number of times interest is compounded per year";
cin >> InterestDensity<<endl;
int NumberofYears;
cout << "Please enter the number of years the money is borrowed for";
cin >> NumberofYears<<endl;
int Accumulation;
Accumulation=Principle*(1+(InterestRate/InterestDensity)^(InterestDensity*NumberofYea
rs);
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
48/49
10/8/2016
1.10bHowtodesignyourfirstprogramsLearnC++
32
Alex
August21,2016at6:48pmReply
Yourcompilershouldbetellingyouexactlywhatswrong.
Butinshort:
1)Yourmainfunctionismissingaparameterlist
2)Youreusing<<endlwithcin,whichdoesn'twork.
Rahul
October6,2016at10:29pmReply
HeyAlex,
1.Whyprogramexecutionstartfrommain()functiononly?
2.HowOperatingSystemcometoknowthattostartprogramexecutionfrommain()function?
3.Canwechangenameofmain()function?
LearnHowtoProgram
GenericProgramming
GetJavaProgrammingCode
ProgrammingTechniques
http://www.learncpp.com/cpptutorial/110bhowtodesignyourfirstprograms/
49/49