Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Standard Deviation C++ Program

  1. Mar 31, 2007 #1
    I wrote a program that is supposed to find the standard deviation of a set, but something really strange happens in a for loop that I have in my main function.

    int main()
    int i=1;
    double data[NUMBER_OF_ELEMENTS];

    cout << "Please enter the number of elements followed by each individual data element:" << endl;

    cout << "Data element " << i << ": ";
    cin >> data[i-1];
    cout << endl;

    cout << "The standard deviation is: " << std_dev(data, NUMBER_OF_ELEMENTS);
    return EXIT_SUCCESS;

    No matter what size I give to the array (for the number_of_elements), the integer, 'i,' in the for loop will go to 2, and the next time through the loop 'i' increments to some wacky number (i.e. 1432104).

    Can anyone pick out what would cause something strange like this?
  2. jcsd
  3. Mar 31, 2007 #2
    what compiler did you use to? does it actually compile?
    do you know anything about "static vs dynamic allocation"?
    and what do you expect these two lines to do:

    double data[NUMBER_OF_ELEMENTS];
  4. Mar 31, 2007 #3
    I think I see what you are getting at. The data declaration should be below where the number of elements is read?
  5. Mar 31, 2007 #4
    Think about this: how would the compiler know how big to make the array?
  6. Mar 31, 2007 #5
    So I could either make a pointer or just move the declaration.

    Awesome, thanks.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook