c - 递归 C 函数 - 打印升序

标签 c loops recursion

我正在尝试实现一个递归调用自身并按升序打印给定数字的代码,即如果数字为 5,则该函数将打印 1 2 3 4 5。我不能以任何方式使用循环!

void print_ascending(int n)
{
   int i = 1;

   if(i < n)
   {
      printf("%d", i);

      i++;

      print_ascending(n);
   }
}

当然,这段代码的问题是它每次都会将变量 i 重新初始化为 1,并无限循环打印 1。

也不允许外部全局变量或外部函数!

最佳答案

每次调用递归函数时,尝试递增参数值。

void print_ascending(int limit, int current_value)
{
   if(current_value < limt)
   {
     printf("%d ", current_value);
     print_ascending(limit, current_value + 1);
   }
}

最初将函数调用为 print_ascending(5, 1)

或者,

void print_ascending(int n)
{
    if(n > 0)
    {
        print_ascending( n - 1);
        printf("%d ", n); 
    }
}

关于c - 递归 C 函数 - 打印升序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29069915/

相关文章:

C 全局变量和局部变量

c - 是否有等效于倒带功能的功能,但仅适用于一个 token ?

php - 递归获取树的所有 parent 和 child

c - 快速排序字符数组(字符串)C编程

c - 为什么这个函数在无限循环中运行?

c++ - 使用一个数组以相反的顺序制作另一个数组

c++ - 二叉搜索树析构函数

perl - 从 DAG 中提取树

c++ - ARM 海湾合作委员会 : Conflicting CPU architectures

PHP mySQL 在大量插入语句上出现性能问题,我应该使用其他方法吗?