Scholar
Scholar

Reputation: 293

smallest value of array

I'm trying to write a function that will return the smallest value of an array. So far I have this, but all it returns is 0.

I don't see how it would return 0 since I am using a for loop to cycle through the array. Perhaps it is not cycling through the arrays values as I would think it does. Can anyone elaborate on the logic and the fallacy in this code?

#include <iostream>

using namespace std;

int newArray[9] = {4,5,9,3,6,2,1,7,8};


int minArray()
{
    int index = 1;
    int minimum;

    for (int i = 0; i < 9; i++)
    {
        if (newArray[i] > newArray[index])
        {
            minimum = newArray[index];
        }
        index++;

    }

    return minimum;
}


int main()    
{   
    cout << "original array:\n ";
    for (int i = 0; i < 9; i++)
    {
        cout << newArray[i] << ", ";
    }

    cout << "minimum value of array: ";
    cout << minArray();

    return 0;
}

Upvotes: 0

Views: 860

Answers (4)

David G
David G

Reputation: 96810

The minimum variable should be initially assigned to a value in the array, then compare each element in the array with minimum. If less than, assign minimum with that value:

int minArray()
{
    int minimum = newArray[0];
    int index = 0;

    for (int i = 0; i < 9; i++)
    {
        if (newArray[i] < minimum)
        {
            minimum = newArray[i];
        }
        index++;

    }
  return minimum;
}

Upvotes: 0

sigod
sigod

Reputation: 6407

You should initialize minimum with some known value or with maximum integer value.

int minArray()
{
    int minimum = newArray[0];

    for (int i = 1; i < 9; i++)
    {
        if (minimum > newArray[i])
        {
            minimum = newArray[i];
        }
    }

    return minimum;
}

And you are dealing wrong with index (actually you don't need it at all). Example of how index can be used instead of minimum:

int minArray()
{
    int index = 0;

    for (int i = 1; i < 9; i++)
    {
        if (newArray[index] > newArray[i])
        {
            index = i;
        }
    }

    return newArray[index];
}

Both examples should work fine, but I recommend to use first.

Upvotes: 0

neoxic
neoxic

Reputation: 565

I'd do something like this:

#include <iostream>

int minArray(int a[], int size) {
    if (size <= 0) return 0; //
    int m = a[0];
    for (int i = 1; i < size; ++i) {
       if (a[i] < m) m = a[i];
    }
    return m;
}

int main() {
    int a[] = { 4, 3, 6, 2 };
    std::cout << minArray(a, 4);
    return 0;
}

Upvotes: 0

Lews Therin
Lews Therin

Reputation: 10995

A good idea might be to initialize minimum with an element in the array. So:

minimum = newArray[0]

In your loop (pseudocode assuming you don't want the answer):

if: newArray[pos] < minimum

        minimum = newArray[pos];

Upvotes: 1

Related Questions