Friday, February 12, 2016

Loops.

The while and for loops are the most important types of loops, and the most commonly used, there is also an advanced for loop called the for each loop but arrays are needed for it.
The while loop is a loop that keeps doing the code inside it until it's conditional is false.

boolean end = false;
int point = 0;
while(!end){
point ++;
if(point > 10){
end;
}
}
//this will run the loop until points is 10

As well as there being a for loop which runs the loop until the conditional say x < 10 reaches false, but is written differently than the while loop and is more controllable.

int point = 0;
for(int i = 0; i < 10; i++){
point++;
System.out.println(point);
}
//this program will run the loop ten times and will print on the console numbers from 1 to 11
// this is because the value of point is increased before the print statement

Loops are allowed to be inside of each other and you can use multiple combinations of the code to achieve different outcomes.

while(!end){
for(int i = 0; i < 10; i++){
point++;
System.out.print(point);
}
System.out.println();
if(point > 30){
end = true;
}
}
//this will run the loops until point is 30, the for loop will run 30 times and the while loop 3 times

For the next loop you will need to know about arrays, which is another post in this blog. After knowing about arrays you can use the for each loop, which loops for every array object or value.

int[] array = new int[4];
for(int arr : array){
arr = 3;
}
//this sets every int of the array to the number 3
//for-each loops are useful for scrolling around arrays quickly

4 comments:

  1. loops is the concept that got me into coding I think the way you explain it is pretty cool thanks for sharing

    ReplyDelete
  2. Loops is very useful in making games. I've used it quite a bit.

    ReplyDelete
  3. Loops is very useful in making games. I've used it quite a bit.

    ReplyDelete
  4. i dont understand yet, but i get it, ill hire you if i ever need to hack into someones account.

    ReplyDelete