Sunday, July 15, 2012

For Loop in Java

Loops are the iterations. That means we can repeat the code for several number of times using loop. But we can write the same code ten times and it will run ten times. Yeah we can do this but this make our code more lengthy, so isn't that good that we write the code once and run it hundred or thousands of times. It saves out time and effort and makes our code smart. So lets see an example

public class ForLoopTest {

public static void main(String[] Args)
{
int counter = 0;
for(counter = 0; counter < 5; counter++)
{
System.out.println("Value of the counter is " + counter);
}
}
}

so friends here we have a variable counter. As its name indicates that it will count our iterations. Initially this counter is set to zero. In for loop we have again initialized the counter to zero. next we have a check statement or check point. That will ensure that the loop runs exactly number of times that we want. So we have set this limit to 5. In the next step we have incremented the counter variable by one using ++. Now every time when loop will run counter will be incremented by one and on reaching a certain limit(in our case 5), the loop will stop.
Here is an important point to remember that this loop will run 5 times. We have set the limit less than 5 but initially was 0. So it run from 0,1,2,3,4 (five times). Here is the output of the code

Value of the counter is 0
Value of the counter is 1
Value of the counter is 2
Value of the counter is 3
Value of the counter is 4

So guys this was out new lesson. Stay tuned to our blog and get new tutorials daily.

No comments:

Post a Comment