Largest index in an array?

I have the following question for a bonus assignment:
Write a program in C++ that asks the user to enter an array of size N and find index of the largest value in that array using a function named largest_location that takes an array of integer values and an integer that tells how many integer values are in the array as arguments. The function should return as its value the index of the cell containing the largest
of the values in the array. Do not forget to write the main function as well. Your main function should get the array from the user and pass it to the function largest_location. Print the index of the largest location in the main function.

I almost completed it, then I realized that I was just doing the greatest number in the array instead of the index number. I just need help outputting that "index 3 has the highest number of..." This is the code I have written that works(except for what the index number is)


#include <iostream>
using namespace std;

void largest_location(float array[],int arraylength )
{
float temporary =array[0];
for (int i=0; i<arraylength; i++){

if(array[i]>temporary){
temporary=array[i];}
}
cout << "The largest location in the array is "<<temporary;
}
int main()
{
int arraylength;
cout<<"Enter the array size: ";
cin>>arraylength;

float* array = new float[arraylength];
cout<<"Enter the numbers in the array:" << endl;
for (int i=0; i<arraylength; i++){
cin >> array[i];
}
largest_location( array, arraylength );
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

// return int: the position of the largest element in the array
int largest_location( const float array[], int arraylength ) // note: const
{
    // basic sanity checks
    if( array == nullptr || arraylength == 0 ) return -1 ;

    int pos_largest_so_far = 0 ;
    for( int i = 0; i < arraylength; ++i ) if( array[i] > array[pos_largest_so_far] ) pos_largest_so_far = i ;

    return pos_largest_so_far ; // return the position
}

int main()
{
    const int MAX_SIZE = 1000 ;
    float array[MAX_SIZE] ;

    int actual_size ;
    std::cout << "Enter the array size: ";
    std::cin >> actual_size;
    if( actual_size > MAX_SIZE ) actual_size = MAX_SIZE ;

    std::cout << "Enter the numbers in the array:\n" ;
    for( int i = 0; i < actual_size; ++i ) std::cin >> array[i] ;

    const int pos_largest = largest_location( array, actual_size );
    if( pos_largest != -1 )
    {
        std::cout << "The largest location in the array is " << pos_largest
                  << " (holding value " << array[pos_largest] << ")\n" ;
    }
}
Topic archived. No new replies allowed.