如何将一个向后打印数组的程序变成一个向后打印第N个字符的程序?

时间:2019-02-13 05:25:11

标签: c++ arrays recursion

我在将该程序转换为递归程序时遇到麻烦。我的函数还必须写出作为参数提供的数组的第N个字符。

我也将N约束为1 <= N <= 3。

如果有人要解释为什么我的教授将 “ cout <<结尾;”也一样 谢谢。

 #include <iostream>
 #include <cstring> 
 namespace std;


 // print an array backwards, where 'first' is the first index
 // of the array, and 'last' is the last index 
 void writeArrayNthBackward(const char anArray[], int first, int last, int n) {
  int i = 0;
  for (i = last; i >= first; i--) {
    std::cout << anArray[i];
  }
  std::cout << std::endl;
}

// test driver
int main() {
  const char *s = "abc123";
  writeArrayNthBackward(s, 0, strlen(s) - 1, 1 <= n <= 3);
}

2 个答案:

答案 0 :(得分:0)

这似乎不是打印数组第n个元素的非常聪明的方法,因为您可以直接访问它。

但是,如果您要这样做,那么最好的方法是编写另一个函数,通过添加一个跟踪当前索引的附加参数来帮助主函数。将您最初传入的第n个值用作基本情况,然后递归直到达到基本情况。从数组的背面开始并测试您的代码,以确保您进行了所有正确的检查。

std :: cout << std :: endl用于打印新行。

答案 1 :(得分:0)

首先,您的代码看起来不正确,我认为正确的代码是:

#include <iostream>
#include <cstring> 
 namespace std;


 // print an array backwards, where 'first' is the first index
 // of the array, and 'last' is the last index 
 void writeArrayNthBackward(const char anArray[], int first, int last, int n) {
  for (int i = last; i >= first; i--) {
    std::cout << anArray[i];
  }
  std::cout << std::endl;
}

// test driver
int main() {
  const char *s = "abc123";
  writeArrayNthBackward(s, 0, strlen(s) - 1, 1 <= n <= 3);
}

如果要使其递归,可以使用以下代码:

#include <iostream>
 #include <cstring> 
 namespace std;


 // print an array backwards, where 'first' is the first index
 // of the array, and 'last' is the last index 
 void writeArrayNthBackwardRec(const char anArray[], int index, int n) {
  if (index == n) {
    std::cout << anArray[index];
  }
  std::cout << std::endl;
  if (index != 0) {
     writeArrayNthBackwardRec(anArray, --index, n);
  }
}

// test driver
int main() {
  const char *s = "abc123";
  if (n >= 1 && n <= 3) {
     writeArrayNthBackwardRec(s, strlen(s) - 1);
  }
}
相关问题