1

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
}
Damian
  • 1,084
  • 3
  • 14
  • 26
  • 2
    It prints zero right? zero is bigger than all your numbers and you initialize with zero the value biggest so the statement a[i]>biggest never evaluates to true – Spyros Mourelatos Mar 16 '21 at 08:10
  • 1
    The for loop doesn't contain the right array bounds, you're looking up to 3 where your array contains 7 elements. – Tom W Mar 16 '21 at 08:12
  • Additionally what @SpyrosMourelatos said - 0 is bigger than -7. – Tom W Mar 16 '21 at 08:13
  • Include `limits` and use `int biggest = std::numeric_limits::min();` Always initialize a variable looking for a maximum with the minimum possible value and vice-versa when looking for a minimum. – David C. Rankin Mar 16 '21 at 08:42

3 Answers3

3

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;
}
Damian
  • 1,084
  • 3
  • 14
  • 26
0

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

-1

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.

iamdhavalparmar
  • 1,090
  • 6
  • 23
  • 1
    I do not think that including bits/stdc++.h is a good practice: https://stackoverflow.com/q/31816095/13156261 – Eddymage Mar 16 '21 at 08:26