8.6.EXERCISES 135
(a)Definiteloopvs.Indefiniteloop
(b)Forloopvs.Whileloop
(c)Interactive loopvs.Sentinelloop
(d)Sentinelloopvs.End-of-fileloop
- Give a truthtablethatshowsthe(Boolean)valueofeachofthefollowingBooleanexpressions,for
everypossiblecombinationof“input”values.Hint:includingcolumnsfor“intermediate”expressions
is helpful.
(a)not (P and Q)
(b)(not P) and Q
(c)(not P) or (not Q)
(d)(P and Q) or R
(e)(P or R) and (Q or R)
- Writeawhileloopfragmentthatcalculatesthefollowingvalues.
(a)Sumofthefirstncountingnumbers: 1 2 3 n
(b)Sumofthefirstn oddnumbers: 1 3 5 2 n 1
(c)Sumofa seriesofnumbersenteredbytheuseruntilthevalue 999 is entered.Note: 999 should
notbepartofthesum.
(d)Thenumberoftimesa wholenumberncanbedividedby2 (usingintegerdivision)beforereach-
ing1 (i.e.,log 2 n).
- TheFibonaccisequencestarts 1 1 2 3 5 8 . Eachnumberinthesequence(afterthefirsttwo)is the
sumoftheprevioustwo.Writea programthatcomputesandoutputsthenthFibonaccinumber, where
nis a valueenteredbytheuser.
- TheNationalWeatherServicecomputesthewindchillindex usingthefollowingformula.
35 74 0 6215 T 35 75
V^0 ^16 0 4275 T
V^0 ^16
WhereTis thetemperatureindegreesFahrenheit,andVis thewindspeedinmilesperhour.
Writea programthatprintsa nicelyformattedtableofwindchillvalues.Rowsshouldrepresentwind
speedfor0 to 50 in5 mphincrements,andthecolumnsrepresenttemperaturesfrom-20to+60in
10-degreeincrements.
- Writea programthatusesawhilelooptodeterminehowlongit takesforaninvestmenttodouble
ata giveninterestrate.Theinputwillbeanannualizedinterestrate,andtheoutputis thenumberof
yearsit takesaninvestmenttodouble.Note:theamountoftheinitialinvestmentdoesnotmatter;you
canuse$1.
- TheSyracuse(alsocalledCollatzorHailstone)sequenceis generatedbystartingwitha naturalnumber
andrepeatedlyapplyingthefollowingfunctionuntilreaching1.
syr
x
x
2 if x is even
3 x 1 if x is odd
Forexample,theSyracusesequencestartingwith5 is: 5 16 8 4 2 1.It is anopenquestioninmathe-
maticswhetherthissequencewillalwaysgoto1 foreverypossiblestartingvalue.
Writea programthatgetsa startingvaluefromtheuserandthenprintstheSyracusesequenceforthat
startingvalue.