Answer to Question #234126 in C++ for SOM

Question #234126

Consider the code snippet given below:-

 [Assume the necessary header files and namespaces included]

int main()

{ int a[10];

 cout<<”enter the elements of the array\n”;

 for(int i=0;i<10;i++)

 cin>>a[i];

 

 

return 0;

}

 Complete the code such that the even and odd numbers from the array ‘a’ are stored into two different arrays. The size of these arrays should be same as that of the number of elements and their memory should be deallocated after displaying the odd and even numbers.


1
Expert's answer
2021-09-06T16:23:23-0400
#include "iostream"

using namespace std;

int main()
{
    int a[10];
    cout<<"enter the elements of the array\n";
    for (int i = 0; i < 10; i++)
        cin >> a[i];

    int numOdd = 0;
    int numEven = 0;
    for (int i =0; i < 10; i++) {
        if(a[i] % 2 == 0)
            numEven++;
        else
            numOdd++;
    }

    int *oddArray = new int[numOdd];
    int *evenArray = new int[numEven];
    int currentOdd = 0;
    int currentEven = 0;
    for (int i = 0; i < 10; i++) {
        if (a[i] % 2 == 0) {
            evenArray[currentEven] = a[i];
            currentEven++;
        }
        else {
            oddArray[currentOdd] = a[i];
            currentOdd++;
        }
    }

    cout << "Odd array" << endl;
    for (int i = 0; i < numOdd; i++) {
        cout << oddArray[i] << ' ';
    }
    cout << endl;
    delete []oddArray;

    cout << "Even array" << endl;
    for (int i = 0; i < numEven; i++) {
        cout << evenArray[i] << ' ';
    }
    cout << endl;
    delete []evenArray;

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS