1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
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;
    int NUMBER_OF_ELEMENTS;
    double data[NUMBER_OF_ELEMENTS];

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

    for(i=1;i<=NUMBER_OF_ELEMENTS;i++)
    {
    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:

    int NUMBER_OF_ELEMENTS;
    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Standard Deviation C++ Program
  1. Program in C (Replies: 1)

  2. C++ Program (Replies: 17)

Loading...