r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and...

26
Chapter 6 Loop Structures and Strings Loop structures, counters and accumulators, and flags are explained in this chapter. Debugging techniques and the String class are also discussed. The while Statement The whi le statement is a loop structure, which executes a set of statements over and over again based on a condition. Loop structures are used to perform tasks such as summing a set of numbers as they are entered by the user or repeatedly prompting the user for a value until valid data is entered. The whi le statement takes the form: whi l e ( <condi t i on>) { <s t at ement s > } The condition of the whi le loop is a Boolean expression, which is evaluated before the statements are executed. When the condition is true the state- ments are executed, when the condition is false program flow continues to the next statement after the closing curly brace of the whi le. Each execution of the loop is called an iteration. Note that a whi le loop may never execute if the condition initially evaluates to false. The following whi le statement executes five times: i nt num = 0; whi l e ( num < 5) { num += 1; } After the fifth execution, numis equal to 5, making the condition false. The do-while Statement The do- whi l e statement is an alternative form of the whi le statement. In the do- whi l e statement the condition is not evaluated until after the first execution of the loop. Therefore, the do- whi l e executes at least once. The do- whi l e takes the following form: do { <s t at ement s > } whi l e ( <condi t i on>) ; Chapter 6 Loop Structures and Strings

Transcript of r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and...

Page 1: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Loop structu res, cou nters and accu mulators, and flags are explained in th is chap ter. Debugging tech n iqu es and the Str ing class are also d iscussed.

The w hile St atement The whi l e statement is a loop structure, which executes a set of statements over and over again based on a cond ition. Loop structu res are u sed to perform tasks such as su m m ing a set of nu mbers as they are entered by the user or repeated ly prompting the user for a value u ntil valid data is entered. The whi l e statement takes the form:

whi l e ( <condi t i on>) { <s t at ement s >}

The condition of the whi l e loop is a Boolean expression, which is evaluated before the statements are executed. When the cond ition is true the state-ments are executed, when the condition is false program flow continues to the next statement after the closing curly brace of the whi l e. Each execution of the loop is called an iteration. Note that a whi l e loop may never execute if the cond ition in itially evaluates to false.

The follow ing whi l e statement executes five times:

i nt num = 0;whi l e ( num < 5) { num += 1;}

After the fifth execution, num is equal to 5, making the cond ition f al se.

The do-w hile St atement The do- whi l e statement is an alternative form of the whi l e statement. In the do- whi l e statement the cond ition is not evaluated u ntil after the first execution of the loop. Therefore, the do- whi l e executes at least once.

The do- whi l e takes the follow ing form:

do { <s t at ement s >} whi l e ( <condi t i on>) ;

Chapter 6Loop St ructures and St r ings

kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Underline
kimberlysmith
Underline
kimberlysmith
Sticky Note
Highlight all of this tip
kimberlysmith
Sticky Note
draw a line to this and write "no semicolon"
kimberlysmith
Sticky Note
write in margin "+= means add one to num and store back in num"
Page 2: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

The follow ing do- whi l e example prompts the user u ntil a valid number is entered :

do { Sys t em. out . pr i nt ( "Ent er a number l es s t han 4:") ; pl ayer Num = i nput . next I nt ( ) ;} whi l e ( pl ayer Num >= 4) ;

I nf init e Loops The cond ition of a loop is used to determ ine when the loop shou ld stop executing. A whi l e continues u ntil its cond ition is false. What happens, though, if the cond ition never becomes false? The resu lt is an infinite loop—one which continues forever. For example, the follow ing generates an infinite loop. Can you see why?

i nt num = -1;whi l e ( num < 0) { num = -1;}

The code causes the application to simply stop respond ing or just “hang.” When this happens, close the output w indow to end the application. Note that some compilers may requ ire a d ifferent procedure to end an infin ite loop.

Syntax errors are a com mon cau se of in fin ite loops. For example, a sem icolon after the cond ition causes the statement to check the cond ition, do nothing, check the cond ition, do nothing, and on and on:

whi l e ( num < 0) ; { / / an i nf i ni t e l oop her e- - added s emi col on num += 1;}

Another example of a syntax error that can lead to an infin ite loop is om itting the cu rly braces:

whi l e ( num < 0) / / an i nf i ni t e l oop her e- - no br aces Sys t em. out . pr i nt ( "Ent er a val ue: ") ; num = i nput . next I nt ( ) ;

In th is case, only the first statement is executed and num is never assigned the input. Although properly done, the indentation makes it d ifficu lt to find the syntax error.

A logic error can also lead to an infinite loop cond ition. For example, in the code below num is in itialized to 1 and never decremented to a number less than 0 in the loop, making the cond ition of the loop structu re always true:

i nt num = 1;do { num += 1;} whi l e ( num >= 0) ;

In th is case, the loop isn’t in fin ite becau se num is eventually assigned a number so large that an overflow resu lts. An overflow occurs when there are not enough bits to store a number. This may generate a ru n-time error or, in the case of the code above, actually cause the cond ition to become false. An overflow changes the sign of the number stored.

kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Underline
kimberlysmith
Underline
Page 3: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Review : PrompterCreate a Prompter application that prompts the user for two nu mbers. The first number is a m in value and the second is a max value. Prompter then prompts the user for a number between the min and max numbers entered. The user shou ld be continually prompted u ntil a nu mber w ith in the range is entered. Be su re to include the m in and max nu mbers in the prompt.

Counters and Accumulat ors Many algorithms requ ire cou nting and sum m ing values. For example, an application that calcu lates the average of a set of nu mbers must su m the nu mbers and then d ivide the total by the cou nt. The AverageValue application perform s cou nting and su m m ing. A ru n of the application looks sim ilar to:

The AverageValue application is based on the pseudocode:

Pr ompt user f or a val uewhi l e ( val ue ! = 0) count val ue add val ue t o s um of val ues pr ompt us er f or anot her val ueDi s pl ay aver age of val ues ( s um/ count )

A program that cou nts the nu m ber of values entered by the u ser is actually cou nting the number of loop iterations. To cou nt loop iterations, a statement sim ilar to the following is used w ithin the loop :

numVal ues += 1;

Each time the statement executes, one is added to the cu rrent value of the variable. This type of variable is called a counter because it is incremented by a constant value. Cou nters are u sefu l for keeping track of the nu mber of times a u ser enters a value, m akes a guess, or types a password . A cou nter shou ld be in itialized when it is declared and then incremented by a fixed amou nt.

A sim ilar assign m ent statement is u sed to su m values as they are entered by the user:

s umOf Val ues += newVal ue;

Each time the statement executes, the value of newVal ue is added to the cu rrent value of the variable. This type of variable is called an accumulator because its value “accumulates.” As with a counter, an accumulator shou ld be in itialized when it is declared.

kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
Page 4: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

The AverageValue code includes both a cou nter (numVa l ues ) and an accumulator (s umOf Val ues):

/ * Aver ageVal ue appl i cat i on. */

i mpor t j ava. ut i l . Scanner ; / ** * Di s pl ays t he aver age of a s et of number s */ publ i c cl as s Aver ageVal ue {

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { f i nal i nt SENTI NEL = 0; i nt newVal ue; i nt numVal ues = 0; i nt s umOf Val ues = 0; doubl e avg; Scanner i nput = new Scanner ( Sys t em. i n) ;

/ * Get a s et of number s f r om us er */ Sys t em. out . pr i nt l n( "Cal cul at e Aver age Pr ogr am"); Sys t em. out . pr i nt ( "Ent er a val ue ( " + SENTI NEL + " t o qui t ) : ") ; newVal ue = i nput . next I nt ( ) ; whi l e ( newVal ue ! = SENTI NEL) { numVal ues += 1; s umOf Val ues += newVal ue; Sys t em. out . pr i nt ( "Ent er a val ue( " + SENTI NEL + " t o qui t ) : ") ; newVal ue = i nput . next I nt ( ) ; } i nput . cl os e( ) ;

/ *Cal cul at e aver age of number s ent er ed by us er */ avg = ( doubl e) s umOf Val ues / ( doubl e) numVal ues ; Sys t em. out . pr i nt l n( "Aver age i s " + avg) ; }}

The AverageValue code uses a constant named SENTI NEL. This constant stores a value to act as a flag, or sentinel, to sign ify that the loop shou ld stop iterating. AverageValue defines the sentinel w ith a constant. Another approach is to use a variable and prompt the user for the sentinel value.

Review : EvensCreate an Evens application that d isplays the even numbers between 1 and 20, inclusive.

Review : NumbersSumCreate a Nu mbersSu m application that prompts the u ser for a nu mber and then d isplays the nu mbers 1 through the nu mber entered, each on a separate line. Below the numbers, the sum is d isplayed.

Review : Percent PassingCreate a PercentPassing application that prompts the user for a set of scores and then calcu lates the percent-age of scores above 70%. The user shou ld have the option to enter as many scores as needed. (H int: Use an i f statement and another cou nter.)

kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Sticky Note
FINAL means that it is a constant and will not change.
kimberlysmith
Sticky Note
Prefer using variable called Flag rather than Sentinel.
kimberlysmith
Sticky Note
Even though this prompt statement is above the while loop, you must also place it inside the while loop because execution will not go back to line above while statement.
Page 5: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

The for St atement The f or statement is a loop structu re that executes a set of statements a fixed number of times. The f or statement takes the form:

f or ( <i ni t i al i zat i on>; <condi t i on>; <i ncr ement >) { <s t at ement s >}

The initialization is performed only once when a f or statement is executed. The cond ition is a Boolean expression, which is evaluated before each loop iteration. When the cond ition is true the statements are executed, when false, program flow continues to the next statement after the closing cu rly brace of the f or . After each loop iteration, the increment is executed.

The follow ing statement u ses a cou nter to control the iterations of a f or statement. The cou nter i is the loop control variable. When i is greater than 10, looping term inates:

f or ( i nt i = 1; i <= 10; i ++) { Sys t em. out . pr i nt l n( i ) ;}

Note that the cou nter is declared in the in itialization of the f or statement (i nt i = 1). With a declaration in th is location, the scope of the cou nter is from the in itialization to the closing cu rly brace of the f or statement. The application w ill not recognize the variable outside of that statement. Declaring variables so that their scope is limited to where they are needed is good program m ing style because it produces cleaner code and helps elim inate the possibility of errors.

The statement above uses the ++ operator in the increment part of the f or statement (i ++). The ++ operator is called the increment operator because it increases the value of a variable by 1. The ++ operator is a good choice in the increment of a f or statement because the effect is to increase the operand by 1. However, ++ shou ld not be used within an expression, such as i ++ <= 10, becau se the value retu rned by the operator is u sed in the expression, not the final value of the operand.

Any combination of components can be left out of a f or statement. This can be usefu l when a cou nter is declared and initialized outside the state-ment, as in the follow ing code:

i nt num;Sys t em. out . pr i nt ( "Ent er t he s t ar t i ng number : ") ;num = i nput . next I nt ( ) ;f or ( ; num <= 10; num++) { Sys t em. out . pr i nt l n( num);}

A f or statement may also count dow n from a start value to an end value using the decrement operator, - - :

f or ( i nt count Down = 10; count Down <= 0; count Down- - ) { Sys t em. out . pr i nt l n( count Down) ;}

While it is possible to mod ify a loop control variable from w ith in a f or loop or to term inate a loop prematu rely, th is is considered poor program-m ing style. Good program m ing style d ictates that changes to the loop control variable occu r in the increment portion of the loop only and that the loop end only when the cond ition is false.

f or

kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Underline
kimberlysmith
Underline
kimberlysmith
Sticky Note
also underline "performed only once"
kimberlysmith
Sticky Note
happens after the loop pass (iteration)
kimberlysmith
Sticky Note
I call it "Pass"
kimberlysmith
Sticky Note
highlight the tip below
kimberlysmith
Sticky Note
Highlight the first two sentences of this box (through postfix)
kimberlysmith
Sticky Note
nothing is between ( and ; because it was assigned above loop
kimberlysmith
Highlight
Page 6: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Review : FactorialCreate a Factorial application that prompts the user for a number and then d isplays its factorial. The factorial of a number is the product of all the positive integers from 1 to the number. For example, 5! = 5*4*3*2*1.

Review : OddSumCreate an OddSum application that prompts the user for a number and then su ms the odd numbers from 1 to the number entered.

Debugging Techniques The sou rce of bugs, which are often logic errors, can be hard to deter-mine without tools for debugging an application. Debugging is the process of getting an application to work correctly. One tool included w ith many compilers is called a debugger.

A debugger is u sed to select statements where execution w ill be su s-pended. These statements are called breakpoints. Application output goes to a Debug Window and statements can be executed one at a time between breakpoints by using a Step command. When stepping through an applica-tion, selected variables are d isplayed in a Watch w indow along w ith their value. When a watch variable is assigned a new value, the Watch w indow is updated. Stepping through code and watching variables can an effective way to determ ine logic errors.

Another debugging tool is called a variable trace and is done manu-ally. A variable trace is a table listing the values of variables at the points of assignment. For the follow ing code, num1 and num2 wou ld be included in a variable trace:

i nt num1 = 0; i nt num2 = 0;whi l e ( num1 < 10) { i f ( num1 % 3 == 0) { num2 += num1; Sys t em. out . pr i nt ( num2 + " ") ; } num1 += 1;}

The variables are listed in the order that assignment occu rs w ith in the loop. Output is also listed to better u nderstand the code:

kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Sticky Note
Highlight bottom TIP
kimberlysmith
Sticky Note
% sign is modulus division (see pg. 83)
Page 7: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

A third debugging technique involves add ing add itional println() state-ments to an application. Add ing println() statements just after a variable is assigned a new value or before and after a cond ition is evaluated can help detect the sou rce of a logic error. For example, the code segment below includes add itional statements for debugging:

i nt num1 = 0; i nt num2 = 0;Sys t em. out . pr i nt l n( "num1 bef or e whi l e: " + num1); / / debugwhi l e ( num1 < 10) { Sys t em. out . pr i nt l n( "num1 i n whi l e: " + num1) ; / / debug i f ( num1 % 3 == 0) { num2 += num1; Sys t em. out . pr i nt l n( "num2:" + num2) ; / / debug Sys t em. out . pr i nt l n( num2 + " ") ; } num1 += 1;}

When ru n, the code above d isplays the follow ing output, which can be compared to the values expected. Note the sim ilarity to a variable trace:

Com menting out statements can be an effective way to locate a bug through process of elim ination. Typically the / / characters are easiest to type at the beginning of a statement to “com ment it out.”

Review : Variable TraceUsing paper and pencil, create a variable trace for the follow ing code, tracing the values of num1, num2, i , and any output:

i nt num1 = 0;i nt num2 = 0;f or ( i nt i = 0; i <= 4; i ++) { num1 = i * i ; num2 += num1; Sys t em. out . pr i nt ( num1 + " ") ;}Sys t em. out . pr i nt l n( num2) ;

kimberlysmith
Highlight
kimberlysmith
Highlight
kimberlysmith
Sticky Note
After students complete all highlighting of chapter, then they help me to hand simulate and trace this code using these headings... num1 num2 output i
Page 8: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

The St r ing Class Primitive data types such as i nt and doubl e are used for storing numeric data. However, when data is comprised of a sequence of characters, a data type for storing strings is needed. Java includes the String class in the java.lang package for storing and manipu lating strings. The String class is large, w ith nu merou s method s for string manipu lation. Some of the String class methods include:

Class String ( java.lang.String)

Methodsl engt h( ) returns an integer corresponding to the number

of characters in the string.s ubs t r i ng( i nt s t ar t , i nt end) retu rns a substring of the string, which starts

at s t ar t position and ends one character before the end position.

s ubs t r i ng( i nt s t ar t ) retu rns a substring of the string, which starts

at s t ar t position and extends to the end of the string.

t oLower Case( ) retu rns a copy of the string w ith all lowercase letters.

t oUpper Case( ) retu rns a copy of the string with all uppercase letters.

t r i m( ) returns a copy of the string with all lead ing and trailing spaces removed.

r epl aceFi r s t ( St r i ng s t r , St r i ng s t r 2) retu rns a string with the first occurrence of s t r

replaced by s t r 2.r epl aceAl l ( St r i ng s t r , St r i ng s t r 2) retu rn s a st r ing w ith all occu rrences of s t r

replaced by s t r 2. The position of a character in a string is called its index. The first char-acter of a str ing is at index 0. The last character of a str ing is at index length() – 1. The Midd leThree class below d isplays the three letters in the m idd le of a string:

publ i c cl as s Mi ddl eThr ee {

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { St r i ng phr ase, t hr eeLet t er s ; i nt phr aseLengt h; i nt mi d; Scanner i nput = new Scanner ( Sys t em. i n) ; / * get s t r i ng f r om user */ Sys t em. out . pr i nt ( "Ent er t ext t hat cont ai ns at l eas t t hr ee char act er s : ") ; phr ase = i nput . next Li ne( ) ; i nput . cl ose( ) ;

/ * det er mi ne mi ddl e of phr as e */ phr aseLengt h = phr as e. l engt h( ) ; mi d = phr as eLengt h / 2;

kimberlysmith
Sticky Note
highlight this box
kimberlysmith
Sticky Note
length of word
kimberlysmith
Line
kimberlysmith
Highlight
kimberlysmith
Highlight
Page 9: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

/ * di s pl ay mi ddl e t hr ee char act er s */ t hr eeLet t er s = phr as e. s ubs t r i ng( mi d - 1, mi d + 2) ; Sys t em. out . pr i nt l n( "Mi ddl e t hr ee char act er s ar e: " + t hr eeLet t er s ) ; }}

Note that the String objects (phr ase, t hr eeLet t er s) can be declared in the same way prim itives are declared—the data type followed by the vari-able name. With the String class, the follow ing two statements perform the same task:

St r i ng al pha = new St r i ng( "abc") ; / / t hes e as s i gnment s ar eSt r i ng al pha = "abc"; / / ef f f ect i vel y t he s ame

The Midd leThree application produces output sim ilar to:

A string is said to be immutable because it cannot be changed. Methods that manipu late the original string, for example toLowerCase(), create a new string in memory because the original string cannot be changed. Assigning a new string to a String object simply changes the object refer-ence to point to the new string in memory. For example, the following code generates a new string. Assigning the string to the text object changes the object’s reference:

St r i ng t ext ;t ext = "heLl O";t ext = t ext . t oLower Case( ) ;Sys t em. out . pr i nt l n( t ext ) ;

The code produces the output:

Until a String object is assigned a value, it refers to nul l . Calling a method from a nu ll String object generates the exception Nu llPointerException.

Review : Account Set upCreate an Accou ntSetup application that prompts the user for a user name and a password. The application shou ld prompt the user u ntil a password w ith at least eight characters is entered. The user name and pass-word shou ld be converted to all lowercase letters and then an appropriate message d isplayed. Application output shou ld look sim ilar to:

�����

���������

kimberlysmith
Highlight
kimberlysmith
Highlight
Page 10: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Comparing St r ings Strings are compared when determining equality or alphabetical order.In chapter 5, relational operators, includ ing == and >, were used to compare prim itive types. When objects need to be compared, methods from their class are u sed. Some of the String class method s for comparing strings include:

Class String ( java.lang.String)

Methodsequal s( St r i ng s t r ) retu rns true when the string is the same as s t r .

Returns false otherw ise.equal s I gnor eCas e( St r i ng s t r ) same as equ als() excep t that upp ercase and

lowercase d ifferences between the strings are ignored.

compar eTo( St r i ng s t r ) retu rns 0 when s t r is the same as the string, a

negative integer is retu rned when s t r comes alphabetically after the string, and a positive integer is retu rned when s t r comes alphabeti-cally before the string. Note that uppercase and lowercase letters are considered d ifferent.

compar eToI gnor eCase( St r i ng s t r ) same as compareTo() except that uppercase and

lowercase d ifferences between the strings are ignored.

i ndexOf( St r i ng s t r ) r et u r n s t h e in teger cor r esp ond in g to t h e

locat ion of the first occu rrence of s t r in the string. Otherw ise –1 is retu rned.

l as t I ndexOf( St r i ng s t r ) r et u r n s t h e in teger cor r esp ond in g to t h e

locat ion of the last occu rrence of s t r in the string. Otherw ise –1 is retu rned.

s t ar t sWi t h( St r i ng s t r ) retu rns true when the string begins w ith s t r .

Returns false otherw ise.endsWi t h( St r i ng s t r ) retu rns t rue when the str ing end s w ith s t r .

Returns false otherw ise.

The AlphaOrder class compares two strings and then d isplays them in alphabetical order:

publ i c cl as s Al phaOr der {

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { St r i ng wor d1, wor d2; Scanner i nput = new Scanner ( Sys t em. i n) ;

kimberlysmith
Highlight
kimberlysmith
Sticky Note
highlight this tip and go to website unicode.org/charts also view ASCII codes for keyboard characters at www.asciitable.com
Page 11: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Sys t em. out . pr i nt ( "Ent er a wor d: ") ; wor d1 = i nput . next Li ne( ) ; Sys t em. out . pr i nt ( "Ent er a s econd wor d: ") ; wor d2 = i nput . next Li ne( ) ; i nput . cl ose( ) ; i f ( wor d1. compar eToI gnor eCas e( wor d2) == 0) { Sys t em. out . pr i nt l n( "Wor ds ar e equal .") ; } el s e i f ( wor d1. compar eToI gnor eCas e( wor d2) < 0) { Sys t em. out . pr i nt l n( "I n al phabet i cal or der : " + wor d1 + " " + wor d2) ; } el s e { Sys t em. out . pr i nt l n( "I n al phabet i cal or der : " + wor d2 + " " + wor d1) ; } }}

AlphaOrder produces output sim ilar to the follow ing:

Review : FormalGreet ingCreate a FormalGreeting application that prompts the user for h is or her name, includ ing title. The applica-tion shou ld d isplay “Hello, sir.” if the string starts w ith Mr ., “Hello, ma’am.” if the string starts w ith Ms., Mr s. , or Mi s s, and “Hello, name.” otherw ise where name is the user’s name.

Chapter 6 Case St udy

In th is case study, a word guessing game w ill be created . The word guessing game allows the player to guess the letters of a secret word. At the start of the game, the player is show n only how many letters the word contains through a set of dashes. When a letter matching one in the word is guessed, it replaces the appropriate dash. Play continues until the entire word is guessed letter-by-letter or when the player chooses to guess the entire word.

WordGuess Specification

WordGuess is played between the computer and a single player. The secret word is BRAIN. At the start of the game, six dashes are d isplayed (––––––), one for each letter of the word. The player is repeatedly prompted for a letter guess. When a letter matching one in the word is guessed, the letter replaces the correspond ing dash. Letters may be entered as upper-case or lowercase. However, only uppercase letters shou ld be d isplayed. If the player enters an exclamation point (!), the player is prompted to guess the word. At that point the player either w ins (a correct guess) or loses (an incorrect guess). Alternatively, the player can continue to guess letters u ntil the entire word is revealed. The games ends by show ing the player the total nu mber of guesses.

Page 12: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

The WordGuess interface shou ld d isplay a row of dashes, one dash for each letter in the word. Prompts shou ld be used to get letter guesses from the player. As correspond ing letters are guessed, the letter is d isplayed instead of the dash. At the end of the game, the user shou ld be show n the word along with the number of guesses.

The WordGuess output sketch:

�����������������������������������������������������������������������������������������������������������������������������������������������������������������

���������������������������������������������������������������������������

The WordGuess algorithm:

1. Display a row of dashes to represent the word.

2. Prompt the user for a letter guess.

3. If the letter guessed is part of the word, then d isplay that letter in place of the correspond ing dash.

4. Repeat steps 2 and 3 u ntil all the letters have been guessed or an exclamation point has been entered by the user.

5. If an exclamation point has been entered, prompt the user to guess the entire word.

6. If the player correctly guesses the entire word or all the letters have been guessed, then d isplay a message ind icating that the player has won, otherw ise the message shou ld ind icate that the player has lost.

7. Display the secret word and the number of guesses.

Page 13: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

The WordGuess flowchart:

�����

������������������������������

������������������

�����������������������

������������������������������������

�����������������

�����������������

�����

���

��

���

����������������������������

��������������������������

���

��

�����������������

�����������������������������������������������

���

�����������������

��

Page 14: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

WordGuess Code Design

The input for WordGuess are letters typed by the user. A String vari-able to store the player’s letter guess w ill be needed. The player may also choose to guess the entire word, so another String variable to store a word guess w ill be needed.

The output for WordGuess is the secret word d isplayed as dashes and then red isplayed whenever a dash shou ld be replaced by a letter, a prompt for the u ser’s guess, a message ind icating a w in or loss, and a message ind icating the secret word and the number of guesses made.

Data generated by WordGuess is a count of the number of guesses made by the u ser. A cou nter variable to store the nu m ber of guesses w ill be needed. Other data u sed in th is application can be represented by String constants to represent the secret word (SECRET_WORD) and to use as a loop sentinel (FLAG). A String variable w ill also be needed to “bu ild” a new string that contains any correctly guessed letters.

Based on the algorithm and flowchart, the code design for the WordGuess application w ill include a loop structu re to compare the user’s input to the letters in the secret word. The best loop structu re w ill be a do- whi l e because u nder any cond ition the loop statements shou ld iterate at least once. It also u nknow n how many times the loop statements shou ld iter-ate, so a type of whi l e statement, not a f or statement, shou ld be used. This comparison w ill be done w ith an i f statement. A pseudocode algorithm for WordGuess follows:

Gener at e and di s pl ay a s et of das hes t hat r epr esent t he wor ddo updat e guess es count er Pr ompt us er f or a l et t er Conver t t o al l upper cas e Det er mi ne i f l et t er i s i n wor d i f l et t er i s i n wor d Cr eat e new s t r i ng t hat cont ai ns t he gues sed l et t erwhi l e ( al l l et t er s haven' t been gues s ed and us er has n' t chosent o gues s t he ent i r e wor d)i f ( ! has been ent er ed) get a wor d guess f r om pl ayer conver t wor d t o al l upper cas ei f ( wor d gues s ed equal s s ecr et wor d OR al l t he l et t er s have been guess ed) di s pl ay mes s age t hat pl ayer has wonel se di s pl ay mes s age t hat pl ayer has l os tDi s pl ay s ecr et wor dDi s pl ay number of guess es

WordGuess Implementation

Based on the code design, the WordGuess implementation follows:

/ * * Wor dGues s .j ava */ i mpor t j ava. ut i l . Scanner ;

Page 15: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

/ ** * Pl ays a wor d gues s i ng game wi t h one pl ayer . */ publ i c cl as s Wor dGuess {

publ i c s t at i c voi d mai n( St r i ng[ ] ar gs ) { f i nal St r i ng SECRET _ WORD = "BRAI N"; f i nal St r i ng FLAG = "! "; St r i ng wor dSoFar = "", updat edWor d = ""; St r i ng l et t er Gues s , wor dGues s = ""; i nt numGuess es = 0; Scanner i nput = new Scanner ( Sys t em. i n) ; / * begi n game */ Sys t em. out . pr i nt l n( "Wor dGues s game.\ n") ; f or ( i nt i = 0; i < SECRET _ WORD. l engt h( ) ; i ++) { wor dSoFar += "- "; / / wor d as das hes } Sys t em. out . pr i nt l n( wor dSoFar + " \ n") ; / / di s pl ay das hes / * al l ow pl ayer t o make gues s es */ do { Sys t em. out . pr i nt ( "Ent er a l et t er ( " + FLAG + " t o gues s ent i r e wor d) : ") ; l et t er Gues s = i nput . next Li ne( ) ; l et t er Gues s = l et t er Guess . t oUpper Case( ) ; / * i ncr ement number of guess es */ numGues s es += 1; / * pl ayer cor r ect l y gues sed a l et t er - - ext r act s t r i ng i n wor dSoFar * up t o t he l et t er guess ed and t hen append gues s ed l et t er t o t hat * s t r i ng Next , ext r act r es t of wor dSoFar and append af t er t he guess ed * l et t er */ i f ( SECRET _ WORD. i ndexOf( l et t er Guess ) >= 0) { updat edWor d = wor dSoFar . s ubs t r i ng( 0, SECRET _ WORD. i ndexOf( l et t er Guess )) ; updat edWor d += l et t er Gues s ; updat edWor d += wor dSoFar . s ubs t r i ng( SECRET _ WORD. i ndexOf( l et t er Guess ) +1, wor dSoFar . l engt h( )) ; wor dSoFar = updat edWor d; } / * di s pl ay guess ed l et t er i ns t ead of das h */ Sys t em. out . pr i nt l n( wor dSoFar + " \ n") ; } whi l e ( ! l et t er Gues s . equal s( FLAG) && ! wor dSoFar . equal s( SECRET _ WORD)) ; / * f i ni s h game and di s pl ay mess age and number of gues ses */ i f ( l et t er Gues s . equal s( FLAG)) { Sys t em. out . pr i nt l n( "What i s your gues s? ") ; wor dGues s = i nput . next Li ne( ) ; wor dGues s = wor dGuess . t oUpper Case( ) ; } i f ( wor dGues s . equal s( SECRET _ WORD) | | wor dSoFar . equal s( SECRET _ WORD)) { Sys t em. out . pr i nt l n( "You won! ") ; } el s e { Sys t em. out . pr i nt l n( "Sor r y. You l ose.") ; } Sys t em. out . pr i nt l n( "The s ecr et wor d i s " + SECRET _ WORD); Sys t em. out . pr i nt l n( "You made " + numGues s es + " gues ses .") ; }

}

Page 16: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

A ru n of WordGuess looks sim ilar to:

WordGuess Testing and Debugging

This case study should test all possible guess combinations. For example, the player m ay enter an exclam ation point on the first guess. Test ing shou ld also include incorrect word guesses.

Review : WordGuessModify the WordGuess Chapter 6 Case Study to d isplay a score at the end of each game. The player shou ld start w ith 100 points and have 10 points taken off for each guess. The score shou ld be updated and d isplayed as the game is played. Display a player loses message if the score gets dow n to 0.

Chapter Summary

This chapter introduced loop structu res and the String class. The whi l e statement and do- whi l e statement are loop structu res that iterate a set of statements repeated ly based on a cond ition. The d ifference between the loops is when the cond ition is evaluated. The whi l e statement evaluates the cond ition before any iterations are performed. The do- whi l e does not evaluate the cond ition u ntil after the first iteration.

Page 17: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Some syntax errors and logic errors can lead to an infinite loop, which executes forever causing the application to just hang. A logic error can also cause an overflow, which occu rs when there are not enough bits to store a number.

Cou nters are u sed for keeping track of loop iterations and are u sed in applications that keep track of the nu mber of guesses or the nu mber of values entered . An accu mu lator is increased by varying amou nts. Accumulators are often used to sum values. Both cou nters and accumula-tors shou ld be in itialized when they are declared.

A flag, also called a sentinel, is used to signify that a loop shou ld stop iterating. Flags are usually a constant that is declared in the application, but may also be determ ined by prompting the user for a value.

The f or statement is another loop structure. This loop structure executes a set of statements a fixed number of times. A loop control variable is used to determine loop iterations and can be declared in the f or statement itself. When a variable is declared in a statement, its scope is lim ited to the open-ing and closing cu rly braces of that statement. The increment operator (++) and decrement operator (- - ) are used to increase or decrease the value of a f or loop control variable.

Debugging techniques include using a debugger, often included with a compiler, and a variable trace, which is a manual technique. Debuggers have the advantage of being able to d isplay the actual value of a variable as it changes. Other techniques include add ing println statements before and after variable assignment. Com menting out statements can also locate an error through process of elim ination.

The String class is used to declare string variables. It contains numerous methods for determining the length of a string, converting a string to low-ercase or uppercase characters, extracting substrings, and for comparing strings. A string is im mutable, which means it cannot be changed from its original value. However, a String object can be assigned a new string in memory. The characters of a string have an index value, w ith the first character at index 0.

Code conventions introduced in th is chapter are :

• The statements of an whi l e statement shou ld be indented.

• The statements of a do- whi l e statement shou ld be indented.

• The statements of a f or statement shou ld be indented.

• Declare variables so that their scope is lim ited to where they are needed.

• Changes to a loop control variable shou ld occu r in the increment portion of the loop only, and the loop shou ld end only when the cond ition is false.

Page 18: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Vocabulary

Accu mu lator A variable that is incremented by varying amou nts.

Breakpoint A statement selected where execution w ill be suspended.

Cou nter A variable that is incremented by a fixed value.

D ebugger A tool included w ith some compilers for debugging.

Debugging The process of getting an application to work correctly.

D ecrem en t op erator The - - op erator, w h ich decreases the value of a variable by 1.

Flag see Sentinel.

Im mutable Unable to change.

Increment operator The ++ operator, which increases the value of a variable by 1.

Index The position of a character in a string.

In fin ite loop A loop that continues forever.

Iteration The execution of a loop.

Loop con trol var iable A cou nter that is u sed to control the nu mber of f or loop iterations.

Loop structu re A statement that executes a set of statements repeated ly based on a cond ition.

N u l lPoi n te rExcep t ion excep t ion A n excep -tion th row n when operations on a nu ll String are attempted.

O verflow A cond ition that occu rs when a number is too large to be stored in a specified nu mber of bits.

Sentinel A constant that stores a value that is used to sign ify that a loop shou ld stop iterating. Also called a flag.

Scope The set of statements that can access a declared variable.

Variable t race A table listing the values of vari-ables at the points of assignment. Used for manually debugging an application.

Java

++ The increment operator.

- - The decrement operator.

do- whi l e A loop structu re that executes a set of statements over and over again based on a cond ition, which is evaluated after an iteration.

f or A loop structu re that executes a set of statements a fixed nu mber of times.

whi l e A loop structu re that executes a set of state-ments over and over again based on a cond ition, which is evaluated before any iterations.

String A java.lang class w ith methods for manipu-lating and comparing strings.

Page 19: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Crit ical Thinking

1. What is the pu rpose of a loop structu re?

2. Explain the d ifference between a whi l e statement and a do- whi l e statement.

3. An input validation loop is a loop that checks u ser input for valid d ata. If valid d ata is not entered , the loop iterates u nt il valid d ata is entered . In wh ich review of th is chap ter d id you write code for an input validation loop?

4. a) What is an infinite loop? b) List two types of errors that can lead to an

infinite loop. c) What is meant by overflow?

5. H ow m a ny t im es w ill t h e d o - wh i l e loop execute?

i nt x = 0; do { x = x + 2; whi l e ( x < 120) ;

6. What in it ial value of x wou ld m ake the loop infinite?

do { x = x + 3; whi l e ( x < 120) ;

7. Compare and contrast cou nters and accumula-tors. List two uses for each.

8. Write a f or statement that su m s the integers from 3 to 10, inclusive.

9. List two factors that shou ld be considered when determ ining which loop structu re to choose.

10. a) Li s t t w o m e t h o d s fo r d e b u g g i n g a n application.

b) Which method listed in part (a) wou ld be best for debugging an application that gen-erates random nu m bers that are u sed for determ in ing the cond it ion of an i f state-ment? Why?

11. Consider the follow ing assignment: St r i ng x = "my s t r i ng.";

Determ ine the value retu rned by each of the follow ing methods:

a) x. l engt h( ) b) x. s ubs t r i ng( 0, 3)

c) x. t oLower Case( ) d) x. t oUpper Case e) x. t r i m( )

12. Consider the follow ing statements: St r i ng x = "l ot s of wor ds ."; St r i ng y = "Lot s of Wor ds."; St r i ng z = "Two wor ds .";

Determ ine the value retu rned by each of the follow ing methods:

a) x. equal s( y) b) x. equal s I gnor eCas e( y) c) x. compar eTo( z) d) x. compar eToI gnor eCase( y) e) x. compar eToI gnor eCase( z) f) x. I ndexOf( "or ") g) x. l as t I ndexOf( "o") h) z. s t ar t sWi t h( "Tw") i) x. endsWi t h( "ds")

13. a) Write an algorithm to cou nt the nu mber of words in a sentence.

b) Write an algorithm to cou nt the nu mber of letters in a sentence.

True/ False

14. Determ ine if each of the follow ing are true or false. If false, explain why.

a) A whi l e statement iterates once before evalu-ating the cond ition.

b) A cou nter is increm ented by a con stant amou nt.

c) An accu mulator signifies that a loop shou ld stop iterating.

d) Sentinel values mu st always be the value –1.

e) A variable declared in a f or statement can be used again anywhere in the program code.

f) String variables are prim itive data types. g) The first ch aracter of a st r ing h as ind ex

position 1. h) Strings are compared using relational opera-

tors such as >. i) The String class includes a method for deter-

m ining the location of a substring w ithin a string.

Page 20: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Exercises

Exercise 1 ——————————————————— Prime Numb e ra) A prime nu mber is an integer greater than 1 that is even ly d ivisible by on ly 1 and

itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Create a PrimeNumber application that prompts the user for a number and then d isplays a message ind icating whether the number is prime or not. H int: The % operator can be used to determ ine if one number is evenly d ivisible by another.

b) Modify the application to prompt the user for two numbers and then d isplay the prime numbers between those numbers.

Exercise 2 ————————————————————Prime FactorsThe Fu ndamental Theorem of Arithmetic states that every positive integer is the product of a set of prime numbers. This set is called the prime factors. For example, the prime factors for 140 are 2, 2, 5, and 7 (2*2*5*7 = 140). Create a PrimeFactors application that prompts the user for a positive integer and then d isplays that integer’s prime factors. Use the follow ing pseudocode when implementing the PrimeFactors code:

I ni t i al i ze a count er t o 2whi l e t he count er i s l es s t han or equal t o t he number i f t he count er di vi des t he number evenl y di s pl ay t he count er di vi de t he number by t he count er t o get a new number el s e i ncr ement count er by 1

Exercise 3 —————————————————————Inve stme ntCreate an Investment application that calcu lates how many years it w ill take for a $2,500 investment to be worth at least $5,000 if compou nded annually at 7.5%

Exercise 4 ö ———————————————————— CarRe callMod ify the CarRecall application created in Chapter 5 Exercise 4 to allow the user to input as many model numbers as needed. Use 0 as a sentinel to end user input. The application output shou ld look sim ilar to:

Page 21: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Exercise 5 ——————————————————— Dig itsDisp layCreate a DigitsDisplay application that prompts the user for a non-negative integer and then d isplays each d igit on a separate line. Application output shou ld look sim ilar to:

Exercise 6 ————————————————————— Dig itsSumCreate a DigitsSum application that prompts the user for a non-negative integer and then d isplays the sum of the d igits. Application output shou ld look sim ilar to:

Exercise 7 —————————————————————Cub e sSuma) Create a CubesSum application that prompts the user for a non-negative integer and

then d isplays the sum of the cubes of the d igits. Application output shou ld look similar to:

b) Mod ify the application to determ ine what integers of two, three, and fou r d igits are equal to the sum of the cubes of their d igits.

Exercise 8 ö ————————————————— Gue ssing GameThe GuessingGame application created in Chapter 5 Exercise 8 would be more fu n if users cou ld make as many guesses as necessary to guess the secret number. Mod ify the GuessingGame application as follows:

a) Mod ify the algorithm to allow for as many guesses as needed.

b) Modify the flowchart based on the algorithm mod ifications.

c) Mod ify the GuessingGame code. Application output shou ld look sim ilar to:

Page 22: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

d) A binary search is a d ivide-and-conquer technique for efficiently searching a list of numbers that are sorted from lowest to highest. A strategy that incorporates the binary search techn ique can be u sed by the Guessing Game player when making guesses about the secret number:

1. Guess the number halfway between the lowest and highest numbers.

2. If the number guessed matches the secret number, then the player w ins.

3. If the nu mber guessed is too h igh, then take the nu mber guessed m inus one and make this the highest number and go back to Step 1.

4. If the number guessed is too low, then take the number guessed plus one and make this the lowest nu mber and go back to Step 1.

For example, assu m ing 15 is the random nu mber generated in the Guessing Game application, the game wou ld play out as follows when the player uses a d ivide-and-conquer technique:

Cu rrent Low Cu rrent H igh Player Types Message Displayed

1 50 26 (i.e., (1+50)/ 2=25.5) Too high.

1 25 13 (i.e., (1+25)/ 2=13) Too low.

14 25 20 (i.e., (14+25)/ 2=19.5) Too h igh.

14 19 16 (i.e., (14+19)/ 2=16.5) Too h igh.

14 15 14 (i.e., (14+15)/ 2=14.5) Too low.

15 15 15 (i.e., (15+15)/ 2=15) You guessed it!

In another program ru n, assu m ing the random nu m ber generated is 20, the game wou ld play out as follows using the same d ivide-and-conquer technique:

Cu rrent Low Cu rrent H igh Player Types Message Displayed

1 50 26 (i.e., (1+50)/ 2=25.5) Too high.

1 25 13 (i.e., (1+25)/ 2=13) Too low.

14 25 20 (i.e., (14+25)/ 2=19.5) You guessed it!

When th is approach is taken, it has been proven that a player w ill not be requ ired to make more than Log2n guesses, in th is case Log250, or at most 6 guesses. Try this technique yourself. Explain in your ow n words why this works. Would this strategy be possible if h ints were not given after each guess?

Exercise 9 ————————————————————Powe rsTab leCreate a PowersTable application that d isplays a table of of powers sim ilar to:

Page 23: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Exercise 10 ——————————————————————— GCDCreate a GCD application that prompts the user for two non-negative integers and then d isplays the greatest com mon d ivisor (GCD) of the two nu mbers. The GCD is the largest integer that d ivides into both nu mbers evenly. An algorithm for find ing the GCD is called Euclid’s Algorithm. Use the follow-ing pseudocode when implementing the GCD code:

whi l e ( num2 > 0) { t emp = num1 % num2; num1 = num2; num2 = t emp;}

Application output shou ld look sim ilar to:

Exercise 11 ———————————————Elap se dTime CalculatorWhat comes 13 hours after 4 o’clock? Create an ElaspsedTimeCalcu lator application that prompts the user for a starting hour, whether it is am or pm, and the number of elapsed hours. The application then d isplays the time after that many hours have passed. Application output shou ld look sim ilar to:

Exercise 12 ————————————————————— Ne cklaceAn interesting problem in number theory is sometimes called the “necklace problem.” This problem begins w ith two single-d igit nu mbers. The next nu mber is obtained by add ing the first two numbers together and saving only the ones d igit. This process is repeated u ntil the “necklace” closes by retu rn-ing to the original two numbers. For example, if the starting two nu mbers are 1 and 8, twelve steps are requ ired to close the necklace: 1 8 9 7 6 3 9 2 1 3 4 7 1 8

Create a Necklace application that prompts the user for two single-d igit integers and then d isplays the sequence and the nu mber of steps taken. The application output shou ld look sim ilar to:

Page 24: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Exercise 13 ————————————————————— HailstoneAn interesting (yet u nsolved) question in mathematics is called “hailstone nu mbers.” Th is series is produced by taking an in itial integer, and if the nu mber is even, d ivid ing it by 2. If the nu mber is odd, mu ltiply it by 3 and add 1. This process is then repeated. For example, an in itial nu mber of 10 produces:

10, 5, 16, 8, 4, 2, 1, 4, 2, 1 …

An initial value of 23 produces:

23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1 …

Note that both numbers eventually reach the 4, 2, 1, 4, 2, 1 … cycle. Create two applications (Hailstone1 and Hailstone2) that answer the follow ing questions for in itial values of 1 to 200:

a) Do all integers from 1 to 200 eventually reach this cycle?

b) What is the m aximu m nu m ber of iterations to reach the cycle and wh ich starting number produces th is maximum?

Exercise 14 ————————————————————— Dice RollsCreate a DiceRolls application that d isplays five rolls of two d ice where each d ie is numbered from 1 to 6. The application shou ld also show the total of each roll:

Exercise 15 ——————————————————————— Chaos“Chaos theory” is a subfield of mathematics which relies heavily on the computer. A simple chaos experiment is:

Start w ith any real nu m ber x between 0 and 1. Generate a new nu m ber u sing the “logistic equation:”

x = 2*x( 1 - x)

Display th is new x and repeat the process 50 times.

a) Create a Chaos application that prompts the user for a starting value and then performs this experiment. Make a pred iction about what happens for d ifferent starting values.

b) Mod ify the application so that the 2 in the logistic equation can be replaced w ith a value specified by the user in the range 2 to 4, but the starting value of x is always 0.5. Note any interesting behavior.

Page 25: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Exercise 16 ————————————————————RandomWalkIn the “random walk” problem, a person is placed at the center of a 7 meter long bridge. Each step the person moves 1 meter either forward or backward at random.

Create a RandomWalk application that determ ines how many steps the person will walk before taking a step off the bridge. Have the application average 50 trials, and d isplay the average and the greatest nu mber of steps. (H int: Generate a random number between 0 and 1, w ith 0 meaning to go forward and 1 meaning to go backward.)

Exercise 17 ————————————————————— PasswordCreate a Password application that stores a secret password of your choice. The Password application shou ld prompt the user for the password and then d isplay “Welcome” if the correct password is typed. If after three tries the correct password has not been entered, the message “Access denied.” shou ld be d isplayed. Application output shou ld look sim ilar to:

Exercise 18 —————————————————————Monog ramCreate a Monogram application that prompts the user for his or her first name, m idd le name, and last name and then d isplays a monogram w ith the first and m idd le in itials in lowercase and the last in itial in uppercase. Application output shou ld look sim ilar to:

Exercise 19 ——————————————————— Re move Str ingCreate a RemoveString application that prompts the user for a sentence and a string. The application shou ld then remove every occu rrence of the string from the sentence. The application shou ld look sim ilar to:

Page 26: r draw a line to this and write no semicolon write in ...€¦ · Chapter 6 Loop Structures and Strings L oop structures, counters and accumulators, and flags are explained in this

Chapter 6 Loop Structures and Strings

Exercise 20 ————————————————————CountVowe lsCreate a Cou ntVowels application that prompts the user for a string and then d isplays a cou nt of the number of vowels in the string. Application output shou ld look sim ilar to:

Exercise 21 ————————————————— Group Assig nme ntCreate a GroupAssignment application that prompts the user for h is or her name and then d isplays a group assignment. The group assignment depends on the first letter of the student’s last name. Last names beginning w ith A through I are assigned to Group 1, J through S are assigned to Group 2, T through Z are assigned to Group 3. Application output shou ld look sim ilar to: