Jump to content

bad nested loop strucure

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
yellowzelo

yellowzelo

    Newbie

  • Members
  • PipPip
  • 18 posts
Hi,

I have a code with n nested loops. Every loop has X iterations.
Is it possible to make this code into some structure that would do the same job for any particular integers n, x?

I think, this could be done somehow with recursion. If yes, is it possible to make it without recursion as well? Could you please, post that code or post some link(s)?

        for (int i_1=0; i_1<X; i_1++){ //first loop
            for (int i_2=0; i_2<X; i_2++){ //second loop
                ...
                for (int i_n=0; i_n<X; i_n++){ //n-th loop
                    print(i+ " "  + i_2 +" "..." "+i_n);
                }
                ...
            }
        }
Thank you.

#2
cdg10620

cdg10620

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 389 posts
If you are using the number of loops as a variable what you can do is call the loop based upon the number of iterations that you desire. I think it would be something like this:


// number of iterations is going to equal i
for( int x = 0; x < i; x++ )
{
   CallFunciton();
}

public void CallFunction()
{
   do work
}


Or you can use recursion in a while loop. I hope this helps. If not can you give me more information? I guess i'm not really understanding why you would have n nested loops.
-CDG10620
Software Developer

#3
yellowzelo

yellowzelo

    Newbie

  • Members
  • PipPip
  • 18 posts
That wouldn't work, because code inside the loops is not always the same. It depends on n.

eg. if n=5: print(i+" "+i_2+" "+i_3+" "+i_4+" "+i_5);

#4
cdg10620

cdg10620

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 389 posts
Then you would need to add an if statement in the function to tell it to do a certain block of code depending on the value of N or it would call another function based on that number.
-CDG10620
Software Developer

#5
yellowzelo

yellowzelo

    Newbie

  • Members
  • PipPip
  • 18 posts
The program should work for any particular integer (viz. my 1. post). That would mean I needed if statement for every possible value of N...

#6
yellowzelo

yellowzelo

    Newbie

  • Members
  • PipPip
  • 18 posts
This is what I was looking for (code is in Java):

        int n=3, x=10;
        byte[] digit=new byte[n];

        while (digit[n-1]<x) {

            printArray(digit);
            digit[0]++;

            for (int j=0; j<n-1; j++){
                if (digit[j]<x) break;

                    digit[j]=0;
                    digit[j+1]++;
            }
        }
If someone knows a faster solution, please share. Thanks