-1

So here is what I am trying to do - To write a program with an array of 50 values getting the highest number in the array and printing it out. I have hit a brick wall though. I am pretty sure I've gotten very confused with the returning in the function, for example why is index "undefined" out of the for loop in the findSmall and findBig functions?

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int findSmallest(int array[], int size, int index)
{
    int index_of_smallest_value = index;
    for (int i = index + 1; i < size; i++)
    {
        if (array[i] < array[index_of_smallest_value])
        {
            index_of_smallest_value = i;
        }
    }
    return index_of_smallest_value;
}

int findBiggest(int array[], int size, int index)
{
    int index_of_biggest_value = index;
    for (int i = index + 1; i < size; i++)
    {
        if (array[i] > array[index_of_biggest_value])
        {
            index_of_biggest_value = i;
        }
    }
    return index_of_biggest_value;
}

int findSmall(int array[], int size)
{
    int index = 0;
    for (int i = 0; i < size; i++)
    {
        index = findSmallest(array, size, i);
        //cout << index << endl;
    }
    return index;
}

int findBig(int array[], int size)
{
    int index = 0;
    for (int i = 0; i < size; i++)
    {
        index = findBiggest(array, size, i);
        //cout << index << endl;
    }
    return index;
}

int main()
{
    int array[50];
    srand(time(NULL));

    for (int i = 0; i < 50; i++)
        array[i] = rand() % 100;

    cout << "The smallest digit is " << findSmall(array, 50) << endl;
    cout << "The biggest digit is " << findBig(array, 50);
    cin.get();
}

I've edited my above code, however I keep getting returned 49 from both findSmall and findBig functions.

Coder77
  • 2,203
  • 5
  • 20
  • 28
  • I don't think there is any use to `findBig` and `findSmall`, except for observing the different results in respect to checking a different range of values of the array. Also, are you sure you want those to return 0? – E_net4 Jul 15 '14 at 09:50
  • 3
    Is this school work? Otherwise there are many nice [algorithmic functions in the standard library](http://en.cppreference.com/w/cpp/algorithm), including [a function to get the maximum value in a range](http://en.cppreference.com/w/cpp/algorithm/max_element). – Some programmer dude Jul 15 '14 at 09:51
  • What do you mean by "undefined"? Except for a type conversion warning in `srand` call everything sompiles – YePhIcK Jul 15 '14 at 09:51
  • Why does `findBig` do `findBiggest` 50 times? I don't see why you don't just do `findBiggest` once and there is your answer. – M.M Jul 15 '14 at 09:51
  • 2
    There's any number of better ways to do this, you should have a look at `std::max_element` and `std::min_element`, `std::sort`, and `std::set`. – user657267 Jul 15 '14 at 09:52
  • It's a practice problem in the book "Jumping into C++ by Alex Allain". – Coder77 Jul 15 '14 at 09:53
  • If I were to simply just call the findSmallest and findBiggest functions, what do I give as the index argument? – Coder77 Jul 15 '14 at 09:55
  • @Coder77 The "index" argument is not needed. Just a simple loop from zero to the size of the array is enough to get the largest value index. In other words, use the loop from `findBig` but in the loop use the loop-body from `findBiggest`. – Some programmer dude Jul 15 '14 at 09:56
  • @YePhIcK See here to know about the vital idea in C++: [undefined](http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). – legends2k Jul 15 '14 at 09:58
  • You can find the locations of *both* the biggest and the smallest in a single pass across the array. Doing so, however, will require you *stop coding* for a minute and think about an algorithm. When you're having problems writing code, spewing even more code usually only leads to even more problems. Know your algorithm first, *then* write the code that matches. – WhozCraig Jul 15 '14 at 10:08
  • Th problem is that the _last_ time you call `findSmallest` you are searching only in the last element. And than the function returns the index of last element. – Daniele Jul 15 '14 at 12:22

7 Answers7

3

You can do it the C++/STL way. This does not only work with arrays, but also with other STL containers.

#include <iterator>
#include <algorithm>

int minelem = *std::min_element(begin(array), end(array));
int maxelem = *std::max_element(begin(array), end(array));

This code loops over array twice. For performance reasons you might consider merging the loops. Or in C++11 you could even

auto result = std::minmax_element(begin(array), end(array));
Werner Henze
  • 16,404
  • 12
  • 44
  • 69
  • 2
    I wouldn't try to take anything away from this answer's content; it *is* the way it's done. But it never ceases to amaze me how no one seems to notice, or care, when op is clearly a struggling student and surely can't use the STL to perform the tasks they're trying to learn from. These "here's how you do it when you know what you're doing" type of answers rarely attempt to answer op's question and yet they are almost always up-voted. :o – ChiefTwoPencils Jul 15 '14 at 17:51
  • @ChiefTwoPencils It *seems* like the OP shall implement it on his own, but he does not clearly state so. So the best way to do it is not to reinvent the wheel but use the STL. Yet, if he wants to implement the function himself, the given STL functions are a good point to start since their source code is directly available (also for copying and modifying). – Werner Henze Jul 16 '14 at 07:48
1

You can follow this answer. If you are not clear here then you can ask/say me what is actually needed. And what is not available in my answer.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int findSmallest(int * begin, int * end)
{
    int small = *begin;
    while(begin != end){
        if(small > (*begin)) small = *begin;
        begin++;
    }
    return small;
}

int findBiggest(int * begin, int * end)
{
    int big = *begin;
    while(begin != end){
        if(big < (*begin)) big = *begin;
        begin++;
    }
    return big;
}

int main()
{
    int array[50];
    srand(time(NULL));

    for (int i = 0; i < 50; i++)
        array[i] = rand() % 100;
    cout << "The smallest digit is " << findSmallest(array, array+50) << endl;
    cout << "The biggest digit is " << findBiggest(array, array+50) << endl;
    return 0;
}

To understand my functions clearly you can follow the link or Use of array and a function to print first n elements in C [as like as sort(a+m, a+n)]

Md Wahid
  • 450
  • 5
  • 12
0

This is taken from link but it has been slightly changed for your problem. Does this do what you wanted it to do?

#include <iostream>

using namespace std;

int main()
{
    int array[50] = {5,123,5,9,1,5,7,89.....};
    int temp = 0;

    for(int i=0;i<50;i++)
    {
        if(array[i]>temp)
        temp=i;
    }
    cout << "The biggest number is: " << temp << endl;
    return 0;
}

You will obviously have to change the code to fit yours.

Alexander Craggs
  • 7,874
  • 4
  • 24
  • 46
0

For a one-element array the only element is a biggest one. For any longer array the biggest element is either a biggest element from the one-but-last subarray ot the last one. So this is what the code might look like:

int findBiggest(int array[], int size)
{
    int big = 0;
    for (int i = 1; i < size; i++)
        if (array[i] > array[big])
            big = i;

    return big;
}

and that's all:

int index2 = findBiggest(array, 50);
cout << "\nThe biggest digit is " << array[index2] << " at position " << index2;
CiaPan
  • 9,381
  • 2
  • 21
  • 35
0

Here is one version, where I've also used std::vector and iterators. A better way to returning values would be e.g. a custom struct or maybe using std::tuple so you don't have to track vector indices.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

using namespace std;

int findBigOrSmall(bool bigOrSmall, int a[], int s){
int big=a[0];
int small=a[0];
for(int i=0; i<s; ++i){
    if(a[i]>big) big=a[i];
    if(a[i]<small) small=a[i];
}
if(bigOrSmall) return big;
else return small;
}
std::vector<int> findBigOrSmallVec(std::vector<int> a){
int big=a[0];
int bigIndex;
int smallIndex;
int small=a[0];

for(std::vector<int>::iterator it=a.begin();it!=a.end();++it){
    if(*it>big) {
        big=*it;
        bigIndex = std::distance(a.begin(),it);
    }
    if(*it<small) {
        small=*it;
        smallIndex = std::distance(a.begin(),it);
    }
}

std::vector<int> res;
res.push_back(bigIndex);
res.push_back(big);
res.push_back(smallIndex);
res.push_back(small);
return res;

}


int main()
{
int array[50];
srand(time(NULL));
std::vector<int> randVec;

for (int i = 0; i < 50; i++){
    int randInt= rand() % 100;
    array[i] =randInt;
    randVec.push_back(randInt);

}

for(int i=0;i<50;++i) cout<<i<<": "<<array[i]<<endl;
cout<<"\n\nBiggest val="<<findBigOrSmall(true,array,50)<<endl;
cout<<"Smallest val="<<findBigOrSmall(false,array,50)<<endl;

//Now more c++-like
std::vector<int> res =findBigOrSmallVec(randVec);

cout<<"Biggest value is at position "<<res[0]<< " and is "<<res[1]<<endl;
cout<<"Smallest value is at position "<<res[2]<< " and is "<<res[3]<<endl;

}
Schaki
  • 1,697
  • 1
  • 12
  • 14
0

A branchless way of doing the same (can be used on either int/float/double)

int findBiggest(int array[],int size){
  int hi = 0;
  for (int p = 0; p < size; p++) {

    int comp = (array[hi] < array[p]);

    int diff = (p - hi);

    // this is just to debug and see what is going on
    printf("\np = %d, array[hi] = %d, array[p] = %d; comp = %d, diff = %d", p, array[hi], array[p], comp, diff);

    hi += diff * comp;

}

printf("\nindex of the highest number (%d) is %f", size[hi], hi);

}

For those of us who love the one (few) liners the version for the loop is:

int hi = 0;
for(int p = 0; p < size; p++)
    hi += (array[hi] < array[p]) * (p - hi);

return array[hi];// the biggest number or...
return hi; // the index of the biggest number
Sqripter
  • 101
  • 2
  • 7
-1
#include<iostream>
using namespace std;
int getlargest(int arr[],int n)
{
    int res = 0;
    for(int i=1;i<n;i++)
    {
        if(arr[i]>arr[res])
        res = arr[i];
    }
    return res;
}
int main()
{
    int arr[] = {9,7,8,15,4,56,74,32,11,8};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout<<getlargest(arr,n);
    cout<<"Largest:"<<" "<<arr[largest];
    return 0;

}