The for statement is similar to the while statement, but it is often easier to use if you are counting or indexing because it combines three elements of many loops: initialization, testing, and incrementing.
The for and equivalent while statements have these forms.
for (init-stmt; condition; next-stmt) {
body
}
|
init-stmt;
while (condition) {
body
next-stmt;
}
|
There are three clauses in the for statement.
while loop).Here is a loop written as both a while loop and a for loop. First using while:
int number = 1;
while (number <= 12) {
System.out.println(number + " squared is " + (number * number));
number++;
}
And here is the same loop using for.
for (int number = 1; number <= 12; number++) {
System.out.println(number + " squared is " + (number * number));
}
This code will look at each character in a string, sentence, and count the number of times any character occurs doubled.
String sentence = ...;
int doubleCount = 0; // Number of doubled characters.
// Start at second char (index 1).
for (int pos = 1; pos < sentence.length(); pos++) (
// Compare each character to the previous character.
if (sentence.charAt(pos) == sentence.charAt(pos-1)) {
doubleCount++;
}
}
The for loop is s