You are on page 1of 11

UNIT 3 REVIEW (Rev 1 11/04) Lesson 9

VOCABULARY:
while break

SENTINEL BOUNDARY

STATE

The general form of a while loop is:


while (expression) statement;

a. As in the if else !ontrol str"!t"re# the Boolean e$pression m"st %e en!lose& in parentheses '(. %. The statement e$e!"te& %) the *hile loop !an %e a simple statement# or a !ompo"n& statement %lo!+e& *ith %ra!es ,-. !. If the e$pression is tr"e the statement is e$e!"te&. After e$e!"tion of the statement# program !ontrol ret"rns to the top of the while !onstr"!t. The statement *ill !ontin"e to %e e$e!"te& "ntil the e$pression e.al"ates as false.

The follo*ing loop *ill print o"t the integers from / /0.
int number = 1; while (number <= 10) { ystem!out!println(number); number""; # // initialize loop control variable // loop boundary condition // increment

The a%o.e e$ample has three +e) lines that nee& emphasis:
a. Yo" m"st initiali1e the loop !ontrol .aria%le 'l!.(. %. The loop %o"n&ar) !on&itional test 'number <= 10( is often a so"r!e of error. 2a+e s"re that )o" ha.e the !orre!t !omparison ' <# $# ==# <=# $=# %=( an& that the %o"n&ar) .al"e is !orre!t. !. There m"st %e some t)pe of in!rement or other statement that allo*s the loop %o"n&ar) to e.ent"all) %e!ome false. Other*ise the program *ill get st"!+ in an en&less 'infinite( loop.

The "se of a sentinel .al"e *ith while loops: the loop !ontin"es "ntil a sentinel .al"e is entere& the sentinel .al"e sho"l& %e an 3in.ali&4 .al"e# for e$ample o 5+eep entering positi.e n"m%ers or enter 6/ to 7"it8 o 5enter .ali& test s!ores or enter /0/ to 7"it8 o 5enter names or enter 37"it4 to 7"it8

9or e$ample# here is a loop that +eeps a r"nning total of positi.e integers# terminate& %) a negati.e .al"e:
int total = 0; int number = 1; // set to an arbitrary value //to &et inside t'e loop

while (number $= 0) { ystem!out!print (()nter a number (*1 to +uit) **$ (); number = console!&et,nt(); if (number $= 0) // dont add sentinel value into runnin& total total "= number; # ystem!out!println((-otal = ( " total);

Regar&ing these : lines a%o.e:


if (number $= 0) total "= number; // dont add sentinel value into runnin& total

An alternati.e is:
if (number < 0) break; total "= number; // t'is does not &et executed i. number < 0

The alternati.e "ses a break; *hi!h !a"ses the program to imme&iatel) e$it the loop. This st)le of programming '"sing b e!" insi&e a loop( is sometimes helpf"l# parti!"larl) *hen the logi! of the loop is more !omple$# %"t it is normall) to %e a.oi&e& %e!a"se it is not follo*ing the r"les of str"!t"re& programming. 9in&ing a minim"m .al"e gi.en a series of .al"es: "sing a .aria%le s"!h as smallest# first initiali1e it to the largest e$pe!te& .al"e as )o" rea& in ne* .al"es# if the ne*est .al"e is less than the .al"e of smallest# then "p&ate smallest to the ne* .al"e
int smallest = ; ... while (score $= 0) // loop boundary { ... if (score < smallest) smallest = score; // maintain state o. smallest #

,nte&er!/0123045)

Use a similar i&ea to fin& a ma$im"m .al"e# e$!ept initiali1e it to the smallest e$pe!te& .al"e.

9in&ing an a.erage of a set of n"m%ers entere&: +eep a r"nning total of all the .al"es 6 remem%er to initiali1e the total to 1ero; +eep a r"nning !o"nt of ho* man) .al"es 6 remem%er to init to 1ero; after all .al"es are entere& 'in other *or&s# after the loop is o.er(# &i.i&e the total %) the n"m%er of .al"es ma+e s"re )o" &on4t &o integer &i.ision *hen !al!"lating the a.erage;
int total=0; int count = 0; while (score $= 0) { !!! score = console!&etln,nt(); total "= score; count""; !!! # av& = (double) total/count;

// runnin& total // 'o6 many values

Lesson /0
VOCABULARY: 9OR DO <=ILE

NESTED LOO> The #$ loop has the same effe!t as a *hile loop# %"t "sing a &ifferent format. It is goo& to "se *hen the loop nee&s to repeat a fi$e& n"m%er of times. The general form of a #$ loop is:
for (statement1; expression7; statement8) statement statement1 initiali1es a .al"e expression7 is a boolean e$pression statement8 alters the +e) .al"e# "s"all) .ia an in!rement?&e!rement statement

=ere is an e$ample of a #$ loop# "se& to print the integers / /0.


for (int loop = 1; loop <= 10; ystem!out!print( loop); loop"")

The e7"i.alent while loop *o"l& loo+ li+e this:


loop = 1; while (loop <= 10) { ystem!out!print( loop); loop""; #

Neste& #$ loops are goo& for printing a ta%le:


for (int ro6 = 1; ro6 <= 7; ro6"")

{ for (col=1; col <= 8; col"") ystem!out!print( (ro6 " col) " 9 9); ystem!out!println( ); #

The o"tp"t of this !o&e is:


7 8 : 8 : ;

Sometimes the inner #$ loop4s !o"nter is &epen&ent on the .al"e of the o"ter #$ loop4s !o"nter:
for (int ro6 = 1; ro6 <= 7; ro6"") { for (col=1; col <= ro6; col"") // last value o. col is based on current value o. ro6 ystem!out!print( (ro6 " col) " 9 9); ystem!out!println( ); #

The o"tp"t of this !o&e is:


7 8 :

The general form of a %$&while loop is:


do statement; while (expression);

The %$&while loop is goo& for tas+s that nee& to %e &one at least on!e# li+e prompting the "ser for at least one pie!e of information Lesson //
VOCABULARY:
switch

The 'wi()h is li+e a spe!iali1e& 3!as!a&e& if else4# *here the test e$pression e.al"ates to some integer .al"e. The 'wi()h statement attempts to mat!h the integer .al"e of the e$pression *ith one of the )!'e integer .al"es. 'Note that !har .al"es !an also %e "se& here sin!e the) ha.e integer AS@II .al"es.( If a mat!h o!!"rs# the statements %elonging to the )!'e .al"e are e$e!"te& "ntil the b e!" statement is en!o"ntere&. The effe!t of the b e!" statement !a"ses program !ontrol to A"mp to the en& of the 'wi()h statement. No other !ases are e$e!"te&. A .er) !ommon error *hen !o&ing a 'wi()h !ontrol str"!t"re is forgetting to in!l"&e the b e!" statements to terminate ea!h !ase .al"e. If the b e!" statement is omitte&# all !ases follo*ing the mat!hing )!'e .al"e are e$e!"te&. This is "s"all) .er) "n&esira%le.

If no mat!h o!!"rs %et*een the e$pression an& the )!'e .al"es# the optional &efa"lt !hoi!e is e$e!"te&.

The follo*ing e$ample applies the 'wi()h statement to printing the *or+ &a) of the *ee+ !orrespon&ing to a .al"e '/ B(:
int day; switch (day) { case 1< ystem!out!println( (/onday(); break; case 7< ystem!out!println ((-uesday(); break; case 8 ystem!out!println ((=ednesday(); break; case :< ystem!out!println ((-'ursday(); break; case ;< ystem!out!println ((>riday()l; break; default< ystem!out!println( (not a valid day(); break; #

The e7"i.alent i#&el'e str"!t"re for the a%o.e !o&e is:


if (day == 1) { ystem!out!println( (/onday(); # else i. (day == 7) { ystem!out!println ((-uesday() # else i. (day == 8) { ystem!out!println ((=ednesday(); # else i. (day == :) { ystem!out!println ((-'ursday(); # else i. (day == ;) ystem!out!println ((>riday(); # else { ystem!out!println( (not a valid day(); #

S"ppose *e *ante& to !o"nt the o!!"rren!es of .o*els an& !onsonants in a stream of te$t. The 'wi()h statement is a%le to anal)1e !hara!ter &ata %e!a"se s"!h &ata is !on.erte& to integer 'AS@II( .al"es for pro!essing. Note that m"ltiple )!'e .al"es !an lea& to one set of statements.
if ((?a? <= letter) @@ (letter <= ?z?)) { switch (letter) { case ?a? < case ?e? < case ?i? < case ?o? < case ?u? < // multiple case values .or vo6el"" vo6el""; break;

default < consonant""; break; # #

Lesson /:
VOCABULARY: >RI2ITICE DATA EARBAEE @OLLE@TION e+uals() OBDE@T RE9EREN@E ALIAS null

9or .aria%les that are of primiti.e &ata t)pes 'li+e int# &o"%le# !har# %oolean( 6 the .al"e of the .aria%le is store& in the .aria%le. EF: int num1 = ;; // num1 contains t'e value ;;
// num1 is a primitive variable

9or .aria%les that are of o%Ae!t &ata t)pes 'li+e String# Dra*ingTool# @onsoleIO# Re!tangle# et!( 6 the .aria%le !ontains a n"m%er '5referen!e8( that is the memor) lo!ation of the a!t"al o%Ae!t 'in other *or&s# it !ontains information on ho* to fin& the o%Ae!t( G it is !alle& an 5'o%Ae!t( referen!e .aria%le8. Yo" !an set the .al"e of a referen!e .aria%le to 5n"ll8 *hen it is not referring to an) o%Ae!t. EF: trin& str0 = null;
// same t'in& as< // trin& str0;

The !on!ept of a 5referen!e .aria%le8 is important to "n&erstan& *hen &ealing *ith String o%Ae!ts# for e$ample. <hen )o" "se the reser.e& *or& 5ne*8# it !reates a ne* o%Ae!t# p"ts it in a ne* pla!e in memor)# an& the memor) lo!ation is store& in a referen!e .aria%le. EF: trin& str0 = ne6 trin&(9t'is strin&A);
// str0 no6 points to t'e location in memory 6'ere // 9t'is strin&A is stored; // str0 is a re.erence variable

There is an option to assign a .al"e to a String o%Ae!t *itho"t "sing the 5ne*8 operator. In !ases li+e that# Da.a *ill !he!+ first to see if the parti!"lar String .al"e has alrea&) %een store& somepla!e in memor) 'not "sing the 5ne*8 operator( an& *ill point the referen!e to the e$isting lo!ation. EF: trin& str0 = 9t'e same strin&A;
trin& strB = 9t'e same strin&A; // didnt use ne6 .or str0 or strB *$ since t'ey // 'ave t'e same valuesC t'ey are pointin& to t'e // same memory location

2ore e$amples: EF:


trin& str0 = ne6 trin&(9t'is strin&A); trin& strB = ne6 trin&(9t'at strin&A); // 'ereC str0 and strB point to di..erence memory locations

EF:

trin& str0 = ne6 trin&(9t'is strin&A); trin& strB = str0; // 'ereC str0 and strB point to same memory location t'at // contains 9t'is strin&A trin& str0 = ne6 trin&(9t'is strin&A); // .irstC str0 points to memory location storin& // 9t'is strin&A str0 = ne6 trin&(9t'at strin&A); // but no6 it points to a ne6 memory location storin& // 9t'at strin&A !!! //and no re.erence is pointin& to 9t'is strin&A anymore%

EF:

<hen )o" "se the relational operator 5HH8 or 5;H8 to !ompare : .aria%les# )o" are testing if the .al"es store& in the : .aria%les are e7"al. That *or+s A"st fine *ith primiti.e &ata t)pes# %"t *at!h o"t for *hat it &oes *ith o%Ae!t &ata t)pes; EF: i. (int0 == intB)
// // i. (str0 // // // testin& i. t'e values stored in t'ose primitive variables are e+ual == strB) testin& i. bot' re.erence variables point to t'e same memory location%% !!! DEFB0B4G HF- =I0- GF5 ,H-)HJ)J%

Therefore# to !ompare the )$*(e*(' of t*o o%Ae!ts# s"!h as t*o String o%Ae!ts# )o" sho"l& "se the 5e7"als'(8 metho&: EF: i. (str0!e+uals(strB))

+ !)(i)e ,-e'(i$*' I( i' hi.hl/ e)$00e*%e% (h!( /$- 1 !)(i)e -'i*. ( !)i*. (!ble'2 3ee '$0e e4!01le' i* (he 5A*'we '6 'e)(i$* bel$w2 /. @onsi&er the follo*ing f"n!tion:
public static int 0(int 1) { int GC K; 6'ile (1 < 10) { G = 1; 6'ile (G <= 10) { G""; K = 1 " G; # 1 "= G; # return K; #

<hat is the .al"e ret"rne& %) the !all 0(;)I 'a( B '%( // '!( /J '&( /K 'e( :L :. @onsi&er the follo*ing f"n!tion:
public static int 0BL(int 1) { int G; do { G = 1; do { G "= G; # 6'ile (G <= 10); 1 "= 7; # 6'ile (1 < 10); return G; #

<hat is the .al"e ret"rne& %) the !all 0BL(;)I 'a( /K '%( /M '!( /9 '&( :/ 'e( :N

J. @onsi&er the follo*ing !o&e segment:


int num = ;; do { num "= 1; ystem!out!print(num); # 6'ile (num < M);

<hat are the first an& last o"tp"tsI 'a( B# L '%( B# M '!( K# L '&( K# M 'e( none of the a%o.e N. Ei.en the follo*ing !o&e segment an& ass"ming that x an& y are positi.e n"m%ers: int $# )# 1O
z = 1; 6'ile (y $ 0) { z N= x; y**; #

<hi!h of the follo*ing %est &es!ri%es *hat this !o&e segment &oesI '=int: >i!+ some small positi.e .al"es for $ an& ) an& then tra!e the !o&e.( A. B. @. D. E. Sets 1 to %e the s"m $P). Sets 1 to %e the pro&"!t $Q). Sets 1 to %e the a%sol"te .al"e of $. Sets 1 to %e the .al"e of $). Sets 1 to %e the .al"e of )$.

B. <hat is the o"tp"t of the follo*ing !o&e segmentI


int sum=0; .or (int O = 1; O <P; O"=7) sum "=O; ystem!out!println(sum);

'a( '%( '!( '&( 'e(

M 9 /K :B JK

K. @on.ert the follo*ing Rs*it!hR statement to one "sing RifR an&?or Rif?elseR statements. 'Note: This 7"estion &oes not ha.e an) m"ltiple !hoi!e ans*ers.(
int xC y; s6itc' (x) { case 1< y = 7; case 7< y = Q; breaO; case 8< case :< y = 70; breaO; de.ault< y = *1; #

A*'we ' ($ + !)(i)e ,-e'(i$*' /. D tra!ing ta%le: $ B ) / : J S /0 // ) B /0 :0 L /N 9 18 7 L M /B 17

/K :. B tra!ing ta%le: $ B L 9 // J. D N. D tra!ing ta%le# starting *ith $ H 3# ) H 9: $ ) 1 J : / / J 0 : : noti!e ho* 9 H J

B. @

tra!ing ta%le:

+ / J B L

s"m / N 9 17

K. i. (x == 1 RR x == 7)
y else y else y = Q; // take note of missing break after case 1 i. (x == 8 RR x == :) = 70; = *1;

You might also like