Está en la página 1de 22

CSE114 Midterm 1 - Practice Problem Solutions

1) What is the output of the following statement?


System.out.println((2.0+3)+3)

a)5.03
b)8.0
c)8
d)53
e)2.033

Eventhoughyouareprobablyusedtostringconcatenationinside
ofprintstatements(suchasabc+xwhichyieldsabcx),you
canstilldomathinsidethem.Sincetherearenostrings
anywhereintheexpression(justnumbers),Javaaddsthemup
normally.Ifweweretochangetheexpressionto
((2.0+3+)+3),theoutputwouldbe5.03.Javaevaluates
expressionsfromlefttoright,soitwouldadd2.0and3to
produce5.0(double+int=double),andonceweaddtheempty
string()toit,Javawillnowinterpretitasastringand
thuswecannolongerdoarithmeticwithit.Similarly,ifthe
epxressionwas((2.0++3)+3),thentheoutputwouldbe
2.033.

2) What is the output of the following code?


for(intc=Ac<Fc++){
System.out.print(c+)
}

a)ABCDE
b)6566676869
c)Thereisacompilererror.
d)Noneoftheabove.

Allinformationstoredonthecomputerisactually,wheninits
simplestform,justanumber,inbinary.Socharacters,and
Strings(whichareprettymuchjustarraysofcharacters),are
alljustnumbers.Therefore,wecaneasilyinitializeanint
variablebypassinginacharacterliteral.Sincewedeclare
intc=,Javaknowstotreatthisvariableasaninteger.Had
wewrittencharc=,thentheanswertotheproblemwouldbe
A.Ifwewanttointerprettheintegerasacharacter,wehave
tocastit,likethis:
(char)c
However,sincewedeclaredcasaninteger,wecannever
actuallystoreitasacharacter,wecanonlychoosehowto
interpretitwhenweuseitinexpressions.

3) What is the output of the following code?


doublex=(int)2.0
doublef=(x/(int)3.0)
System.out.println(f)

a)0
b)0.0
c)0.66
d)0.6666666666666666
e)1

2.0isadouble,andwhenwecastittoanint,itthenbecomes
2.However,xrepresentsadoublevariable,andwhenweassign2
tox,Javaconvertsitinto2.0.Then,inthefollowinglineof
code,sincexisadouble,eventhough3iscastedtoanint,we
arestilldoingdoubledivision,and2.0/3=0.6666666666666666.
Ifwehadcastedbothsides,((int)x/(int)3.0),thenJava
wouldperformintegerdivisioninsidetheparentheses,(2/3=
0),andthenassignthatvaluetof,whichisadouble,soit
wouldturnitinto0.0.CisincorrectbecauseJavadoesnot
automaticallyroundandtruncatedigitsindoublesforyou,if
youwanttoprintonlyacertainnumberofdecimalsyouhaveto
eitheruseString.format()orDecimalFormat(thesimplesttwo
options).

4) What is returned by the following method?


publicstaticStringoneOfTwo(){
intx=(6/4==1)?2:3
returnx
}

a)2
b)3
c)2
d)3
e)Compilererror.

Thisisatrickquestion.Paycloseattentiontothemethod
signature,whichstatesthatthemethodreturnsaString.x
representsanintegervariable,andeventhoughwecaneasily
turnitintoaString(x+),wehaventdonethathereand
thusthiswillgiveacompilererror(Eclipsewillunderlinethe
returnstatementinredandyouwontbeabletorunthe
program.)IfStringinthemethodsignaturewasreplacedwith
int,thentheanswerwouldbeA.Weuseaconditionaloperator
?toassigntoxoneoftwovalues,basedonthevalueofthe
booleanexpressionprecedingthe?.6/4=1(not1.5),
becauseofintegerdivision,andthusthebooleanexpressionis
true,andsotheconditionalexpressionevaluatestothefirst
choice,notthesecondone.

(boolexpression)?iftrue,returnthis:otherwise,returnthis

5) What is the output of the following program?


publicclassTest{
booleana=false
booleanb=!a
booleanc=(25%3==0||2!=3)

publicstaticvoidmain(String[]args){
if(a&&!a){
if(c)
System.out.println(32)
elseSystem.out.println(31)
}
elseif(c||b&&a){
if(c)
System.out.println(30)
elseSystem.out.println(29)
}
elseSystem.out.println(28)
}
}

a)32
b)31
c)30
d)29
e)28

aisfalse,andbisassignedto!a,meaningnota,andis
thustrue.25%3=1,andisnotequalto0,thus25%3==0
evaluatestofalse.However,2!=3evaluatestotrue,andfalse
||trueevaluatestotrue,thereforecistrue.(a&&!a)can
neverbetrue(logicalcontradiction),sooptions32and31are
eliminatedimmediately.Heresthetrickypart:(c||b&&a)
evaluatestotrue,becausethe&&operatorhasahigher
precedencethanthe||operator(thinkorderofoperations),and
isthusexecutedfirst.(true&&false)isfalse.However,cis
true,and(true||false)istrue.Sowearenowinsideofthe
elseifblock.cistrue,sotheprogramprintsout30,andthen
exits.Noticethattheprogramiswritteninsuchawaysuch

thatonlyonethingiseverprinted(trytothinkofa
combinationofvaluesfora,b,andcsuchthatmorethanone
thingisprintedyouwontbeableto:)

6) Write a static public method called encrypt, that takes one String as an argument
and returns a String. The method encrypts a word, by replacing each letter with the
character two places ahead of it in the alphabet. The last two letters of the alphabet
wrap around to the front (i.e. y = a, z = b). Assume that all input consists solely
of lowercase letters, and that only one word is input.

Sample output:
System.out.println(encrypt("abcdefxyz"))
cdefghzab

System.out.println(encrypt("sampletext"))
ucorngvgzv

Solution:
publicstaticStringencrypt(Stringtext){
Stringans=""
for(inti=0i<text.length()i++){
ans+=(char)((((text.charAt(i)'a')+2)%26)+'a')
}
returnans
}

First,wecreateanemptyStringans.Thisiswhatwewilladd
ontoasweencryptthetextcharacterbycharacter.Wecannot
simplyaddtwotothecharactervaluebecauseweneedthelast
twoletters,yandz,towraparoundtoaandb.Thecheapway
todoitwouldbewithtwoifstatements,(iftext.charAt(i)==
y),butwerebetterthanthat.Inordertowraparoundthe
characters,wewillusemodulus(%).Letssaytheletterweare
encryptingisz.Inordertogetitspositioninthealphabet
(0based),wesubtractthecodefora,(aais0,b
ais1,etc.).Next,weadd2.Then,wemodthesumby26.If
thesumislessthan26,thenthemodulusisequivalenttothe
sum.Ifitisgreater,thenmoduluswillwrapusaroundbackto
0,andperhapsplussome.Now,ourvaluerepresentsthe0based
positioninthealphabetofournewletter.SotogettheASCII
value,wesimplyaddbacka.Sincewedidarithmeticinsideof
thisexpression,wehavetocastitbacktoacharacterbyusing
(char)outsideoftheexpression.Nowweadditontoans,and
aftertheloopisfinished,wereturnans.

7) Write a static public method called reverse, that accepts one String as an
argument, returns nothing, and prints the reverse of the input.

Sampleoutput:

reverse(Thequickbrownfoxjumpsoverthelazydog.)
.godyzalehtrevospmujxofnworbkciuqehT

Solution:

publicstaticvoidreverse(Stringinput){
for(inti=input.length()1i>=0i){
System.out.print(input.charAt(i))
}
}

Thisproblemisfairlysimple,andsimilartothepreviousone,
inthatweareprocessingaStringcharacterbycharacter,and
addingittooutput.However,inthiscase,insteadofbuilding
aStringpiecebypiecewithconcatenation,weareinstead
simplyprintingtostandardoutputcharacterbycharacter,since
ourmethoddoesntreturnanything.Toprintthereverseofthe
stringwesimplystartatthelastcharacter
(i=input.length()
1)
,andkeepdecrementingi
(i)
,untilwegetto0
(i>=0)
,
andprinteachstepoftheway,
System.out.print(input.charAt(i))
.RememberthatStrings(just
likearrays)are0based,sothefirstcharacterisatposition
0.Therefore,inaStringoflengthn,thelastcharacterwill
beatpositionn1.

8) Create a class, called TriangleNumbers, that has a static public method called
th
genNum that takes one non-negative integer argument n, and returns the n
triangle
th
number, an integer. The ntriangle number is defined as the sum of numbers 1
through n, inclusive. For example:
First triangle number = 1
Third triangle number = 1 + 2 + 3 = 6
Ninth triangle number = 1 + 2 + 3 + ... + 8 + 9 = 45
The program should prompt the user to enter an integer x (you can safely assume it is
th
greater than 0), and then print the first x triangle numbers, with each i
line holding
th
the itriangle number amount of values, separated by commas (except for the last
number in every line). So the first line would contain the first triangle number, the
second line would contain the next three, the third line would contain the next six,
the fourth line would contain the next ten, and so forth.
Sample input/output:

Userenters4,programoutputs:
1
3,6,10

Userenters22,programoutputs:
1
3,6,10
15,21,28,36,45,55
66,78,91,105,120,136,153,171,190,210
231,253

Thesolutiontothisproblemisalittlemorecomplex,
andthereisdefinitelymorethanonewaytodoit.
Therefore,Ihaveprovidedtwodifferentsolutions,
whichdifferinafewways.


//Author:Vasia
//Solution1
importjava.util.Scanner

publicclassTriangleNumbers{

/*
Wecoulduseaforlooptogeneratethenthtrianglenumber,(which
isactuallymoreefficientbecausemultiplicationismuchmore
expensivethanaddition),butitisalsoacceptabletousethe
formulaforthenthtrianglenumber,asIdohere.
*/
publicstaticintgenNum(intn){
return(n*(n+1))/2
}


//mainmethod
publicstaticvoidmain(String[]args){
//constructanewScanner
Scannerinput=newScanner(System.in)

//printoutaprompt
System.out.println("TriangleNumberprogram.Enteraninteger
value:")

//readinavalue
intamount=input.nextInt()

/*totalCountrepresentsthetotalnumberoftrianglenumbersprinted
perRowCountrepresentshowmanywehaveprintedonthecurrentrow
rowCountrepresentsi,orthenumberoftherowwearecurrently
printing.
amountOnThisRowrepresentshowmanynumberswewanttoprintonthis
row,whichisequaltothetriangleNumberofrowCount,
genNum(rowCount).
*/
inttotalCount=1
intperRowCount=0
introwCount=1

intamountOnThisRow=genNum(rowCount)

/*Asyou'venoticedhere,Iammissingthefirstpartofthefor
loop,andIcouldhaveeasilydeclaredtotalCountinside(beforethe
firstsemicolon),butIdeclareditearliersoitiseasiertosee
allthevariablesbeingused.awhileloopcouldeasilybesubstitued
fortheforloop:
while(totalCount<=amount){
(allthesamecode,exceptweadda
totalCount++attheveryend.)

totalCount++
}
*/

for(totalCount<=amounttotalCount++){
//numisthenumberweareprinting
intnum=genNum(totalCount)
System.out.print(num)
//we'vejustprintedonarow,soincrementtheperRowCount
perRowCount++

/*letscheckifwe'veprintedenoughnumbersonthisrow.ifso,
printanewline,resettheperRowCount,augmenttherowCount,and
setanewvalueforamountOnThisRow
*/
if(perRowCount==amountOnThisRow){
System.out.println()
perRowCount=0
rowCount++
amountOnThisRow=genNum(rowCount)
}

/*ifwecanstillprintmorenumbersonthisline,weneedacomma
afterthenumber
*/
else{
/*unlesswearedoneprintingallofthenumbersthatis,wedon't
wantacommaaftertheverylastnumberweprint.
*/
if(totalCount!=amount)
System.out.print(",")
}
}
/*finally,printanewline,sothatthatouroutputis
separatedfromanysubsequentcompilernotices.(totallyoptional)
*/
System.out.println("")
}
}

//Author:Vasia
//Solution2
importjava.util.Scanner
publicclassTriangleNumbers2{

/*
Tocalculatethenthtrianglenumber,weneedtofindthesumofall
numbersbetween1andn,inclusive.Createanintegervariableans,
andaddontoitinsideofaloop,iteratingfrom1,ton.
*/
publicstaticintgenNum(intn){
intans=0
for(inti=1i<=ni++){
ans+=i
}
returnans
}

publicstaticvoidmain(String[]args){

//constructanewScanner
Scannerinput=newScanner(System.in)

//printoutaprompt
System.out.println("TriangleNumberprogram.Enteraninteger
value:")

//readinavalue
intamount=input.nextInt()

//separateuserinputfromouroutputwithanewline(optional)
System.out.println("")

/*
Inthissolutionwewillcreateanarray,fillitwithtriangle
numbers,anduseittohelpusprinttheminthewaywewant.
Createanewintarraycallednumbersofsizeamount.amountisthe
integerthatwereadinfromtheuser.
*/
int[]numbers=newint[amount]

/*
Fillinthearraywithtrianglenumbers,sothattheithposition
containstheithtrianglenumbers(rememberarraysare0based,so
position0willhold0.)

*/

for(inti=0i<amounti++){
numbers[i]=genNum(i)
}
/*
Nowwehavefilledupourarray.Eventhoughthisworksjustfine,
duetothenatureofcalculatingtrianglenumbers,thisisslightly
inefficient.(wearedoingredundantcalculations).Canyouthinkofa
moreefficientwaytofillupthearray?(Hint:youmightnoteven
havetousegenNum.)
*/

/*
rowwillkeeptrackofwhatrowwearecurrentlyprintingon
perRowCountwillkeeptrackofhowmanywehaveprintedonthe
currentRow.nistheintegervariablewithwhichwewilliterate
throughthearray.
*/
introw=1
intperRowCount=0

for(inti=1i<amounti++){
//printoutthetrianglenumberintheithpositionofthearray
System.out.print(numbers[i])
//incrementtheperRowCount
perRowCount++

/*ifwehaveprintedonthisrowtherowthtrianglenumberamountof
trianglenumbers(sorryifthatsconfusing),thenweresetthe
perRowCount,incrementtherow,andprintanewline.
*/
if(perRowCount==numbers[row]){
perRowCount=0
row++
System.out.println("")
}

/*
ifwe'renotincrementingtherow,thenthatmeanswe'restayingon
thesamerow,andwewanttoprintacommaafterthenumber,unless
wehaveprinted
allofthenumbers.sincewe'reonlygoinguptoamount1,aslong
asiisnotequaltoamount1,thenweprintacommawithaspace.
*/
else{
if(i!=amount1)
System.out.print(",")
}
}

//finally,printanewlineforgoodmeasure(optional)
System.out.println("")
}
}

9) Write a public static method printHourglass that accepts one integer argument,
returns nothing, and prints an hourglass pattern.

Sampleoutput:
printHourglass(3)
***
*
***

printHourglass(6)
******
**
**
**
******
printHourglass(14)
**************
**
**
**
**
**
**
**
**
**
**
**
**************

publicstaticvoidprintHourglass(intn){
/*n=1isaspecialcase,andourcodelogiconlyproperlyworks
forn>=2,sowe'lljusthandlethiscasemanually,andthenreturn
outofthemethod.eventhoughourmethodisvoid,soitdoesn't
returnanything,wecanusethe"return"statementtostopexecution
andexitthemethod
*/

if(n==1){
System.out.println("*")
return
}

//printstheverytopofthehourglass,justalineofnstars.
for(inti=1i<=ni++){
System.out.print("*")
}

//printanewline
System.out.println("")

//Wewanttheverymiddleofourhourglasstobe
//onlyoneline,soweDONOT
//DONOTwantsomethinglikethis:
//******
//**
//**
//**
//**
//******
//
//Wewantsomethinglikethis:
//******
//**
//**
//**
//******
//Wewillonlyencounterthisproblemisnisevenhowever,sowe'll
//handlethisbycontrollingtheboundsfortheforloopbelowas
//shown.IfyouwanttobetterunderstandwhyIdiditthisway,
//replacethecodebelow(inbetweenthe//)withjust

//"intbound=n/21"andthenrunitwithanevennumber,thenan
//oddnumber.

//
intbound
if(n%2==0)
bound=n/21
elsebound=n/2

//

//printstherestofthetophalf
for(inti=1i<boundi++){

//printtheinitialspaces
for(intj=1j<=ij++){
System.out.print("")
}

//printthestar
System.out.print("*")

//printtheintermediatespaces
for(intj=1j<=n2(2*i)j++){
System.out.print("")
}
//printthelaststar,andwecanprintanewline(println)because
//we'redonewiththeline
System.out.println("*")
}

//ifnisodd,thenweprintjustonestarinthemiddleoftheline,
//weneedaloopforthespacesbeforehandthough
if(n%2!=0){
for(inti=0i<n/2i++){
System.out.print("")
}
System.out.println("*")
}

//nowletsprintthebottomhalf...sigh,thehardpart.
//PSYCH!itsprettyeasy,especiallybecausewealreadywrote
//practicallyallofthecodethatisgoingtodoit!Allweneedto
//doistaketheloopthatprintsthetophalf,andfliptheforloop
//bounds.

//Soinsteadofiascending,itwillnowbedescending.So,ifyou
//lookclosely,thetwoblocksofcodeareidentical,exceptforwhats
//insidetheforloopheader

//printstherestofthebottomhalf
for(inti=n/21i>=1i){

//printtheintialspaces
for(intj=1j<=ij++){
System.out.print("")
}

//printthestar
System.out.print("*")

//printtheintermediatespaces
for(intj=1j<=n2(2*i)j++){
System.out.print("")
}
//printthelaststar,andwecanprintanewline(println)because
//we'redonewiththeline
System.out.println("*")
}

//nowletsprinttheverybottom,whichisidenticaltotheverytop.
for(inti=1i<=ni++){
System.out.print("*")
}

//letsprintanewlinejustforgoodmeasure(totallyoptional)
System.out.println("")

//we'redone!Gonuts,dosomethinglikeprintHourglass(100)!funfun
}

10) Problem taken from projecteuler.net (#1)


If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5,
6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5
below 1000.

Solution:

//Author:Vasia
publicclassPracticeProblemsNumber10{

/*
Loopthroughallintegersfrom3(because3isthefirstmultipleof
3or5),to999,andaddthemtosumiftheyareamultipleof3(i%
3==0)oriftheyareamultipleof5(i%5==0).Byfarthe
easiestsolutiontoimplement,andtounderstand.
*/
publicstaticintfirstWay(){
intsum=0
for(inti=3i<1000i++){
if(i%3==0||i%5==0)
sum+=i
}
returnsum
}

/*
Thismethodisdefinitelymoreconfusingthanthefirstone.
Thissecondsolutionutilizestwoideas:
1)Theformulaforthesumofthefirstnintegers.
2)Setinclusionexclusionprinciple.

Theformulaforthesumofthefirstnintegers,(1+2+...+n)is
equalto((n)*(n+1))/2(I'msureyoualllearnedthisinCalc2.)

Whatifwewantedthesumof(3+6+9+...+999)?
Isn'tthatjust(1+2+3+...+333)*3?
Sameappliesfor(5+10+15+...+995).
Inordertogettheupperbound,wecansimplydivide999byeither3
or5.
999/3=333,999/5=199(integerdivison).

However,ifthenumberisamultipleof3andof5,weareaccounting
forittwice.Therefore,byfollowingthesetinclusionexclusion
principle,wesimplysubtractfromoursumthesumofmultiplesof
15,whichis(15+30+45+...+66).

Thissolutionismuchmoremathematicalinnature,andcanquite
easilybedoneonpaper,andalthoughyouaren'texpectedtocomeup
withthiskindofasolution,Iprovidedithereforyourenrichment.

*/
publicstaticintsecondWay(){
intsumOfThrees=3*(((999/3)*((999/3)+1))/2)
intsumOfFives=5*(((999/5)*((999/5)+1))/2)
intsumOfFifteens=15*(((999/15)*((999/15)+1))/2)

returnsumOfThrees+sumOfFivessumOfFifteens
}


/*
Thisthirdsolutionisthemostefficientofthethreeasfaras
spendingcomputationalresourcesgo.

Ifyoulookatthenumbersthatwearesummingup,youcanfinda
simplepattern...
0,3,5,6,9,10,12,15,18,20,21,24,25,27,30...
Wecangetfromtheveryfirstnumbertothenextnumberbyadding3,
then2,then1,then3,then1,then2,then3,andthenthepattern
repeatseverytimewegettoamultipleof3and5(amultipleof15).
Sowecancreatealittleintegerarraythatwillstorethese
"addends",andwewillcyclethroughthemaswecalculatethenumber
weareaddingontooursum.Everytimewefigureoutthecurrent
number,weincrementtheindexweusetokeeptrackofwhataddendwe
arecurrentlyon,andbecausewehaveasmallarray,weneedtomod
theincrementbythelengthofthearraysothatifweincrememnt
pastitsbounds,wewrapbackaroundto0.(Anotherwaytodothisis
tocheckifindex==addends.length,thensetindexto0.)

Sobeforeweentertheloop,currentisequalto0.Afterweenter
theloop,afterthefirstfewiterationscurrentisequalto3,then
5,then6,9,10,12,15,18,20,21,...etc.Youcanputthis
statementSystem.out.println(current)inthelooptoseehow
currentchangeswitheachiteration.
*/

publicstaticintthirdWay(){
//0,3,5,6,9,10,12,15
int[]addends={3,2,1,3,1,2,3}

intcurrent=0
intsum=0
intindex=0
while(current<999){
current=current+addends[index]
sum+=current
index=(index+1)%addends.length
}
returnsum
}


/*
Youcanalsoalwayscheatandjustlookitup.
However,ifyougetusedtodoingthis,oneday,
whenyoucan'tfindtheanswer....

You'llbescrewed.

Also,youcan'tlookupstuffduringtests.
*/
publicstaticintfourthWay(){
return223168
}

//printouttheresultsofthefourdifferentsolutions
//toensuretheyareequivalent(whataretheoddstheyare
//allwrong?haha)
publicstaticvoidmain(String[]args){
System.out.println(firstWay())
System.out.println(secondWay())
System.out.println(thirdWay())
System.out.println(fourthWay())
}
}

También podría gustarte