Orion42 Blog

~IT made easy~

Computer and Coding

[C++] Count how many even and odd numbers there are in a sequence

Today we learn how to count how many even and odd numbers there are in a sequence of integers. Like any problem, many solutions exist and here we analyse just one among many possible ones.

This is the complete code:

/* Write a function to count how many even and odd numbers there are in a sequence of integers.
    Examples:
    Input                      Returns
    [1, 6, 3, 2, 5, 12, 7]     3 even, 4
    [-2, -12, 5, 8, 9, 10]     4 even, 2 odd 
*/

#include <iostream>
#include <tuple>
using namespace std;

// Foward declarations
int countEven(int *seq);  
tuple<int , int> countEvenOdd(int *seq);


main() { 

// Initialise sequences
  int seq1[] = {1, 6, 3, 2, 5, 12, 7} ;
  int seq2[] = {-2, -12, 5, 8, 9, 10};

// Run the function
  int nEven1 = countEven(seq1);
  int nEven2 = countEven(seq2);

// Print outputs
  cout << "Number of even number" << endl;
  cout << "  in seq1: " << nEven1 << endl;
  cout << "  in seq2: " << nEven2 << endl;

// Print both even and odd numbers with a different function
  int nEven, nOdd;
  tie(nEven , nOdd) = countEvenOdd(seq1);
  printf("seq1 has %d even numbers and %d odd numbers. \n", nEven, nOdd); 

   tie(nEven , nOdd) = countEvenOdd(seq2); 
   printf("seq2 has %d even numbers and %d odd numbers. \n", nEven, nOdd); 
  
return 0;
}


int countEven(int *seq){

  int counter = 0;  // Set up a counter 
  for (int i=0; i < sizeof(seq)-1; i++) {   // loop
  
    if (seq[i]%2 == 0)    // divide by two: the number is even if remainder is zero
      counter += 1;              // 
    
  } 

return counter;
}

tuple<int , int> countEvenOdd(int *seq)
{

  int even = 0;
  int odd =0;
  for (int i=0; i < sizeof(seq)-1; i++)    // loop
    (seq[i]%2  == 0) ? even += 1 : odd += 1 ;
    
    return make_tuple(even, odd);
}

 

Leave a Reply

Skip to content