Array concatenation program in C


Advertisements

To concate two arrays, we need at least three array variables. We shall take two arrays and then based on some constraint, will copy their content into one single array. Here in this example, we shall take two arrays one will hold even values and another will hold odd values and we shall concate to get one array.

Algorithm

Let's first see what should be the step-by-step procedure of this program −

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

Pseudocode

Let's now see the pseudocode of this algorithm −

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

Implementation

The implementation of the above derived pseudocode is as follows −

#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;
}

The output should look like this −

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
Advertisements