Write C++ program to put even and odd elements of array in two separate array


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. #define MAX_SIZE 100 //Maximum size of the array
  3. using namespace std;
  4.  
  5. // Function declaration to print array
  6. void printArray(int arr[], int len);
  7.  
  8. int main()
  9. {
  10. int arr[MAX_SIZE];
  11. int even[MAX_SIZE];
  12. int odd[MAX_SIZE];
  13.  
  14. int evenCount, oddCount;
  15. int i, size;
  16.  
  17. // Reading size of the array
  18. cout<<"Enter size of the array: ";
  19. cin>>size;
  20.  
  21. // Reading elements in array
  22. cout<<"Enter elements in the array: ";
  23. for (i = 0; i < size; i++) {
  24. cin>>arr[i];
  25. }
  26.  
  27. evenCount = 0;
  28. oddCount = 0;
  29.  
  30. for (i = 0; i < size; i++) {
  31. // If arr[i] is odd
  32. if (arr[i] & 1) {
  33. odd[oddCount] = arr[i];
  34. oddCount++;
  35. } else {
  36. even[evenCount] = arr[i];
  37. evenCount++;
  38. }
  39. }
  40.  
  41. cout<<"\nElements of even array: ";
  42. printArray(even, evenCount);
  43.  
  44. cout<<"\nElements of odd array: ";
  45. printArray(odd, oddCount);
  46.  
  47. return 0;
  48. }
  49. //Logic
  50. void printArray(int arr[], int len) {
  51. int i;
  52.  
  53. for (i = 0; i < len; i++) {
  54. cout<<arr[i]<<"\t";
  55. }
  56. cout<<"\n";
  57. }

Result

C++ language techstudy.org

     





Related Topics




Popular Posts