how does nested for loop work? (prime numbers)

edited April 2015 in How To...
for(){ 
    for(){}  
       }

Answers

  • edited April 2015

    This question doesn't make a ton of sense. What do you mean how does it work?

    A for loop is simply a way to do something multiple times. For example, you could do this:

    void printLoop(int times){
        for(int i = 0; i < times; i++){
           println(times);
        }
    }
    

    That function takes an integer parameter and uses a for loop to print that number, that many times. So if you pass 3 in, you'll print 3 out 3 times.

    We could then create another function that calls this function:

       void printMoreLoops(){
          for(int j = 0; j < 10; j++){
             printLoop(j);
          }
       }
    

    That function now uses a for loop to call our first function. So we'll print out 0 zeroes, 1 ones, 2 twos, 3 threes, etc. All we're doing is doing something 10 times, and that something in this case is calling the printLoop() function.

    But that doing something could also be calling another for loop. So we can call a for loop multiple times by putting it inside another for loop. We can rewrite our little program by doing this:

       void printMoreLoops(){
          for(int j = 0; j < 10; j++){
             for(int i = 0; i < j; i++){
               println(j);
            }
          }
       }
    
  • do you know how to find prime numbers using for loops?

  • It's easy to find all the prime numbers between 2 and N! First, look at each number between 2 and N (including 2 and N). For each number that you look at, see if the numbers between 1 and N-1 will divide equally into it. If one does, you know the number you're looking at is not a prime! If none do, you know that it is!

    This process translates fairly easily into code. Try it for yourself and post the resulting code if you want more help.

Sign In or Register to comment.