Write a C program to combine two arrays of the same size
arranged in order
descendant.
Test data :
Enter the number of elements to be stored in the first array:
3
Input 3 elements in the arrangement:
element [0]: 1
element [1]: 2
element [2]: 3
Enter the number of elements to be stored in the second array:
3
Input 3 elements in the arrangement:
element [0]: 1
element [1]: 2
element [2]: 3
Expected output:
The combined array in descending order is:
3 3 2 2 1 1
Please find the C code for the following:
Code:
#include <stdio.h>
int main()
{
int size1,size2,index=0;
//Prompt the user to enter the size of the first array
printf("Enter the number of elements to be stored in the first
array: ");
scanf("%d",&size1);
int array1[size1];
printf("Input %d elements in the arrangement:\n",size1);
//Read the first array elements
for(int i=0;i<size1;i++)
{
printf("element[%d]:",i);
scanf("%d",&array1[i]);
}
//Prompt the user to enter the size of the second array
printf("Enter the number of elements to be stored in the second
array: ");
scanf("%d",&size2);
int array2[size2];
printf("Input %d elements in the arrangement:\n",size2);
//Read the second array elements
for(int i=0;i<size2;i++)
{
printf("element[%d]:",i);
scanf("%d",&array2[i]);
}
//Copy both the arrays into a single array named
combinedArray
int combinedArray[size1+size2];
for(int i=0;i<size1;i++)
combinedArray[index++]=array1[i];
for(int i=0;i<size2;i++)
combinedArray[index++]=array2[i];
//Sort the array in descending order
for(int i=0;i<size1+size2;i++)
{
for(int j=i+1;j<size1+size2;j++)
{
if(combinedArray[i]<combinedArray[j])
{
int temp=combinedArray[j];
combinedArray[j]=combinedArray[i];
combinedArray[i]=temp;
}
}
}
//Print out the elements of the combinedArray in descending
order
printf("The combined array in descending order is:\n");
for(int i=0;i<size2+size1;i++)
printf("%d ",combinedArray[i]);
return 0;
}
Please check the
compiled program and its output for your reference:
Output:
(I believe that I made the code simple and understandable. If you
still have any query, Feel free to drop me a comment)
Hope this Helps!!!
Please upvote as well, If you got the answer?
If not please comment, I will Help you with that...
Get Answers For Free
Most questions answered within 1 hours.