Write in C++, comments would be a plus! Suppose A, B, C are arrays of integers o
ID: 3801843 • Letter: W
Question
Write in C++, comments would be a plus!
Suppose A, B, C are arrays of integers of size M, N, and M + N respectively. The numbers in array A appear in ascending order while the numbers in array B appear in descending order. Write a user defined function in C++ to produce third array C by merging arrays A and B in ascending order. Use A, B and C as arguments in the function. You will need to ask user to input M and N, and based on those inputs user needs to fill the arrays A and B in an appropriate order. If user wants to input wrong order of values, your program should not accept it, and should ask for appropriate value.
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
void asendingOrder(int A[], int B[], int C[], int m, int n){
int i;
for(i=0; i<m; i++){
C[i]=A[i];
}
for(int j=n-1; j>=0;j--, i++){
C[i]=B[j];
}
}
int main() {
int *pvalue1 = NULL, *pvalue2 = NULL;
pvalue1 = new int;
pvalue2 = new int;
cout<<"Enter the first array size: ";
cin >> *pvalue1;
cout<<"Enter the first array size: ";
cin >> *pvalue2;
const int m = *pvalue1;
const int n = *pvalue2;
int *A = 0;
A = new int[m];
int *B = 0;
B = new int[n];
int *C = 0;
C = new int[m+n];
cout<<"Enter the "<<m<<" values: "<<endl;
for(int i=0; i<m; i++){
cin >> A[i];
if(i > 0){
if(A[i] <= A[i-1]){
cout<<"Invalid input. Value should be greater than the previous"<<endl;
i--;
}
}
}
cout<<"Enter the "<<n<<" values: "<<endl;
for(int i=0; i<n; i++){
cin >> B[i];
if(i > 0){
if(B[i] >= B[i-1]){
cout<<"Invalid input. Value should be less than the previous"<<endl;
i--;
}
}
}
asendingOrder(A, B,C, m,n);
cout<<"New array elements are: "<<endl;
for(int i=0; i<m+n; i++){
cout<<C[i]<<" ";
}
cout<<endl;
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter the first array size: 4
Enter the first array size: 3
Enter the 4 values:
1
2
3
-1
Invalid input. Value should be greater than the previous
4
Enter the 3 values:
8
7
9
Invalid input. Value should be less than the previous
6
New array elements are:
1 2 3 4 6 7 8
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.