To date we have used loops to repeatedly run code until some condition is met. Sometimes however, we know exactly how many times we would like a loop to run. A while loop to print the numbers from 0 to 10 would appear as follows:
int counter = 0; //initialisation statement
while (counter <= 10) { //continue condition
System.out.println(counter);
counter++; //code executed post iteration
}
One of the negatiaves of using this format is that the initialisation statement (in this case code to keep count), the condition, and the code executed after iteration, are seperated from each other.
A different type of loop, a for
loop, provides a more concise (though with syntax that is slightly more tricky to learn) way of doing things. The structure of a for loop is as follows:
for (<initialisation statement>; <continue condition>; <increment statement>) {
//do something
}
If we wanted to convert our original while
statement into a for
statement, the resulting code would look like this:for (int counter = 0; counter <= 10; counter++) {
System.out.println(counter);
}
This code is now neater, and it has the additional benefit that the counter
variable is only available inside the for
loop, this avoids confusion, and means you can use the same variable name for another loop later in the same code
It's worth being aware that it is very common practise to use the letter 'i' as the variable name for a counter, thus code like this is very common:
for (int i = 0; i <= 10; i++) {
System.out.println(i);
}
In the above example, we started our loop at 0 and incremented the counter by 1 every iteration, we are no means limited to doing this, the example below shows a loop that starts at 20, and decreases by 2 until just before 10:
for (int i = 20; i > 10; i -= 2) {
System.out.println(i); //prints 20, 18, 16, 14, 12
}
For each of the following sequences, create a command line programme, and use the For loop syntax generator to get the code for a loop, add the relevent code as neccesary inside the loop, check that the result is as expected:
x
i
Without using the syntax generator, complete the following tasks in the same format, but this time write the code yourself, using an example on the page above as reference if needed. Check each loop behaves as expected and then delete all the loop code before starting the next task
counter
i
0:00am 1:00am 2:00am 3:00am ... 11:00am 12:00pm 1:00pm ... 11:00pm
Using two loops (one inside the other), print out all the minutes of a day using the 24 hour clock. The start of the output would be as follows:
0:00 0:01 0:02 ...