431,918 Members | 1,557 Online
Need help? Post your question and get tips & solutions from a community of 431,918 IT Pros & Developers. It's quick & easy.

# calculating the min and max from a loop

 P: 1 Hello, I am writing a program that asks the user how many integers they would like to enter. You can assume they will enter a number >= 1. The program will then prompt the user to enter that many integers. After all the numbers have been entered, the program should display the largest and smallest of those numbers. I am having a couple problems. For example, if I input that I want to enter 4 integers I can only input 3 numbers before it calculates the min and max. Additionally, if I input that I want to enter 4 integers, and one of those integers is negative (-1 for instance), the output is shortened and is sometimes incorrect. Any insight is much appreciated. Expand|Select|Wrap|Line Numbers #include  using namespace std;   int main() {   int input;   int tmp;   int counter = 1;   int max_num = -1;   int min_num = -1;   //prompt user for integer amount   cout << "How many integers would you like to enter? " << endl;   cin >> input;     cout << "Please enter " << input << " integers." << endl;   tmp = input;   //loop for requested amount with a test for each input   while (counter <= tmp){     cin >> input;   //if smaller than previous number it is the minimum   if (input < min_num || min_num == -1){     min_num = input;     counter++;   }   // if larger than previous number it becomes max number else   if (input > max_num){     max_num = input;     counter++;   }   //continue loop if number isn't bigger than max or smaller than min   else {     counter++;   } }   //display the max and min cout << "min: " << min_num << endl; cout << "max: " << max_num << endl;   return 0;   }   Oct 8 '17 #1
 Expert Mod 5K+ P: 9,731 You aren't incrementing your counter properly. Right now you have: Expand|Select|Wrap|Line Numbers while (counter <= tmp){   cin >> input;     if (input < min_num || min_num == -1){     //increment counter   }     if (input > max_num){     //increment counter   }else{     //increment counter   } }   This means that your counter gets incremented the fist time someone enters a number (because `min_num` is -1) and then it gets incremented again in the second if-block. You should only be incrementing `counter` once per loop. And it should be incremented regardless of the user's input because it is simply used to count the number of integers that the user has entered so far. You should have something like: Expand|Select|Wrap|Line Numbers while (counter <= tmp){   cin >> input;     if (input < min_num || min_num == -1){     //do stuff to set the minimum number entered   }     if (input > max_num){     //do stuff to set the maximum number entered   }     //increment counter that is tracking the number   //of integers the user has provided so far   //(regardless of what you have done above)   counter++; }   Oct 10 '17 #3