Advertise Here

Author Topic: A better understanding of for loops  (Read 5200 times)

0 Members and 1 Guest are viewing this topic.

Offline slayer766

  • SMF For Free Full Member
  • *
  • Posts: 212
    • View Profile

  • Total Badges: 13
    Badges: (View All)
    Topic Starter Combination Level 3 Level 2 Level 1
A better understanding of for loops
« on: February 04, 2008, 07:30:12 pm »
For loops basically loop through something you specify and will execute forever until you either input a break, an if condition, or simply tell the loop to end at a certain number. Here are some examples of the three I said:

Example 1: Breaking a for loop with break.

Breaks can be used in functions, loops, etc. I will show you how to use the break in a for loop.
Code: [Select]
<script type="text/javascript">
for(i = 0; i < 5; i++){
document.write(i);
break;
}
</script>

That will basically stop the loop at 0, because it breaks the code after it writes 0. Breaks are quite effective to haulting something.


Example 2: Stopping a for loop with an if condition.

An if condition will just basically stop the loop once it reaches X amount.
Code: [Select]
<script type="text/javascript">
for(i = 0; i < 5; i++){
if(i == 3){
document.write(i);
}
}
</script>

That will count all the way up to 3 and then write the number 3 and go no further than that.


Example 3: Completeing a for loop with a specified number
Code: [Select]
<script type="text/javascript">
for(i = 0; i < 5; i++){
document.write(i);
}
</script>
It's as simple as that. The loop will count up to 5, which it will become 4 because the loop started on 0.

 

Related Topics

  Subject / Started by Replies Last post
0 Replies
3399 Views
Last post February 04, 2008, 07:31:27 pm
by slayer766
0 Replies
765 Views
Last post March 22, 2008, 05:55:24 pm
by dosanjh5
5 Replies
2550 Views
Last post January 29, 2009, 03:31:28 pm
by taogem
4 Replies
2293 Views
Last post June 05, 2014, 07:45:32 am
by SMF For Free