Home > Software engineering >  Find the product of elements located between the maximum and minimum elements of an array
Find the product of elements located between the maximum and minimum elements of an array

Time:11-17

#include <iostream>
using namespace std;

int main()
{
    int n, a, b,min,max, Prod = 1, Sum = 0;
    cout << "Initialize an array n: ";
    cin >> n;
    do
    {
        cout << "Input the start value: ";
        cin >> a;
        cout << "Input the end value: ";
        cin >> b;
        if (!(a < b))
        {
            cout << "a is bigger than b, please enter new values " << endl;
            continue;
        }
    } while (!(a < b));

    int* lpi_arr;
    lpi_arr = new int[n];

    srand(time(NULL));
    cout << "Int numbers from " << a << " to " << b << endl;

    for (int i = 0; i < n; i  )
    {
        lpi_arr[i] = rand() % (b - a)   a;
        cout << lpi_arr[i] << " ";
    }

    max = lpi_arr[0];
    for (int i = 0; i < n; i  )
    {
        if (max < lpi_arr[i])
            max = lpi_arr[i];
    }
    min = lpi_arr[0];
    for (int i = 0; i < n; i  )
    {
        if (min > lpi_arr[i])
            min = lpi_arr[i];
    }

    cout << "\nmin element is = " << min << endl;
    cout << "\nmax element is = " << max << endl;

    for (int i = max   1; i < min; i  )
        Prod *= lpi_arr[i];

    for (int i = 0; lpi_arr[i] < 0 && i < n; i  )
        Sum  = lpi_arr[i];

    cout << "Summ =" << Sum << endl << "Prod = " << Prod << endl;

    delete[] lpi_arr; 
}

The main purpose of this code is to calculate the sum of negative numbers of an array, and multiplication of elements located between the maximum and minimum elements of an array.

The problem is that the code implements only 1(one) as an answer, and I don't know how to change it. Every other part of the code works well, but if you have any recommendations I'd also like to read it. Waiting for your help.

CodePudding user response:

Your issue is that you're confusing array indexes with array values.

Here you're assigning max (and same with min) to an array value.

max = lpi_arr[i];

Here you're treating max (and same with min) as an array index.

for (int i = max   1; i < min; i  )
    Prod *= lpi_arr[i];
  • Related