Lesson 3: Loops
Loops are the best things in the world. Imagine yourself having to write "1" to the console 1000 times. You will find the job tedious, and soon want to quit. This is where our programs kick in. Through loops, they repeat things over and over, until we tell them to stop.
In our case, we will ask our program to stop printing 1 when one thousand "1" have been printed on console. It will be:
for(int i=0;i<1000;i++){
System.out.println(1);
}
"for" is one of the most common loop that we see, along with while. Lets talk about "for" first.
There are three parts to the for loop. (1) Variable initialization(that's used for condition) (2) Condition ( True or False ) (3) Action every loop(eg. increment the variable in (1))
for( (1) ; (2) ; (3) );
To explain our code above, (1) we first introduce a variable called i, which is a common variable when used to iterate(loops), and initialize it to 0. (2) our condition is when i < 1000. if i = 1000, the condition will return false, and loop will end. (3) for each iteration, we increase the value of i by 1.
int i=0;
while(i!=1000){
System.out.println(1);
i++;
}
"while" is the other loop we commonly encounter. While(condition) is the syntax, and this loop is used for repeated actions, while for loops are common for iterating over arrays and other iterations. In our code above, our condition is when i is not 1000. This will return false when i = 1000. Similar syntax to our for loop, but different in a way that it can be expressed like this:
Boolean isThousand = false;
int i =0;
while( !isThousand ) {
System.out.println(1);
i++;
if( i == 1000 ) {
isThousand = true;
}
}
While loops are pretty useful, but sometimes if the condition is false from the beginning, the loop does not even execute. In such cases, we have "DO - WHILE" loops, which will execute at least once.
Boolean insane = true;
do {
//something crazy
} while ( insane )
simply putting it, the condition is evaluated at the bottom of "do" section. Therefore, whether insane is true or not, "something crazy" will happen at least once.