[英]How do I print two arrays using recursion, one after another (i.e. not concurrently)?
My code is posted as follows and currently prints out "1,6,2,7,3,8,4,9,5,10,DONE", in other words, it goes through and prints out the first arrays first element then the second arrays first element then the first arrays second and the second arrays second and so on and so forth (sorry for the run on sentence). 我的代码发布如下,目前打印出“1,6,2,7,3,8,4,9,5,10,DONE”,换句话说,它通过并打印出第一个数组的第一个元素然后第二个数组第一个元素然后第一个数组第二个,第二个数组第二个,依此类推等等(抱歉句子上的运行)。 I want an output of "1,2,3,4,5,6,7,8,9,10,DONE" so that the first array is completely printed, then the second array is too, then DONE is printed. 我想输出“1,2,3,4,5,6,7,8,9,10,DONE”以便第一个数组完全打印,然后第二个数组也是,然后打印DONE。 PLEASE KEEP RECURSION IN THIS FUNCTION (I'm trying to understand the fundamentals of recursively calling a function): 请保持这个功能的回归(我试图理解递归调用函数的基本原理):
#include <stdio.h>
#define N 5
void printcombo(int* a, int* b)
{
int first,second;
first = *a;
second = *b;
if (first != 0 && second !=0)
{
printf("%d,",first);
printf("%d,",second);
printcombo(a+1,b+1);
}
else
{
printf("DONE\n");
}
}
int main()
{
int a[N] = {1,2,3,4,5};
int b[N] = {6,7,8,9,10};
printcombo(a,b);
return 0;
}
I would appreciate it if only a small bit of the code was changed, but obviously do what you gotta do. 如果只改变了一小部分代码,我会很感激,但显然要做你必须做的事情。
Here's one variant: 这是一个变种:
#include <stdio.h>
#define N 6
void printcombo(int* a, int* b)
{
int first,second;
first = *a;
second = *b;
if (first != 0) {
printf("%d ", first);
printcombo(a+1,b);
} else if (second != 0) {
printf("%d ", second);
printcombo(a,b+1);
} else {
printf("DONE\n");
}
}
int main()
{
int a[N] = {1,2,3,4,5,0};
int b[N] = {6,7,8,9,10,0};
printcombo(a,b);
return 0;
}
Can you simply have two separate invocations of your recursive function? 你能简单地对你的递归函数进行两次单独的调用吗?
(I've also added zeros to the end of the arrays, since if you're checking for it you ought to put it there. It's bad form to assume.) (我还在数组的末尾添加了零,因为如果你要检查它,你应该把它放在那里。这是不好的形式。)
#include <stdio.h>
#define N 6
void printarray(int* n)
{
int number;
number = *n;
if (number != 0)
{
printf("%d,",number);
printcombo(n+1);
}
}
int main()
{
int a[N] = {1,2,3,4,5,0};
int b[N] = {6,7,8,9,10,0};
printarray(a);
printarray(b);
printf("DONE\n");
return 0;
}
#include <stdio.h>
#define N 5
void printcombo(int* a, int* b){
int first,second;
first = *a;
second = *b;
if(first == 0 && second == 0){
printf("DONE\n");
return ;
}
if (first != 0 && second !=0){
if(first < second){
printf("%d,",first);
++a;
} else {
printf("%d,",second);
++b;
}
} else if (first != 0 && second == 0){
printf("%d,",first);
++a;
} else if (first == 0 && second != 0){
printf("%d,",second);
++b ;
}
printcombo(a, b);
}
int main(){
int a[N+1] = {1,2,3,4,5, 0};//last element is 0 and sorted
int b[N+1] = {6,7,8,9,10, 0};
printcombo(a,b);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.