【问题标题】:How to convert nested for loops into a recursive function? [closed]如何将嵌套的for循环转换为递归函数? [关闭]
【发布时间】:2013-01-04 16:57:39
【问题描述】:
for(a[9]=0;a[9]<16;a[9]++)

for(a[8]=0;a[8]<16;a[8]++)

for(a[7]=0;a[7]<16;a[7]++)

for(a[6]=0;a[6]<16;a[6]++)

for(a[5]=0;a[5]<16;a[5]++)

for(a[4]=0;a[4]<16;a[4]++)

for(a[3]=0;a[3]<16;a[3]++)

for(a[2]=0;a[2]<16;a[2]++)

for(a[1]=0;a[1]<16;a[1]++)

for(a[0]=0;a[0]<16;a[0]++)

i++;

【问题讨论】:

  • 你到底想用这么深的嵌套循环来达到什么目的???

标签: c recursion for-loop


【解决方案1】:

以下逻辑将帮助您将嵌套的 for 循环转换为递归函数。但是不要在代码中不必要地添加太多嵌套的for 循环。即使在编写小程序时也需要考虑性能。

int i = 0; //make it as global variable
...
void func(int a[], int index)
{
   for (a[index] = 0; a[index] < 16; a[index]++)
   {
       if (index != 0)
       {
           func(a, (index - 1));
       }
       else
       {
           i++;
       }
   }
}

【讨论】:

    猜你喜欢
    • 2019-04-14
    • 1970-01-01
    • 2013-11-29
    • 2013-05-31
    • 1970-01-01
    • 2021-09-16
    • 2019-05-30
    • 1970-01-01
    相关资源
    最近更新 更多