yonatantaase
yonatantaase

Reputation: 21

C++ Find biggest element in an array with negative values

I set the variable biggest to 0 and then looped every element in the array and checked if it is bigger than the current biggest value and it works with regular numbers but not with negative ones.
How can I fix it to work with negatives too?

#include <iostream>

using namespace std;

int main(){
    int a[7] = { -1, -3, -4, -5, -6, -1, -7 }; //array
    int biggest = 0; //biggest number in the array
    for(int i = 0; i < 4; i++) { //looping every element in the array 
        if(a[i] > biggest) { //checking if the current number is bigger then the biiger number
            biggest = a[i]; //setting the biggest number to be = to the current number
         }
     }
     cout << biggest << endl; //printing the biggest number
}

Upvotes: 1

Views: 1536

Answers (3)

Damian
Damian

Reputation: 1374

You can make the initial biggest as the first element of the array. You don't need to use any limits.

#include <iostream>

using namespace std;

int main() {
   int a[7] = { -1, -3, -4, -5, -6, -1, -7 };
   int biggest = a[0];
   for (int i = 1; i < 7; i++){ 
      if (a[i] > biggest){
         biggest = a[i];
      }
   }
   cout << biggest << endl;
}

Upvotes: 3

Kapil khandelwal
Kapil khandelwal

Reputation: 63

Use INT_MIN as it has the minimum value in int, you can use this by adding a #include<climits> library in your program

Upvotes: 0

iamdhavalparmar
iamdhavalparmar

Reputation: 1218

It will print the zero but if you want to get the biggest number from your array

initialize your int biggest = INT_MIN; instead of int biggest = 0;

The value of INT_MIN is -2147483647 - 1 which will solve your problem.

Also include #include <bits/stdc++.h> for INT_MIN.

Upvotes: -1

Related Questions