Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

FOR loop and array help

  1. Dec 4, 2004 #1
    Does anyone know of a site that has some problem solving using FOR loops and or Arrays?
  2. jcsd
  3. Dec 4, 2004 #2

    Dr Transport

    User Avatar
    Science Advisor
    Gold Member

    What language?????
  4. Dec 4, 2004 #3
    I'm Looking For Something That Is Not Language Specific, But If I Had To Choose A Language Visual Basic Would Be The One. Thx
  5. Dec 4, 2004 #4


    User Avatar
    Staff Emeritus

    A for statement does three things:

    Assign a starting value to a counter variable
    Increments the counter variable by a specified amount
    Checks to see if the expression which makes the loop continue holds true

    For example in C++:

    for( int x = 0; x < 5 ; x++) { some code}

    When the computer first enters the for loop the first thing it does is set x to the value 0. Then it checks the condition to see if it should enter the loop. Since x which is equal to 0 is in fact less than 5 it executes some code. When it finishes it increments x by 1 and then checks to see if the condition still holds. If it does it executes some code, increments x by 1 and checks to see if the condition still holds. This basic sequence happens over and over again until the condition is false, at which point it leaves the for loop.
  6. Dec 5, 2004 #5
    In Visual Basic, the syntax is a bit different.

    DIM A(10)

    gives you eleven variables to play with, called A(0), A(1), ... A(10)

    the FOR statement works like this:

    FOR J = 1 TO 10

    ... do some stuff ...


    this makes J take the value 1 for the first pass through the loop, 2 for the second and so on up to 10 the last time through.

    To make the values of A() be the seven times table, you could do something like:

    DIM A(12)

    FOR J = 1 to 12

    A(J) = 7 * J


    If you want the loop variable to go in steps other than 1 you add a step clause:

    FOR J = 0 to 20 STEP 2

    ' this loop will print 0, 2, 4, 6, ... 18, 20

Share this great discussion with others via Reddit, Google+, Twitter, or Facebook