22
Another Simple Program: Adding Two Integers

Another Simple Program: Adding Two Integers

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

Page 2: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  Thisprogramusestheinputstreamobjectstd::cinandthestreamextrac<onoperator,>>,toobtaintwointegerstypedbyauseratthekeyboard,computesthesumofthesevaluesandoutputstheresultusingstd::cout.

Note:‘<<‘iscalled‘inser<onoperator’

Page 3: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  Variabledeclara0on:

•  number1,number2,sumarethenamesofvariables•  Avariableisaloca<oninthecomputer’smemorywhereavalue

canbestoredforusebyaprogram.•  Thesedeclara<onsspecifythatthevariablesnumber1,number2,

andsumaredataoftypeint,meaningthatthesevariableswillholdintegervalues,i.e.,wholenumberssuchas7,–11,0and31,914.

•  Allvariablesmustbedeclaredwithanameandadatatypebeforetheycanbeusedinaprogram.

•  Severalvariablesofthesametypemaybedeclaredinonedeclara<onorinmul<pledeclara<ons.Wecouldhavedeclaredallthreevariablesinonedeclara<onbyusingacomma-separatedlistasfollows:int number1, number2, sum;!

Page 4: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  Variable’sname– Aseriesofcharactersconsis<ngofleQers,digitsandunderscores(_).

– DoesNOTbeginwithanumber.– C++iscasesensi<vei.e.,uppercaseandlowercaseleQersaredifferent,soa1andA1representdifferentvariables.

– MustNOTbeaspecialcharactere.g.,&,%,$,… – MustNOTbeakeyword.(Whatisakeyword?)

Page 5: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  Variable’stypes–  We’llsoondiscussthetypefloatforspecifying

decimalnumbers,andthetypecharforspecifyingcharacterdata.•  Decimalnumbersarenumberswithdecimalpoints,

suchas3.4,0.0and–11.19.•  Acharvariablemayholdonlyasinglelowercase

leQer,asingleuppercaseleQer,asingledigitorasinglespecialcharacter(e.g.,$or*).

–  Typessuchasint,float,andchararecalledfundamentaltypes.

–  Fundamental-typenamesarekeywords.

Page 6: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  PlacementofVariableDeclara0ons– Declara<onsofvariablescanbeplacedalmostanywhereinaprogram,buttheymustappearbeforetheircorrespondingvariablesareusedintheprogram.

Page 7: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  ObtainingtheFirstValuefromtheUser

–  displaysEnterfirstinteger:followedbyaspace.Thismessageiscalledapromptbecauseitdirectstheusertotakeaspecificac<on.

–  usesthestandardinputstreamobjectcin(ofnamespacestd)andthestreamextrac<onoperator,>>,toobtainavaluefromthekeyboard.

–  Usingthestreamextrac<onoperatorwithstd::cintakescharacterinputfromthestandardinputstream,whichisusuallythekeyboard.

Page 8: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  ObtainingtheSecondValuefromtheUser

Page 9: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  Calcula0ngtheSumoftheValuesInputbytheUser

–  Thisassignmentstatementaddsthevaluesofvariablesnumber1andnumber2andassignstheresulttovariablesumusingtheassignmentoperator=

Page 10: Another Simple Program: Adding Two Integers

AnotherSimpleProgram:AddingTwoIntegers

•  DisplayingtheResult

– displaysthecharacterstringSumisfollowedbythenumericalvalueofvariablesumfollowedbystd::endl—aso-calledstreammanipulator.

– Thenameendlisanabbrevia<onfor“endline”andbelongstonamespacestd.Thestd::endlstreammanipulatoroutputsanewline.

Page 11: Another Simple Program: Adding Two Integers

MemoryConcepts

•  Variablenamessuchasnumber1,number2andsumactuallycorrespondtoloca<onsinthecomputer’smemory.Everyvariablehasaname,atype,asizeandavalue.

Page 12: Another Simple Program: Adding Two Integers

Arithme<c

•  C++providesthemodulusoperator,%,thatyieldstheremainderamerintegerdivision.Themodulusoperatorcanbeusedonlywithintegeroperands.Theexpressionx%yyieldstheremainderamerxisdividedbyy.Thus,7%4yields3and17%5yields2.

Page 13: Another Simple Program: Adding Two Integers

Arithme<c•  Examples,

Page 14: Another Simple Program: Adding Two Integers

Arithme<c•  RulesofOperatorPrecedence

C++appliestheoperatorsinarithme<cexpressionsinapreciseorderdeterminedbytheserulesofoperatorprecedence,whicharegenerallythesameasthoseinalgebra:1.  Operatorsinexpressionscontainedwithinpairsof

parenthesesareevaluatedfirst.Parenthesesaresaidtobeatthe“highestlevelofprecedence.”Incasesofnested,orembedded,parentheses,suchas(a*(b+c)),theoperatorsintheinnermostpairofparenthesesareappliedfirst.

2.   Mul0plica0on,division,andmodulusopera<onsareappliednext.Ifanexpressioncontainsseveralmul<plica<on,divisionandmodulusopera<ons,operatorsareappliedfromlemtoright.

3.   Addi0onandsubtrac0onopera<onsareappliedlast.Ifanexpressioncontainsseveraladdi<onandsubtrac<onopera<ons,operatorsareappliedfromlemtoright.

Page 15: Another Simple Program: Adding Two Integers

Arithme<c•  Examples

1:2+(2-2)*(2+2)/2=?2:3+3-3*(3/3)=?3:(4+4–4*4)/((4+4)*-1)=?4:(22%4–1)/2+1/2=?

Page 16: Another Simple Program: Adding Two Integers

ModifytheProgram

•  Writeaprogramthattakesthreeintegersfromtheuserandoutputsthefollowingopera<on:

Page 17: Another Simple Program: Adding Two Integers

Decisionmaking(EqualityandRela<onalOperators)

•  Theifstatementallowsaprogramtotakealterna<veac<onbasedonwhetheracondi<onistrueorfalse.–  Ifthecondi<onistrue,thestatementinthebodyoftheifstatementisexecuted.Ifthecondi<onisfalse,thebodystatementisnotexecuted.

– Condi<onsinifstatementscanbeformedbyusingtheequalityoperatorsandrela<onaloperators.

Page 18: Another Simple Program: Adding Two Integers

Decisionmaking(EqualityandRela<onalOperators)

•  Ifstatement if(condi<on){ //dosomething… }

Page 19: Another Simple Program: Adding Two Integers

Decisionmaking(EqualityandRela<onalOperators)

Page 20: Another Simple Program: Adding Two Integers

Decisionmaking(EqualityandRela<onalOperators)

•  Let’swriteaprogramthatcomparestwointegers!

Page 21: Another Simple Program: Adding Two Integers

Decisionmaking(EqualityandRela<onalOperators)

using namesapce std!isadirec<vethatenablesaprogramtouseallnamesinanystandardC++headersuchas<iostream>

Page 22: Another Simple Program: Adding Two Integers

LabAssignment#1