Array Inputs and Functions

The program uses a function to return the multiple of the two largest inputs from 3 different arrays.

It would be the two largest, from the 3 arrays the first column.

The user has to input 5 Values for each Array. So 15 inputs in total.

My questions.
1) Is there a way I can alter the function, to find the two largest multiples?
2) How do I input values into the Arrays.
3) How would I alter it so the user can input the size of the Array?

Here is my code:
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
35
36
37
38
# include <iostream>
using namespace std;

float prodlargest(float a, float b, float c){
        float one, two;
        one = a;
        two = b;
        if (b > one){
            one = b;
            two = a;
        }
        if (c > one){
            two = one;
            one = c;
        } else if (c > two){
            two = c;
        }
        return one * two;
}

int main () {
    int inputArray1[5]={0,0,0,0,0};
    int inputArray2[5]={0,0,0,0,0};
    int inputArray3[5]={0,0,0,0,0};

    cin >> inputArray1[5];
    cin >> inputArray2[5];
    cin >> inputArray3[5];

    float ans1, ans2, ans3;

    //The FOR loop will multiply the first two biggest integers in the array.
    for (int i = 0; i < 5; i++) {
            ans1 = prodlargest(inputArray1[i], inputArray2[i], inputArray3[i]);
            cout << "The largest products are: " << ans1 << endl;
    } //End Loop
    return 0;
}


1) Undoubtedly, yes. But I'm not quite sure what you want. Your comment above the for loop doesn't seem to actually match up with what's happening.

2) You're doing it, albeit incorrectly. Remember that an array index starts at zero. So an array of five elements has indices 0 - 4. The line cin >> inputArray1[5] is trying to access an array index that doesn't exists. Your compiler might not flag this and let the program compile but you're accessing (or attempting to) the wrong segment of memory.

You'd want something like....
1
2
3
4
5
for( int i = 0; i < 5; i++ )
{
   cout << "Enter value for array: ";
   cin >> inputArray1[i];
}


This would need to be addressed for the other two arrays as well.

3) Naturally, array sizes are expected to be known at compile time. You can make dynamically sized arrays but they're a pain, especially considering that C++ has a class we can use for this sort of thing. What you're looking for is an STL vector: http://www.cplusplus.com/reference/stl/vector/
Last edited on
Thanks a tons, I really appreciate it.
Topic archived. No new replies allowed.