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>
#include <string>
#include <iomanip>
using namespace std;
int main(){
int a[10];
int counterEvenNumbers=0;
int counterOddNumbers=0;
cout<<"enter the elements of the array\n";
for(int i=0;i<10;i++){
cin>>a[i];
if(a[i]%2==0){
counterEvenNumbers++;
}else{
counterOddNumbers++;
}
}
int* evenNumbers=new int[counterEvenNumbers];
int* oddNumbers=new int[counterOddNumbers];
counterEvenNumbers=0;
counterOddNumbers=0;
for(int i=0;i<10;i++){
if(a[i]%2==0){
evenNumbers[counterEvenNumbers]=a[i];
counterEvenNumbers++;
}else{
oddNumbers[counterOddNumbers]=a[i];
counterOddNumbers++;
}
}
cout<<"\nEven numbers: \n";
for(int i=0;i<counterEvenNumbers;i++){
cout<<evenNumbers[i]<<" ";
}
cout<<"\nOdd numbers: \n";
for(int i=0;i<counterOddNumbers;i++){
cout<<oddNumbers[i]<<" ";
}
delete[] evenNumbers;
delete[] oddNumbers;
cin>>a[0];
return 0;
}
Comments
Leave a comment