简体   繁体   中英

How to implement nested loops with the depth of n?

The following code shows what I want to achieve. How can I generalize this principle for any value of n to generate nested loops of the same depth? Or is there a better solution?

For n = 2 :

for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
    }
}

For n = 3 :

for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
        for(k=0;k<n;k++)
        {
        }
    }
}

The way that i answered this question is; suppose we want n nested loops that is supposed to run from 1 to 10, this is how it would look

void nLoop(int n)
{
     if(n<=0)
         return;
     for(int i=1;i<=10;i++)
     {
           nLoop(n-1);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM