如何使用递归打印两个数组,一个接一个(即不同时)?

时间:2013-11-28 23:21:56

标签: c arrays recursion

我的代码发布如下,目前打印出“1,6,2,7,3,8,4,9,5,10,DONE”,换句话说,它通过并打印出第一个数组第一个元素然后第二个数组第一个元素然后第一个数组第二个,第二个数组第二个,依此类推等等(抱歉句子上运行)。我想输出“1,2,3,4,5,6,7,8,9,10,DONE”以便第一个数组完全打印,然后第二个数组也是,然后打印DONE。 请保持这个功能的回归(我试图理解递归调用函数的基本原理):

#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;
}

如果只改变了一小部分代码,我会很感激,但显然要做你要做的事。

3 个答案:

答案 0 :(得分:2)

这是一个变体:

#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;
}

答案 1 :(得分:0)

你能简单地对你的递归函数进行两次单独的调用吗?

(我还在数组的末尾添加了零,因为如果你正在检查它,你应该把它放在那里。假设这是不好的形式。)

#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;
}

答案 2 :(得分: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;
}