如何编写没有循环的代码? (暂无)我只能使用递归。
您可以创建另一个递归函数来打印\t
:
void print_rec (int i){
if(i > 0) {
printf("\t");
print_rec(i-1);
} else {
return;
}
}
然后在您的函数中:
// replace for loop by print_rec function
print_rec(depth);
我不希望您避免使用用于创建缩进的循环,但实际上可以将其替换为递归。
您可以通过打印一个标签然后打印depth
标签来打印depth-1
标签。
void print_indent(unsigned i) {
if (!i)
return;
printf("\t");
print_indent(i-1);
}
print_indent(depth);
实际上,任何循环都可以用递归代替。
我们知道我们可以通过循环消除tail call recursion。通过相反的过程,我们知道
while (cond()) {
body();
}
可以写为
void recursive_loop() {
if (!cond())
return;
body();
recursive_loop();
)
我们也知道
for (init(); cond(); post()) {
body();
}
只是另一种书写方式
init();
while (cond()) {
body();
post();
}
so
for (int i=0; i<depth; ++i) {
printf("\t");
}
可以写为
void print_indent(int depth, int i) {
if (i >= depth) {
return;
printf("\t");
++i;
print_indent(depth, i);
}
int i = 0;
print_indent(depth, i);