Thread: Can you help me?

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    15

    Can you help me?

    I am trying to modify this code so that it displays the index of the array element that contains the highest amount.


    // searches for the highest amount stored in a one-dimensional array ()

    {

    //declare array

    int dollars [6] = {25, 30, 50, 20, 15, 25} ;


    int high = dollars [0]; // assign first element value to high

    int x = 1; // begin search with second element

    while (x < 6)

    {

    if (dollars{x} > high) //compare values
    high = dollars{x}; // assign element value to high

    //end if

    x = x+1; // update subscript

    } //end while



    // display highest value
    cout << "High: " << high << endl;

    return 0;

    } //end of main function

  2. #2
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Load the value of x into another int at the start of each loop. When the loop exits that value will hold the index (as long as you populate it prior to incrementing x).

    Code:
    int i, x=1, high=dollars[0];
    
    while(x<6)
    {
       i=x;
       if(dollars[x]>high)
       high=dollars[x];
       x++;
    }
    
    cout<<"High value: "<<high<<" found at index: "<<i<<endl;

  3. #3
    Unregistered
    Guest
    I'm not quite sure about this but it looks like the code above would give you 5 for a value of x every time.

    try instead of
    Code:
    high=dollars[x];
    
    high=x;
    This will give you the index of the highest element once you exit the loop. Or you could add the i=x line into the if statement.

  4. #4
    . Driveway's Avatar
    Join Date
    May 2002
    Posts
    469
    if (dollars{x} > high) //compare values
    high = dollars{x}
    You need to use these [] not these {}

  5. #5
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Originally posted by Unregistered
    I'm not quite sure about this but it looks like the code above would give you 5 for a value of x every time.
    You're right. I didn't even catch that. I normally use a break-point test in my loops ( though I didn't include one here ). I didn't load the index value into high due to the fact that ( as I understood it ) he needs to return the value and the index.

    What I should have put was:

    Code:
    int i, x=1, high=dollar[0];
    
    while(x<6)
    {
        if(dollar[x]>high)
        {
           i=x;
           high=dollar[x];
        }
        x++;
    }
    
    cout<<"High value: "<<high<<" found at index: "<<i<<endl;
    Thanks for catching that!

  6. #6
    Registered User
    Join Date
    May 2002
    Posts
    15

    THanks!!!

    I appreciate your help!!!!!!!!!!!!!

Popular pages Recent additions subscribe to a feed