Loops

A general principal in programming : DRY or Don't Repeat Yourself. If you find yourself writing exactly the same code more than once, you need to stop and find a way to reuse what you already written. In programming we call this iteration or loops, meaning take a few statements, put in a block, and repeat that block multiple times.

Creating a loop is easy. The thing you have to worry about is making that loop to stop. We will cover two of the most common loop used in programming.

While Loop

The basic idea of this loop is :

while some condition is true {
    statement one
    statement two
    statement three
    ...
}

Like using if/else, the condition must be resulting in true or false. If true, the statements inside the block will executed. After that, program will check that condition again. If still true, that block will executed again. If false, then the loop is stopped and that block is ignored. That is the basic idea of while loop.

while balance > 1000 {
    print("Nice!")
}

Now see the code above, what do you think will happen? Yes, the loop will never stop because value of balance never change. You have to be careful about this. What we expect is something in this code will eventually change this condition when we check it to false.

while balance > 1000 {
    print("Nice!")
    balance = balance - 500
}

Now this block will be only executed twice, because in each loop variable balance is subtracted by 500. After the second loop, balance have value of 0, and the condition will resulting false.

For Loop

The other common way is using For Loop. It's similar to While Loop, you have condition and code block. The different is in For Loop, we know how much we want to looping the block. Simple example :

for (int counter=0; counter<5; counter++) {
    print("nice");
}

Maybe it looks more complex, but the basic actually really similar. Let see it step by step :

  1. When we entering the first loop, integer named counter will be created and given initial value of 0
  2. Next, program will check whether counter is less than 5
  3. If true, print "nice". If false, ignored the block.
  4. If true, adding counter by 1 (see that ++ operator? It called increment. It's the easy way to adding 1 to variable)
  5. Back to number 2

Other Loop

Many languages also have For-In/For-Each Loop. This is when you don't want to keep track about specific number iterations, you want to repeat a section of code based on how many thing you have. The typical format is :

for each item in collection {
    //statement to execute
    ...
}

Of course this means you have to that collection, piece of data that contain another pieces of data.

results matching ""

    No results matching ""