Tuesday, January 21, 2014

Control Structures - Loops

This post is linked with this, which we have talked about the IF, IF ELSE, IF ELSE IF and SWITCH CASE. So please make sure you read that and then come to this.

So you already know there are 2 types of control structures. The first one we have already discussed, the Conditional Statements. What we have left with is the Iterative structures. Simply the looping structures or the repeating structures. We can divide up to 2 types in this category.

  1. Infinite loops
  2. Finite loops
Let us first discuss about the 3 looping structures.

For loop

The syntax of the for loop is as follows:
for(startingIndex; condition; increment) //you can either use increment or decrement
{
    //codes to loop
}
Example for a finite loop:
for(int i=0; i<5;i++)
{
    System.out.println("This will print 5 times");
}
Example for a infinite loop:

for(int i=0;true;i++)
{
    System.out.println("Thisis i: "+i);
}

The code I have illustrated in the example executes like this. First when the interpreter comes into the for loop, it checks what the starting index variable and keeps them in a memory location. Then it checks the condition, if the condition returns a TRUE value, interpreter moves on to the code block surrounding with the curly brackets. After it has been executed, the interpreter goes to the increment or decrement part of the loop and executes it. Then the next step for the interpreter is to check the condition, if it returns a TRUE value, it goes on to the code block to loop...



There are two more looping structures, which I will explain in the next article. Enjoy and practice the for loop before you read the next :)

Resources: 
Images: 

No comments:

Post a Comment

Its all about friendly scientific conversation here at One Science Fact. I'd love to hear your thoughts about this blog.

Be sure to check back again because i always reply to every single comment