程序将一个数组分成两个数组(Program to divide one array into two arrays)

优质
小牛编辑
133浏览
2023-12-01

要将数组分成两部分,我们至少需要三个数组变量。 我们将采用具有连续数字的数组,然后将其值基于偶数和奇数值存储到两个不同的变量中。

算法 (Algorithm)

让我们首先看看该程序的逐步程序应该是什么 -

START
   Step 1 → Take three array variables A, E, and O
   Step 2 → Store continuous values in A
   Step 3 → Loop for each value of A  
   Step 4 → If A[n] is <i>even</i> then store in E array
   Step 5 → If A[n] is <i>odd</i> then store in E array
STOP

伪代码 (Pseudocode)

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

procedure divide_array(A)
   FOR EACH value in A DO
      IF A[n] is even
         save in E
      ELSE
         save in O
      END IF
   END FOR
end procedure

实现 (Implementation)

上述派生伪代码的实现如下 -

#include <stdio.h>
int main() {
   int array[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
   int even[10], odd[10];
   int loop, e, d;
   e = d = 0;
   for(loop = 0; loop < 10; loop++) {
      if(array[loop]%2 == 0) {
         even[e] = array[loop];
         e++;
      } else {
         odd[d] = array[loop];
         d++;
      }
   }
   printf(" original -> ");
   for(loop = 0; loop < 10; loop++)
      printf(" %d", array[loop]);
   printf("\n even -> ");
   for(loop = 0; loop < e; loop++)
      printf(" %d", even[loop]);   
   printf("\n odd -> ");
   for(loop = 0; loop < d; loop++)
      printf(" %d", odd[loop]);   
   return 0;
}

输出应该是这样的 -

 original ->  0 1 2 3 4 5 6 7 8 9
 even ->  0 2 4 6 8
 odd ->  1 3 5 7 9