Answer to Question #238938 in C++ for kool

Question #238938

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-18T11:26:44-0400
#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;
}

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