C 编程 - 递归的两个 for 循环 [英] C Programming - Two for loops to recursion

查看:54
本文介绍了C 编程 - 递归的两个 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个可以模拟两个 for 循环的递归函数.所以,函数必须这样做:

I was trying to make recursive function that would simulate two for loops. So, function would have to do this:

int recursion(int n, int i, int j)
{
    for(i=0; i<n; i++)
    {
        for(j=i+1; j<n; j++)
        {
            printf("%d %d\n", i, j);
        }
    }
}

但是,我希望它是递归的.我试过类似的东西:

but, i want it to be recursive. I tried something like:

int recursion(int n, int i, int j)
{
    if(i<n)
    {
        if(j<n)
        {
            printf("%d %d\n", i, j);
            recursion(n, i+1, j+1);
        }
        recursion(n, i+1, i+1+1);
    }
}

我会在 main 中调用递归,就像

I would call recursive one in main like

recursion(10, 0, 1);

但是这两个版本的函数的输出不同.谁能告诉我我在哪里与递归错误?

but output is not the same for those two version of function. May anyone tell me where am I mistaking with the recursive one?

推荐答案

为了模拟嵌套的 for 循环,你应该只为每次递归调用增加一个计数器变量,这取决于你是否在"内循环或外循环.此外,外循环调用需要将内循环计数器重置为零.

For simulating nested for loops, you should only increment one of your counter variables for each recursive call, depending on whether you're "in" the inner or outer loop. Also, the outer loop calls need to reset the inner loop counter to zero.

/* i for outer loop, j for inner loop, both going 0 to n-1 */
void recursion(int n, int i, int j)
{
  if (i < n) {
    if (j < n) {
      // inner loop when j < n
      printf("i=%d, j=%d\n",i,j); // inner loop body
      recursion(n, i, j+1); // increment inner counter only!
    } else { // when j has reached n...
      // outer loop, which restarts inner loop
      recursion(n, i+1, 0); // increment outer counter, reset inner
                            // since we're starting a new inner loop
    }
  }
}

如果最初调用为 recursion(N, 0, 0) 这应该大致相当于:

If called initially as recursion(N, 0, 0) this should be roughly equivalent to:

for (i = 0; i < N; i++) {
  for (j = 0; j < N; j++) {
    printf("i=%d, j=%d\n", i, j);
  }
}

...除了它不考虑在内循环中对 i 的修改(在这些示例中没有发生,但如果内循环确实设置了 i大于 N,递归版本会在没有先完成内部循环的情况下中断两个循环).

...except that it doesn't account for modifications of i within the inner loop (none happen in these examples, but if the inner loop did set i larger than N, the recursive version would break both loops without finishing the inner loop first).

这篇关于C 编程 - 递归的两个 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆