Home > Enterprise >  getting the minimum for arrays and for statments?
getting the minimum for arrays and for statments?

Time:10-16

I sorta need help getting the minimum I keep getting thirteen can some one help me out? The issue I believe is I'm not showing the formula for low n line I'm confused I have tried to switch out the values for the array and I can't figure it out just if someone could explain to m please.

#include <iostream>
using namespace std;

int getHighest(int numArray[], int numElements);
int getLowest(int numArray[], int numelements);

int main()
{
    int numbers[4] = { 13, 2, 40, 25 };

    cout << "The highest number in the array is " << getHighest(numbers, 4) << "." << endl;
    cout << "The lowest number in the array is "<< getLowest(numbers,0) << "." << endl;
    return 0;
}
int getHighest(int numArray[], int numElements)
{
    int high = numArray[0];

    for (int sub = 1; sub < numElements; sub  = 1)
        if (numArray[sub] > high)
            high = numArray[sub];
       
    return high;
}
int getLowest(int numArray[], int numElements)
{
    int low = numArray[0];
    for (int sub = 0; sub >= numElements; sub--)
        if (numArray[sub]< low)
            low = numArray[sub];
    return low;
}

CodePudding user response:

This is the corrected example:

int getLowest(int numArray[], int numElements)
{
    int low = numArray[0];
    for (int sub = 1; sub < numElements;   sub)
        {
        //std::cout<<"checking: "<<numArray[sub]<<"with"<<low<<std::endl;
        if (numArray[sub]< low){
            low = numArray[sub];
        }
            
        }
    return low;
}

The complete working example is here

Also note in your given example you have made a mistake at:

cout << "The lowest number in the array is "<< getLowest(numbers,0) << "." << endl;

Instead of passing 0 as the second argument you should pass 4 as i did here.

Another mistake was the initial value of varaible sub in the for loop. You started with sub = 0 instead of sub = numelements - 1. That is the for loop should have looked like:

//note in the next line we have sub >=1 instead of sub>=0 becuase you have already stored numArray[0] in variable low
for (int sub = numElements -1; sub >=1; --sub)
{
    ...other code here
}

CodePudding user response:

Concerning getLowest():

There is actually no need to iterate backwards. It could be done like in getHighest(). However, say this is a requirement for teaching…

The test array is

int numbers[4] = { 13, 2, 40, 25 };
// indices:        0   1  2   3
// number of elements: 4

A loop to iterate backwards has to start with index numElements - 1 (3 in this case) and to stop at index 0.

for (int sub = numElements - 1; sub >= 0; sub--)

Nevertheless, this will check the last element which is already assigned before the loop. (getHighest() starts the loop with the 2nd element for this reason: for (int sub = 1;…) Thus, this can be corrected to:

for (int sub = numElements - 2; sub >= 0; sub--)
  • Related