1. The for loop The for loop So far we have used while loops whenever we needed to carry out a sequence of steps over and over. A while loop was often controlled by a single variable and was characterized by 3 elements: - initialization of control variable - loop condition - update of control variable Here is one of the earlier example where the three elements are highlighted:void printSpelling( String phrase ) { int index = 0; while ( index < phrase.length() ) { char curLetter = phrase.charAt( index ); System.out.println( curLetter + ", " ); index = index + 1; } }In the loop above the control variable has a very well-defined: - starting value -- index = 0 - loop condition -- index < phrase.length() - update increment -- index = index + 1 Such loops are so common that Java offers a new construct that puts all 3 loop elements on a single line. This makes it easy to see how the loop is controlled and how it works. A for loop can make the the intentions of the programmer much clearer, so it is good to use it whenever possible. Typically this would be in situations where the loop is controlled by a variable that has well-defined starting value and updates via fixed increments. On the other hand, the guessing game is a good example of appropriate use ofwhile loop. Here is a comparison of the structure of while and for loop. One is simply a rearrangement of the other. Here are a few of the earlier examples re-written with for loops: Spelling a word
initialize control variable while ( loop condition ) { LOOP BODY -- THE ACTUAL WORK update control variable }for ( initialize control variable ; loop condition ; update control variable ) { LOOP BODY -- THE ACTUAL WORK }Counting character in a string
void printSpelling( String phrase ) { int index = 0; while ( index < phrase.length() ) { char curLetter = phrase.charAt( index ); System.out.println( curLetter + ", " ); index = index + 1; } }void printSpelling( String phrase ) { for ( int index = 0 ; index < phrase.length() ; index = index + 1 ) { char curLetter = phrase.charAt( index ); System.out.println( curLetter + ", " ); } }
int countCharacter( String phrase, char letter ) { int result = 0; int index = 0; while ( index < phrase.length() ) { char curLetter = phrase.charAt( index ); if ( curLetter == letter ) { result = result + 1; } index = index + 1; } return result; }int countCharacter( String phrase, char letter ) { int result = 0; for ( int index = 0 ; index < phrase.length() ; index = index + 1 ) { char curLetter = phrase.charAt( index ); if ( curLetter == letter ) { result = result + 1; } } return result; }