eHow launches Android app: Get the best of eHow on the go.

How To

How to Write a For Loop

Member
By takezo
User-Submitted Article
(5 Ratings)
Write a For Loop
Write a For Loop
http://course.cs.ust.hk

The for loop is one of the most important constructs in programming. Learn the basics of this easy to use, but powerful tool.

Difficulty: Moderately Easy
Instructions
  1. Step 1

    Identify the components of your for loop. There are three components. The before step, the conditional and the iterator. Consider how we might convert the following loop to a for loop:

    int i=0;
    while (i < 10)
    {
    ...
    i++;
    }

  2. Step 2

    The before step. This is the step that only happens once, before you start running the loop. Typically this initializes some counter variable that will keep track of how many times you've gone through the loop. In our case, that's:

    int i=0;

  3. Step 3

    The conditional. Everytime you run through the loop, check to make sure this conditional is true. If it's not, then the loop stops running. In our case, that's:

    i < 10

  4. Step 4

    The iterator. This is the last step of your typical loop. It's something that runs everytime you go through the loop. The key thing to remember is, it should slowly bring you closer to a case where the conditional isn't true. In our case, that's:

    i++;

  5. Step 5

    Now put it in the right syntax:

    for(before-step; conditional; iterator)
    {
    ....
    }

    In our case, we get:

    for(int i=0; i<10; i++)
    {
    ....
    }

Tips & Warnings
  • Although for loops appear in almost all modern programming languages, the syntax used here is primarily for Java, C, C++ and C#. It probably works in many other languages too.

Comments  

analee said

Flag This Comment

on 2/1/2009 Thanks for the instructions on how to write for loop.

Flag This Comment

on 1/30/2009 This is a really nice explanation of the for loop. Well written article. Giving it 5* for being both simple and informational.

sharishops said

Flag This Comment

on 1/3/2009 You make it sound very easy!

Anai said

Flag This Comment

on 12/28/2008 I don't understand technical stuff very well, but it sounds informative, thanks.

Flag This Comment

on 12/27/2008 Neato. I need to try this out sometime. I get too lazy after working all week. 5*s

Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Computers Newsletters

Copyright © 1999-2010 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. † requires javascript

eHow Computers
eHow_eHow Technology and Electronics