You are here:

C/Merging char-arrays

Advertisement


Question
Dear Sir/ Madam,
I need answer to the following program in C/C++.

You are required to write a program that takes character values in two different arrays as input from user. After getting input, make a third array and merge both these array in third array. Output array must be sorted in ascending order.

Sample Output
Enter values in first array:  a h b c u v I j k e
Enter values in Second array: y u d f g k I w q a

Merged array:  a y h u b d c f g v k I j w q e
  
Sorted Array in ascending order:  a b c d e f g h I j k q u v w y


Regards
ihsan

Answer
Hello Ihsan.

The easiest way to do this is to input the two arrays, create one large array with the data of both inputs, and then sort the large array. A more complicated way is to sort each input array and then merge the two sorted arrays into a final array. Either way you get the same output, but it depends on what skill your instructor wants to see. I will give you the easier way so that there is some work left for you to do. I will present you with a simple bubble sort. Maybe you can implement a better sort. If you have any question about the code I presented, please post a follow up question.

Here is the sample output:

Put in the first array
qwertyuiop
Put in the second array
asdfghjklzxcvbnm
Merged array is 'abcdefghijklmnopqrstuvwxyz'

Here is the code:


#include <stdio.h>

// A simple bubble sort
void sort(char data[], int length)
{
   int end = length - 1;
   for (int i = 0; i < length; ++i)
   {
       for (int j = 0; j < end; ++j)
       {
           if (data[j] > data[j+1])
           {
               char tmp = data[j];
               data[j] = data[j+1];
               data[j+1] = tmp;
           }
       }
       --end;
   }
}

int main(void)
{
   char firstArray[100];
   char secondArray[100];
   char mergedArray[200];

   int i;
   int mergedIndex;

   printf("Put in the first array\n");
   fgets(firstArray, sizeof(firstArray), stdin);

   printf("Put in the second array\n");
   fgets(secondArray, sizeof(secondArray), stdin);

   // Copy the first array into the merged array
   for(i = 0; firstArray[i] != '\n'; ++i)
   {
       mergedArray[i] = firstArray[i];
   }
   mergedIndex = i;
   for(i = 0; secondArray[i] != '\n'; ++i)
   {
       mergedArray[mergedIndex++] = secondArray[i];
   }
   mergedArray[mergedIndex] = 0;

   sort(mergedArray, mergedIndex);
   printf("Merged array is '%s'\n", mergedArray);
   return 0;
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.