Monday, 8 December 2008

For Loop - First Draft

The for loop allows us to specify the number of times a code block will repeat. We use an int type variable to define the loop's iteration. A for loop takes a start value, an exit loop conditional clause and the amount, the looping integer will be changed by, in each iteration of the loop. For loops can be incremented or decremented as the loop is traversed.
It sounds a lot more complex than it is in practice!

for(int n=0;n==10;n++) //starts at 0 - stops at 10 - increments by 1
{ //code block to be repeated is contained within curly brackets
function1(n);//performs some operation
a=+n; //performs some other operation (can contain many statements)

} // for loop ends
The code block to be executed, need not use the integer that is used in the loop, and can instead, perform some operation, a certain number of times.
The first two statements in the first line of a for loop always end in a semi colon. The first statement initialises the integer, in this example the integer is declared and initialised within the loop, making the integers scope local in the loop. However the integer can be declared elsewhere, thus changing its scope.

int n;
for (n=10;n <= 100;n=n+10){
println("number's final value: "+n);

In this next loop the value of for's integer is decreased in each iteration
for(int n=10;n > 0;n--){
println("Blast Off!");

Chunk 16 uses a for loop to control how many patterns are used to make a picture:
for(count=0;count < patternsPerPicture;count++){
a great many statements to repeat!}

As long as count's value, is less than the constant patternsPerPicture the statements in the for loop will execute. Each time the loop is repeated the value of n is increased by one. If we changed the loop to start at one, then we would need to change the conditional to count <=patternsPerPicture+1; When the for loop is finished the value of patternsPerPicture is changed to a random number between 2 and 50, the variables count and design are reset to zero and the for loop is entered again, with the new exit value condition. (patternsPerPicture)

Another example of the for loop can be seen in the drawCircles(int) function. Here the value of n is increased by the gap parameter, which is sent by the calling statement. So in each iteration, the drawCircle(int) method is called with n incremented by the value of gap which should produce a larger circle in each repetition of the loop. This for loop stops at a random number between the centre and edge of the display window.


    Leave the for loop start at zero otherwise the background never gets cleared!

  2. Ignore last note, it is utter rubbish!
    add background(0); before for loop is entered to clear background for a new picture. If the value of n is zero the iteration still takes place! Idiot! How many times have you used Array[n] to get the first value in an array!
    Cant believe you wrote this gibberish!
    Matbe you should have a break...