循环中的递归 [英] Recursion inside for loop

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

问题描述

任何人都可以解释一下这段代码中发生了什么,以及当它离开for循环时有多么有趣(x-1)在for循环中工作,即使循环没有结束它会造成巨大的混乱。



我的尝试:



 #include< stdio .H> 
int main()
{
int n,i;
printf(输入n \ n);
scanf(%d,& n);
fun(n);
}
int fun(int x)
{int i;
char c ='*';
printf(\ n);
if(x> = 1){
for(i = 1; i< = x; i ++)
printf(%c,fun(x-1));
}
其他
返回c;
}

解决方案

我已经在你这个问题的原始帖子中解释了这个。


< blockquote> 中的递归没什么特别的(但是增长非常大)。但是, printf 语句大多数时候都会输出垃圾,因为虽然 x> 0 但是没有返回语句执行 fun 函数。


can anyone please explain what here going on in this code and how fun(x-1)is working inside for loop when it is going out of for loop evenwhen for loop is not ended its creating huge confusion.

What I have tried:

#include<stdio.h>
int main()
{
    int n,i;
    printf("enter n\n");
    scanf("%d",&n);
    fun(n);
}
int fun(int x)
{int i;
char c='*';
printf("\n");
    if(x>=1){
    for(i=1;i<=x;i++)
    printf("%c",fun(x-1));
    }
    else 
    return c;
}

解决方案

I already explained this in your original post of this question.


Recursion inside a for as nothing special (but a very big growth). However, the printf statements most of the times will output garbage, because while x>0 no return statement is executed in the fun function.


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

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