C 语言数组拼接程序



要连接两个数组,我们需要至少三个数组变量。我们将取两个数组,然后根据某些约束条件,将它们的内容复制到一个数组中。在此示例中,我们将取两个数组,一个将保存偶数,另一个将保存奇数,然后连接以得到一个数组。

算法

让我们首先看看此程序的分步过程 -

START
   Step 1 → Take three array variables A, E, and O
   Step 2 → Store even values in array E
   Step 3 → Store odd values in array O
   Step 4 → Start loop from 0 to sizeof(E)
   Step 5 → Copy E[n] to A[index]
   Step 6 → Start loop from 0 to sizeof(O)
   Step 7 → Copy E[n] to A[index]
   Step 8 → Display A
STOP

伪代码

让我们现在看看此算法的伪代码 -

procedure concate_array(A)

   Array E, O
   index ← 0
   FOR EACH value in E DO
      A[index] ← E[n]
      INCREMENT index
   END FOR
   
   FOR EACH value in O DO
      A[index] ← O[n]
      INCREMENT index
   END FOR
   DISPLAY A

end procedure

实现

以上推导出的伪代码实现如下 -

#include <stdio.h>

int main() {
   int array[10];
   int even[5] = {0, 2, 4, 6, 8};
   int odd[5]  = {1, 3, 5, 7, 9};
   
   int loop, index, e_len, o_len;
   
   e_len = o_len = 5;
   
   index = 0;
 
   for(loop = 0; loop < e_len; loop++) {
      array[index] = even[loop];
      index++;
   }
 
   for(loop = 0; loop < o_len; loop++) {
      array[index] = odd[loop];
      index++;
   }

   printf("\nEven -> ");
   
   for(loop = 0; loop < e_len; loop++)
      printf(" %d", even[loop]);
   
   printf("\nOdd  -> ");
   
   for(loop = 0; loop < o_len; loop++)
      printf(" %d", odd[loop]);

   printf("\nConcat -> ");
   
   for(loop = 0; loop < 10; loop++)
      printf(" %d", array[loop]);

   return 0;
}

输出应如下所示 -

Even ->  0 2 4 6 8
Odd  ->  1 3 5 7 9
Concat ->  0 2 4 6 8 1 3 5 7 9
array_examples_in_c.htm
广告