Home > Mobile >  Find Extreme Value in Integers Given
Find Extreme Value in Integers Given

Time:10-22

I'm trying to find the highest value in a given list, but in an input list like this

7 385 -390 305 470 -145 255 30

my output is wrong, 385 instead of 470.

Could anyone please guide me towards my error!

Task description:

Read in an input value for variable numIn. Then, read numIn integers from input and output the largest of the integers read. End with a newline.

Ex: If the input is 2 345 -5, then the output is:

345

my code below

#include <iostream>
using namespace std;

int main() {
    int numIn;

    int high = 0;

    cin >> numIn;

    for (int i = 0; i < numIn; i  ) {
        cin >> numIn;

        if (numIn > high) {
            high = numIn;
        }
    }

    cout << high << endl;

    return 0;
}

CodePudding user response:

First of all, your list has negative numbers. You can't set the default value of high to 0 since a list with all negative numbers won't work if you do this.

The error in your loop occurs because you overwrite numIn. Use a different variable for the number of input numbers.

cin >> numIn; // numIn is the number of input numbers
  for (int i = 0; i < numIn; i  ) {
    cin >> numIn; // oops, numIn is now the first input number. it has been overwritten.
    if (numIn > high) {
      high = numIn;
    }
  }

A correct solution would look like this:

#include <iostream>

int main() {
  int N; // assume that N >= 1. You could also replace this with numIn.
  std::cin >> N;

  int max;
  std::cin >> max; // take in the first integer outside the loop
  for (auto i = 1; i < N; i  ) { // loop which runs N - 1 times
    int E;
    std::cin >> E;
    max = std::max(max, E);
  }

  std::cout << max << '\n';
}

Without using std::max()

If you don't want to use std::max(), replace the line where you use it with a normal comparison (this is what std::max() does internally too)

if (E > max) { max = E; }
  •  Tags:  
  • c
  • Related