This code keep giving me 0 for mode

  • Thread starter Thread starter Demon117
  • Start date Start date
  • Tags Tags
    Code Mode
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 1K views
Demon117
Messages
162
Reaction score
1
This is the code I have:

Code:
#include <iostream>
#include <cstring>
using namespace std;


template <class X> X mode(X *data, int size)
{
  register int t, w;
  X md, oldmd;
  int count, oldcount;

  oldmd = 0;
  oldcount = 0;
  for(t=0; t<size; t++) {
    md = data[t];
    count = 1;
    for(w = t+1; w < size; w++) 
      if(md==data[w]) count++;
    if(count > oldcount) {
      oldmd = md;
      oldcount = count;
    }
  }
  system("pause");
  return oldmd;
}

int main()
{
  int i[] = { 2, 3, 4, 2, 1, 2, 2, 5, 6, 7};
  char *p = "lame question";

  cout << "mode of i: " << mode(i, 100) << endl;
  cout << "mode of p: " << mode(p, (int) strlen(p))<<endl;
  system("pause");
  return 0;
}

Why does my mode keep coming back for i?
 
Physics news on Phys.org
Shouldn't your first call to mode be mode(i, 10)? Your array has 10 elements in it, not 100.

Also, it's not the best style to name your array i. C or C++ programmers typically use i as a loop counter variable of type int.
 
When you have a function that takes an array as a parameter, as your mode function does, the usual practice is to pass the address of the array and the size of the array (which you are doing). However, it's better to let the compiler calculate the size of the array at compile time, like this:
Code:
cout << "mode of i: " << mode(i, sizeof (i)/sizeof(i[0])) << endl;
Assuming four-byte ints, sizeof(i) evaluates to 40, and sizeof(i[0]) evaluates to 4. The quotient is 10, the number of elements in your array.
 
Mark44 said:
When you have a function that takes an array as a parameter, as your mode function does, the usual practice is to pass the address of the array and the size of the array (which you are doing). However, it's better to let the compiler calculate the size of the array at compile time, like this:
Code:
cout << "mode of i: " << mode(i, sizeof (i)/sizeof(i[0])) << endl;
Assuming four-byte ints, sizeof(i) evaluates to 40, and sizeof(i[0]) evaluates to 4. The quotient is 10, the number of elements in your array.
Alas this practice is prone to error when you decide to make i dynamically allocated.

Really, since he's using C++, he should be using container classes. :)