将迭代算法转换为递归算法

标签 c algorithm recursion

我编写了以下程序:

#include <stdio.h>

void printValue();

int main (){
   int n = 100;
   int i;
   for (i=0; i<n; i+=1)
          printValue();
}


void printValue(){
     static unsigned int y = 0;
     printf("y = %d", y);
     y+=1;
}

如何重写算法以使其递归?

最佳答案

#include <stdio.h>

void printValue(void);
void times(int n, void (*func)(void)){
    if(n>0){
        func();
        times(--n, func);
    }
}

int main (void){
    int n = 100;
    times(n, printValue);
    return 0;
}

void printValue(void){
    static unsigned int y = 0;
    printf("y = %d\n", y);
    y+=1;
}
<小时/>
#include <stdio.h>

void printValue(int);
void repeat_upto(int init_value, int end_value, int incremental,
                 void (*func)(int)){
    if(incremental < 0 ? init_value >= end_value : init_value <= end_value){
        func(init_value);
        repeat_upto(init_value + incremental, end_value, incremental, func);
    }
}

int main (void){
    repeat_upto(0, 100-1, +1, printValue);
    return 0;
}

void printValue(int v){
    printf("%d\n", v);
}
<小时/>
#include <stdio.h>

void printValue(int v, int end_value){
    if(v < end_value){
        printf("%d\n", v);
        printValue(v+1, end_value);
    }
}

int main (void){
    printValue(0, 100);
    return 0;
}

关于将迭代算法转换为递归算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27892071/

相关文章:

php删除特定文件夹及其所有内容

c - 验证可变长度参数

python - 从距原点给定距离的图中查找路径的所有组合

java - 对于 2 个数字,如何测试一个是否是另一个的整数幂?

mysql - 带循环计数器的递归查询

java - 递归查找字符串中指定字符出现的次数

c - 访问二维数组时出现段错误

c - 使用字符串和 Malloc/Realoc

c - 寻找邻居的扫雷算法?

php - 使用 python 或 php 处理音频文件