In: Computer Science
C++
1) Given Arr[10] = {7, 9, 13, 15, 16, 10, 12, 5, 20, 27}
Write a program to count number of EVEN and ODD items. Do a screen output of your result.
2) Given Arr[10] = {7, 9, 13, 15, 16, 10, 12, 5, 20, 27}
Write a program to construct array ODD[] and EVEN[] from Arr[10] as you realize ODD[] consists of odd number and EVEN[] consists of even number.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n; // total number of elements in the array
cin >> n;
int arr[n]; //defining array of size n
int oddCount = 0, evenCount = 0;
for(int i = 0; i<n; i++){
cin >> arr[i];
if(arr[i]%2 == 0) // checking if number is even
{
evenCount = evenCount +1; //increasing even count
}
else{ // checking for odd numbers
oddCount = oddCount + 1; // increasing odd count
}
}
cout << "Total number of even numbers are " << evenCount << " and total number of odd numbers are " << oddCount << endl;
int even[evenCount]; // array of even numbers only
int odd[oddCount]; // array of odd numbers only
//Question two starts from here
int j = 0, k = 0; // iterators
for(int i = 0; i < n; i++){
if(arr[i]%2 == 0) // checking if number is even
{
even[j++] = arr[i]; // storing even numbers in even array
}
else{ // checking for odd numbers
odd[k++] = arr[i]; // storing odd numbers in odd array
}
}
cout << "Even numbers array : ";
for(int i = 0 ; i<evenCount; i++){ // dispalying even numbers array
cout << even[i] << " ";
}
cout << "\nOdd numbers array : ";
for(int i = 0; i<oddCount; i++){ //displaying odd numbers array
cout << odd[i] << " ";
}
}
output will look like below image
i have done both questions combined and added comments for better understanding. i hope it will help you.
for any more doubt comment below.