How to separate even and odd numbers in an array in C++
This tutorial will explain how to separate even and odd numbers in an array in C++ and transport them to two different and separate arrays.
Illustration
Suppose we enter an array that contains the following elements 1,2,3,4,5,6,7,8,9 then the program will separate the even and or numbers and it will create two new arrays, one contains – Odd numbers: 1,3,5,7,9 and the other contains Even numbers: 2,4,6,8. ( This should be kept specifically in mind that there needs to be an equal size of all three arrays. Otherwise, a problem might arise later if all the numbers the user inserts are either even or odd and there’s not enough space in the array )
For those of you who don’t understand the concept of an array, it’s basically a type of contiguous data structure that has memory locations next to each other. This allows a rigid type of data structure whose length or position in memory cannot be altered once it is declared.
Separate even and odd numbers in an array in C++
Algorithm of the program:
- Take input in the form of an integer or float array(Arr).
- Take evncnt=0 and oddcnt=0
- start for loop i=0 up to i<= length of array
- if (Arr[i]%2==0) then
- even[evncnt++]=Arr[i]
- else odd[oddcnt++]=Arr[i]
- end if
- end for
- end
Program to separate even and odd numbers in an array in C++
#include <iostream> using namespace std; int main() { int arr[10],even[10],odd[10],evncnt=0,oddcnt=0,i; cout<<"Input numbers in the array"; for(i=0;i<10;i++) cin>>arr[i]; for(i=0;i<10;i++) { if(arr[i]%2==0) even[evncnt++]=arr[i]; else odd[oddcnt++]=arr[i]; } cout<<"The even numbers are: "; for(i=0;i<evncnt;i++) cout<<even[i]<<" "; cout<<"\nThe odd numbers are: "; for(i=0;i<oddcnt;i++) cout<<odd[i]<<" "; }
The output of the above program:
As you can see the results came out pretty nicely, but there are a few downsides of using this program. While using the array, we cannot determine how many numbers the array should hold in the first place since the array is not dynamic in C++. We also cannot change the size of the even and odd array thereby them taking equal space as of the primary array.
Leave a Reply