將數組A中的內容和數組B中的內容進行交換。

1、解決方案

設計一個循環,對兩個數組同時依次遍歷,每變一次都執行交換操作,這樣遍歷結束就完成了數組的交換。


2、具體的交換方法的實現

void exchangeArray(int max, int* a, int* b)//exchange the two same size arrays, num is the size
{
    //交換的實現
    int temp = 0;
    for(int i = 0; i < max; i++)
    {
        temp = *(a + i);
        *(a + i) = *(b+i);
        *(b + i) = temp;
    }

	//展示交換後的結果
    printf("交換後數組a:");
    for(int i = 0; i < max; i++)
    {
        
        printf("%d\t", *(a + i));   
    } 
    printf("\n");
    
    printf("交換後數組b:");
    for(int i = 0; i < max; i++)
    {
        
        printf("%d\t", *(b + i));
    } 
    printf("\n");
}

3、測試

void exchangeArray(int max, int* a, int* b)//exchange the two same size arrays, num is the size
{
    
    int temp;
    for(int i = 0; i < max; i++)
    {
        temp = *(a + i);
        *(a + i) = *(b+i);
        *(b + i) = temp;
    }

	//展示交換後的結果
    printf("交換後數組a:");
    for(int i = 0; i < max; i++)
    {
        
        printf("%d\t", *(a + i));   
    } 
    printf("\n");
    
    printf("交換後數組b:");
    for(int i = 0; i < max; i++)
    {
        
        printf("%d\t", *(b + i));
    } 
    printf("\n");
}


int main()
{
    int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    int b[10] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};

    printf("交換前數組a:");
    for(int i = 0; i < 10; i++)
    {
        
        printf("%d\t", *(a + i));   
    } 
    printf("\n");
    
    printf("交換前數組b:");
    for(int i = 0; i < 10; i++)
    {
        
        printf("%d\t", *(b + i));
    } 
    printf("\n\n");

    exchangeArray(10, a, b);
    
    printf("\n");
    system("pause");
    return 0;
}

結果爲:
在這裏插入圖片描述