将数组分成几个部分的程序



要将数组分成两部分,我们需要至少三个数组变量。我们将取一个包含连续数字的数组,然后根据偶数和奇数值将其存储到两个不同的变量中。

算法

让我们首先了解此程序的分步流程 −

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 even then store in E array
   Step 5 → If A[n] is odd then store in E array
STOP

伪代码

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

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

实现

所得伪代码的实现如下 −

#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
array_examples_in_c.htm
广告