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.
#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;
}
Comments
Leave a comment