Finding smallest value in an array.

I'm trying to write a function that runs a loop to find and display the smallest integer in an array. This is for a much larger program for class, but this what I'm struggling with, so I've isolated it into it's own little program. At the moment, it doesn't output anything. I feel like this is something small and kind of silly, but I can't for the life of me figure out what's wrong. Here's 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
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
    const int SIZE = 5;
    int array []= {4,2,3,1,5};
    int smallest=array[0];
    for (int i=0; i<=SIZE-1; i++) 
    {
        if (array[i]<=smallest && i!=SIZE-1) 
        {
            smallest=array[i];

        }
        else if (array[i]<= smallest && i==SIZE-1)
        {
            smallest=array[i];
            cout << smallest << endl;
        }
    
    }
    return 0;
}

Thank you!
It doesn't output anything because array[SIZE-1] is not <= smallest. (5 <= 1) evaluates to false.


The more usual way to do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main ()
{
    int array []= {4,2,3,1,5};

    int smallest = array[0] ;
    for ( int i=1;  i < sizeof(array)/sizeof(array[0]);  ++i )
        if ( array[i] < smallest )
             smallest = array[i] ;

    cout << smallest << '\n' ;

    return 0;
}
Thank you so much!
Topic archived. No new replies allowed.