Monday, March 30, 2009

How to create a For Loop In JavaScript?

1- A basic While Loop.
The Basic While Loop-First of all you just need to understand the while loop in it's most basic form, so that you'll understand how the for loop works. Lets take a look at a very basic form of the while loop:
i = 0;
while(i <= end)


First of all you'll notice the "i" variable, this will most likely be declared as an int by the way, it's basically what will keep count of the number of times the computer is supposed to go through the loop. You'll also notice the i++ inside the loop, this is what makes the "i" variable go up by one after every loop. It can then stop looping once it reaches whatever you've set the "end" variable to, which will more than likely be an int as well.

Now we'll take a look at the for loop piece by piece. The for loop itself is really just shorthand in Java for the above while loop. it's also going to have an "i" variable, so you could go ahead and declare that. It'll also have a starting value, which was zero in the while loop above, and an end value. Just make sure the starting value is smaller than the end value, and that it will eventually reach the end value. Don't want an infinite loop do you?
int i;
int begin;
int end;
3-Start, End, And Count-
Now all you have to do is to set up the for loop:
for(i = begin; i <= end; i++)

Just remember that you can set the beginning and ending values to whatever you need them to be.

No comments: