Write C++ program to count even and odd elements in an 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. int main()
  6. {
  7.  
  8. int arr[MAX_SIZE];
  9. int i, num, evennum, oddnum;
  10.  
  11. // Reads size and elements in array
  12. cout<<"Enter size of the array: ";
  13. cin>>num;
  14. cout<<"Enter "<<num<<" elements in array: ";
  15. for(i=0; i<num; i++)
  16. {
  17. cin>>arr[i];
  18. }
  19.  
  20. evennum = 0; // Assuming 0 even numbers
  21. oddnum = 0; // Assuming 0 odd numbers
  22.  
  23. for(i=0; i<num; i++)
  24. {
  25. /* If the current element of array is evennumber then increment evennumber count */
  26. if(arr[i]%2 == 0)
  27. {
  28. evennum++;
  29. }
  30. else
  31. {
  32. oddnum++; // increment oddnumber count
  33. }
  34. }
  35.  
  36. cout<<"Total even numbers: "<<evennum<<endl;
  37. cout<<"Total odd numbers: "<<oddnum<<endl;
  38.  
  39. return 0;
  40.  
  41. }
  42.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts