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;
}
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];