Program 5.8: += in a for loop
However what do you do when you want to increment not by one but by two? or three? or fifteen? You could of course write i = i + 15, but this also happens frequently enough that there's another shorthand for the general add and assign operation, +=. You would normally write this as i += 15. Program 5.8 uses += to count from 0 to 20 by twos.
class CountToTwentyByTwos {
public static void main (String args[]) {
int i;
for (i=0; i <=20; i += 2) {
System.out.println(i);
}
System.out.println("All done!");
} //main ends here
}
Here's the output:
% javac CountToTwentyByTwos.java
% java CountToTwentyByTwos
0
2
4
6
8
10
12
14
16
18
20
All done!
%
Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home