在 C 中反向複製陣列的程式



本程式將幫助你瞭解陣列的基本原理之一。我們將在反向複製一個數組到另一個數組。

演算法

讓我們首先了解該程式分步執行的過程 -

START
   Step 1 → Take two arrays A, B
   Step 2 → Store values in A
   Step 3 → Set count to sizeof(A)
   Step 4 → Loop for each value of A
   Step 5 → Copy A[loop] to B[count]
   Step 6 → Decrement count
   Step 7 → Display B
STOP

虛擬碼

現在我們來看該演算法的虛擬碼 -

procedure reversecopy_array(A, B)

   SET index to 1
   Set count to sizeof(A)
   FOR EACH value in A DO
      B[count] = A[index]
      INCREMENT index
      DECREMENT count
   END FOR
   DISPLAY B
   
end procedure

實現

以上虛擬碼的實現如下 -

#include <stdio.h>

int main() {
   int original[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
   int copied[10];
   int loop, count;
   
   count = 9;
   
   for(loop = 0; loop < 10; loop++) {
      copied[count] = original[loop];
      count--;
   }
      
   printf("original -> copied \n");
   
   for(loop = 0; loop < 10; loop++) {
      printf("   %2d        %2d\n", original[loop], copied[loop]);
   }

   return 0;
}

輸出應如下所示 -

original -> copied
    1         0
    2         9
    3         8
    4         7
    5         6
    6         5
    7         4
    8         3
    9         2
    0         1
array_examples_in_c.htm
廣告
© . All rights reserved.