For Loops
There are several kinds of loops in java—the for loop, a while loop, and a do-while loop. We’ll focus on the for loop. More information about the others can be found in here. The basic format for a for loop is
for (initial counter value; logical statement; increment){
//put code here
}
Example:
for (int counter=1; counter<=10; counter++){
//Put code here
}
This is a loop with an initial counter value of counter=1, a logical statement of counter<=10 (this causes the loop to run until counter has exceeded 10), and an increment of counter++ which increments the integer variable counter by 1 after each pass through the loop.
Observations.
- Note that I’ve declared counter as an int inline. This means that I have not declared the variable counter previously. Of course, if I have previously declared the variable counter, then there is no need to declare it again here. One benefit of doing inline declarations is that when the program passes out of scope (i.e. out of this loop), the variable counter is no longer accessible and will prevent accidental increment/decrements.
- The expression counter++; is shorthand for counter=counter+1; If you wish to increment by 2, you can utilize the expression counter=counter+2; or counter+=2;. Both will do the same thing. Similarly, if you wish to decrement counter by one, counter--; will do the trick as will counter=counter-1;. If you wish to multiply the counter by 3 on each pass through the loop, counter=counter*3; and counter*=3; are equivalent expressions.
- Historical note. The “”++” in the C++ programming language is a nod towards this shorthand notation and suggests that C++ is a little bit more than the language C. And this is certainly true since C is a subset of C++, even though C++ was developed after C was created.
You try it...
- Write a loop that will add up the numbers one through 10 and store the answer in the integer variable answer when clicking computeButton.
- Output your answer to loopLabel. You must use the setText(String) method to output to loopLabel. Since this method requires a String as an argument, you must convert answer to String. The easiest way to do this is to append it to another String with the + operator. In the context of the setText(String) method, Java will force the type of the appended String and int to be a String.
- Build and run your applet. If you’ve done everything correctly, your result should be 55.
See Sample Code 1 to check work.