AmitM9S6
AmitM9S6

Reputation: 131

How to find the biggest number in an array

I have an array with a size that I dont know(mostly a size of a 10), that most of it has 1's and 2's, but sometimes 3's and 4's... I cant buble sort, because the order is importhan, but other then that, I can do everything

Thanks :)

Upvotes: 0

Views: 409

Answers (5)

std''OrgnlDave
std''OrgnlDave

Reputation: 3968

I don't have access to a compiler that supports this right now, but here's a concise example of how to do it in C++11:

#include <iostream>

constexpr int array[10] = { 1, 0, 2, 3, 0, 2, 7, 1, 9, 2 };

template<int maxest, int index>
struct find_biggest_r {
  enum { value = find_biggest_r<(array[index] > maxest ? array[index]:maxest),index-1>::value };
};

template<int maxest>
struct find_biggest_r<maxest,0> {
 enum { value = (array[0] > maxest ? array[0] : maxest) };
};

template<int index>
struct find_biggest {
  enum { value = find_biggest_r<array[index],index-1>::value };
};

int main()
{
    std::cout << find_biggest<9>::value;
}

//

Now that I'm done trolling, in C, you would do:

int array[4] = { 2, 1, 0, 2 };
int biggest = array[0];
for (int i = 1; i < 4; i++) { // we've already used array[0] so we start at array[1]
  if (array[i] > biggest) biggest = array[i];
}

Upvotes: 2

Jainendra
Jainendra

Reputation: 25153

You can try this:-

int max = array[0];    
for (int j = 1 to size)
{
    if(array[j] > max)
     {
        max = array[j];
     }
}

Upvotes: 1

Vijay
Vijay

Reputation: 67301

start traversing the array in a for loop. Take a variable and by default put the first element in it and assume as the highest. while you traverse,when ever you find an element greater than the value in the variable just replace it. at the end of the loop the value contains the highest number.

Upvotes: 1

Asha
Asha

Reputation: 11232

I will give only the pseudocode

max := array[0];

for i = 1 to size
    if(array[i] > max)
     {
        max := array[i]
     }

Upvotes: 1

Mario The Spoon
Mario The Spoon

Reputation: 4869

Iterate over the array until you hit your break condition.

While iterating (use the for or while loop), remember the highest value so far and compare against current.

Upvotes: 2

Related Questions