Associating Array addresses to a variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • monte cristo gunnison
    New Member
    • Nov 2008
    • 2

    Associating Array addresses to a variable

    I am trying to get the array location to print out along with the value that is stored in that array. It works in a list of the printout of the array & value but does not later when I am trying to use it in a cout of a high and low search.

    The array size is 10 so address 0-9 are relevant and contain the data (int) entered. But when searched for high and low in the array the high returns correctly in the cout but then the array address (location) jumps to 10 and the low comes back as a 0 even when that is incorrect also at address 10 (which has no value entered and may well be 0)

    Here is the example

    for ( int j = 0; j < arraySize; j++ )
    cout<< setw( 7 ) << j << setw( 13 ) << nums[j] << endl;

    for ( j=0; j<arraySize; j++)

    cout<<nums[j]<<" "<< j<<'\n';
    //above it works just fine 0-9 with all the right values in place
    //but below j becomes 10 and only the high is correct

    for (j=0; j<arraySize; j++)
    if (nums[j] > high)
    high=nums[j];
    else
    high=high;



    for (int u=0; u<arraySize; u++)
    if (nums[j] < high)
    low=nums[j];
    else
    low=low;


    cout<<"The Highest Number is : "<<high<<" At Array Position: "<<j<< '\n';
    cout<<"The Lowest Number is : "<<low<<" At Array Position: "<<j<< '\n';
    Last edited by monte cristo gunnison; Nov 10 '08, 02:00 AM. Reason: Just to check if it is correct
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    Instead of
    Code:
    if (nums[j] > high)
        high=nums[j];
    why not do something like
    Code:
    if (nums[j] > nums[highIndex])
        highIndex=j;
    Then you can keep the location of the high variable, and you can get the value there easily.
    By the way, it would be helpful if you used code tags around your code. Put [CODE] before the code and [/CODE] after it, so it shows up in a code box and the indentation isn't wrecked. Thanks.
    I hope this is helpful.

    Comment

    • arnaudk
      Contributor
      • Sep 2007
      • 425

      #3
      "if (nums[j] < high)" should be "if (nums[u] < low)" then you'll get the correct low value. There are other places where you've used j instead of u. In any case, j and u will always become 10 because the for() loops run until this is so. To store the index of the high/low values, use another variable or do as boxfish suggests.

      Comment

      Working...