Pushkar Soni Pushkar Soni - 2 months ago 6
C++ Question

why i am getting this number?

i am trying to merge two arrays into one. but could not figure out why the number comes out instead of the desired number and what does this number signify.

#include<iostream>
#include<conio.h>

using namespace std;

void MergeArray(int[], int, int[], int,int[]);

void main()
{
int A[50], m, B[50], n, C[100],a, mn;

cout<<"Enter the size of First Array::\n";
cin>>m;
cout<<"Enter the First Array(ASCENDING ORDER)\n";
for(int i=0; i<m ; i++)
cin>>A[i];
cout<<"Enter the size of Second Array::\n";
cin>>n;
cout<<"Enter the Second Array(DESCENDING ORDER) ::\n";
for(int j=0; j<n; j++)
cin>>B[j];
mn=m+n;
MergeArray(A,m,B,n,C);

cout<<"The Array After merging is ::\n";
for(int k=0; k < mn; k++ )
cout<<C[k]<<"\n";
cout<<"Press any key";
cin>>a;

}


void MergeArray(int a[],int M , int b[], int N, int c[] )
{
int x,y,z;
z=0;

for(x=0, y=N-1; x<M && y>=0;)
{
if(a[x]<=b[y])
c[z++]=a[x++];
else if(b[y]<a[x])
c[z++]=b[y--];
}

if(x<M)
{
while(x<M)
c[z++]=a[x++];
}

if(y>0)
{
while(y>=0)
c[z++]=b[y++];

}

getch();

}


Image of the output screen}

Answer

I think the problem is right here:

if(y>0)
{
    while(y>=0)
        c[z++]=b[y++];  // <-- y++ instead of y--

}

You should be decreasing y, not increasing it.

Comments