C++ Program To Find Smallest and Largest Number In Array -


beginner in c++ here , learning arrays. program below supposed return smallest , largest number in array using 2 separate functions. 1 largest , 1 smallest number. however, returning 0 time function lastlowestindex , unsure may doing wrong.

could ever kindly advice , show me incorrect in function , can done correct returns correct value? not seeing and/or understanding incorrect.

thank , time in advance!!!

#include <iostream> #include <cstdlib>  int lastlargestindex(int [], int); int lastlowestindex(int [], int );  using namespace std;  int main() {    const int n = 15;    int arr[n] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};    int location;    //int location2;     location = lastlargestindex( arr, n );     cout << "the last largest number is:" << location << endl;    location = lastlowestindex(arr, n);    cout << "the last smallest number is:" << location << endl;     // std::system ("pause");     return 0; }  int lastlargestindex( int arr[], int size ) {    int highnum = 0;     for( int = 0; < size; i++ )    {       if ( arr[i]  > highnum )       {          highnum = arr[i];       }    }     return highnum; }  int lastlowestindex(int arr[], int size) {      int smallest = 0;      (int = 0; < size; i++)     {         if (arr[i] < smallest)         {              smallest = arr[i];          }      }      //cout << smallest << '\n';      return smallest;   } 

however, returning 0 time function lastlowestindex , unsure may doing wrong.

you got logic error when initialised smallest 0 in function lastlowestindex() - way if (arr[i] < smallest) condition not evaluated true if input positive. instead, should initialise first member of array arr. function should this:

int lastlowestindex(int arr[], int size) {      int smallest = arr[0];     (int = 0; < size; i++)     {         if (arr[i] < smallest)         {             smallest = arr[i];         }     }     return smallest; } 

Comments

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

arrays - Algorithm to find ideal starting spot in a circle -