Min and Max Loop - c++

I am writing code for an assignment that wants me to make a program that asks the user for the amount of integers they'd like to input then it accepts each input while testing if the value is the max value or minimum. My program runs fine for every integer entered besides 1. When i input the int 1 only the max value is recorded even though the number inputted is technically the minimum as well, this is due to the if statement causing the loop to reiterate once it founds out if the number is the max or min and in this case the number will always be the max so the test never runs again. How can i fix this?
#include <iostream>
using namespace std;
int main()
{
int input;
int tmp;
int counter = 1;
int max_num=0;
int min_num;
//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 = 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;
}

int max_num = -1;
int min_num = -1
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++; => This operation is carried out in every case. Why not just do it once?
}
// if larger than previous number it becomes max number
// Else statement not needed here, What if user inputs only one number. It will be both max and min
if (input > max_num){
max_num = input;
//counter++;
}
//continue loop if number isn't bigger than max or smaller than min
counter++;
}

In the statement if (input < min_num) the value of min_num is undefined, because you did not assign any value to min_num. You want to #include <climits> and initialize min_num to INT_MAX.

The problem arises as a result of default value of int min_num which is 0 becuase min_num is a global variable. Add this lines of code just before while loop and it should work fine.
if(input >= 1)
cin >> min_num;
tmp = input-1;
if((input==1)&&(min_num > max_num)){
max_num = min_num;
min_num = 0;
}
If only one integer is added the result is reversed. So we need an error check. By the way the code is not good.

Try this code
#include <iostream>
#include <limits>
using namespace std;
int main() {
int n, input, max_num, min_num;
max_num = numeric_limits<int>::min();
min_num = numeric_limits<int>::max();
cin >> n;
while (n--) {
cin >> input;
max_num = max(max_num, input);
min_num = min(min_num, input);
}
cout << "min: " << min_num << "\nmax: " << max_num << endl;
return 0;
}
Input
2
34
65
Output
min: 34
max: 65

Related

Collect positive floats & output the average when negative integer is input

I'm trying to write a program that reads in positive float numbers from the user and then when the user's is a negative number, gives the average of the numbers, excluding the negative.
#include <iostream>
using namespace std;
int main() {
float av_number, total = 0, input;
do {
for (int i = 1; i >= 1; i = ++i) {
cout << "Please input a number: ";
cin >> input;
total = total += input;
av_number = total / i;
cout << av_number << endl;
break;
}
} while (input >= 0);
cout << av_number << endl;
}
When I run this, the program simply adds the inputs together on each line, and then subtracts my final negative input before closing the program.
If I were to guess, It's likely a logical confliction within my sequence of do & for loops, but I'm unable to identify the issue. I may have also misused i in some fashion, but I'm not certain precisely how.
Any help would be appreciated as I'm still learning, Cheers!
you don't need the for loop, you just need some iterator to count the number of entered numbers, so you can delete that for loop and use a counter variable instead.
also, you are breaking in the loop without checking if the input < 0, so you can write this
if (input < 0)
break;
also, you shouldn't calculate av_number = total / counter; except only after the end of the big while loop
it's total += input; not total = total += input;
writing while (input >= 0) wouldn't make sense as long as you are breaking inside the loop when input < 0, so you can write while (true); instead
and this is the code edited:
#include <iostream>
using namespace std;
int main() {
float av_number = 1.0, total = 1, input = 1.0;
int counter = 0;
do {
cout << "Please input a number: ";
cin >> input;
if (input < 0)
break;
counter++;
total += input;
} while (true);
av_number = total / counter;
cout << av_number << endl;
}
and this is the output:
Please input a number: 5
Please input a number: 12
Please input a number: 7
Please input a number: -2
8
P.S : read more about Why is "using namespace std;" considered bad practice?
You should move the calculation of the average value out of the loop where the adding takes place and only add non-negative values to total.
#include <iostream>
int main() {
float total = 0.f;
int i = 0;
// loop for as long as the user successfully enters a non-negative value:
for (float input; std::cout << "Please input a number: " &&
std::cin >> input &&
!(input < 0.f); ++i)
{
// now `input` is non-negative
total += input; // and only sum it up here, no average calculation
}
if (i > 0) { // avoid division by zero
// finally calculate the average:
float av_number = total / i;
std::cout << av_number << '\n';
}
}
The condition for the loop is that std::cout << "Please input a number: " succeeds and that std::cin >> input succeeds and that input is not less than zero.

How do I determine the highest and lowest value using do while loops

I am currently stuck in my homework and the problem is that I need to create a program that will ask for 5 integer numbers from which I should determine the highest and lowest value. I am quite confused as of now, and my initial code is this:
#include<iostream>
using namespace std;
int main(){
int num1,num2,num3,num4,num5,min=0,max=0;
cout << " Enter 1st number : ";
cin >> num1;
cout << " Enter 2nd number : ";
cin >> num2;
cout << " Enter 3rd number : ";
cin >> num3;
cout << " Enter 4th number : ";
cin >> num4;
cout << " Enter 5th number : ";
cin >> num5;
do{
if(num1<num2 && num1<num3 && num1<num4 && num1<num5 ){
max = num1;}
if(num2<num1 && num2<num3 && num2<num4 && num2<num5 ){
max = num2;}
if(num3<num1 && num3<num2 && num3<num4 && num3<num5 ){
max = num3;}
if(num4<num1 && num4<num3 && num4<num2 && num4<num5 ){
max = num4;}
if(num5<num1 && num5<num3 && num5<num4 && num5<num2 ){
max = num2;}
}while(max>0);
cout << " The highest number is : " <<max;
return 0;
}
Any help would be appreciated. Thanks in advance!
You should store your numbers into a std::vector<int> or std::array and then use the std::minmax_element algorithm to obtain the largest and smallest number.
If you are allowed to use std::max and std::min, you can use:
max = std::max({num1, num2, num3, num4, num5});
min = std::min({num1, num2, num3, num4, num5});
to simplify the code in the loop.
This would be my solution without using arrays.
I'd suggest you to try it yourself before. You don't learn when you just copy code.
#include <iostream>
int main() {
int i=0, num, min=INT_MAX, max=INT_MIN;
do {
std::cout << "Enter number: ";
std::cin >> num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
i++;
} while (i < 5);
std::cout << "The max number is: " << max << std::endl;
std::cout << "The min number is: " << min << std::endl;
return 0;
}
If you don't need to remember, you can loop for e.g. 5 times, then have a comparison before asking the next number.
so generally (idea, write it yourself and learn):
for (5 times)
ask user input, save as input
if largest number is null, then equal to input
else if largest number is smaller, then set input equal to largest number
Continue for loop times.
Rather than compare all the numbers each time. Simply compare your current smallest against the numbers in sequence.
int data[5];
// read numbers into data.
int min = data[0]; // Guess that number 0 is the smallst number.
// Now check if the guess is correct and update if you are wrong.
for(int loop = 0; loop < 5; ++loop)
{
// check if data[loop] is smaller than your current guess.
// if it is smaller than update your guess.
// when you have checked all the values exit the loop.
}
std::cout << "Smallest: " << min << "\n";
There is no need to use a loop to do this you can do that without it else if it's necessary to use a loop you must use an array or some other data structure

Calculating the minimum and maximum values from a user-generated list

I am writing code for an assignment that wants me to make a program that asks the user for the amount of integers they'd like to input then it accepts each input while testing if the value is the max value or the minimum.
The program runs fine but for some reason will stop and show me the min and max number when I have entered in 1 integer less than the original input.
Examples of the problem I am having:
If I input 5 for the first value, it asks me to enter 5 integers.
After entering 4 numbers, 1 2 3 and 4.
It tells me the max is 4 and min is 1.
It prevents me from entering in the 5th integer.
Additionally,
If I input 5 for the first value, it asks me to enter 5 integers.
If I enter a negative number, like -1, the input allowed to me is further
shortened.
If I enter -1, 2, 3 then the output is min: 2 and max: 3
I have two main questions:
What adjustments do I need to make to my code so that I can properly
enter in the number of integers initially asked for?
What adjustments need to be made in order for me to be able to enter
negative integers so they are outputted correctly?
The code:
#include <iostream>
using namespace std;
int main()
{
int input;
int tmp;
int counter = 1;
int max_num = 0;
int min_num;
// 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++;
} else { // continue loop if number isn't bigger than max or smaller than min
counter++;
}
}
// display the max and min
cout << "min: " << min_num << endl;
cout << "max: " << max_num << endl;
return 0;
}

How to use a while loop with an array?

I've created a program that allows the user to enter 10 grades. I've used a while loop to store grades in the array, but if the user only has 5 grades to input, he can type done to exit the program.
After the loop has finished, it will then calculate and display. the highest grade, lowest grade, and the average grade within the array
Unfortunately, when the user types done, the program will display the rest of the grade lines that were not entered.
Can you help me find out how to stop the while loop from displaying the rest of unentered grades of the loop?
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int grade[SIZE];
int count = 0;
int lowestGrade;
int highestGrade;
bool done = false;
cout << "This program is limited to entering up to 10 grades." << endl;
while ( grade[count] != done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
}
//LOWEST GRADE
lowestGrade = grade[0];
for (count = 0; count < SIZE; count++)
if (grade[count] < lowestGrade)
{
lowestGrade = grade[count];
}
//HIGHEST GRADE
highestGrade = grade[0];
for (count = 0; count < SIZE; count++)
{
if (grade[count] > highestGrade)
{
highestGrade = grade[count];
}
}
//AVERAGE GRADE
double total = 0;
double average;
for (int count = 0; count < SIZE; count++)
total += grade[count];
average = (total / SIZE);
cout << endl;
cout << "Your highest grade is: " << highestGrade << endl;
cout << "Your lowest grade is: " << lowestGrade << endl;
cout << "Your average grade is: " << average << endl;
system("pause");
return 0;
}
Here are two problems with your code.
First:
....
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
....
The code above will attepmpt to read word "done" into integer variable, producing 0. Not what you want to do!
Second:
...
for (count = 0; count < SIZE; count++)
...
Code above will try to iterate over all possible elements (SIZE). However, you might have enetered less than that! You need to use count calculated in the previous loop as your boundary (and of course, use a different name for control variable in the loop).
There are a couple of things to unpack here.
Basically, the input you are retrieving is a char * and the >> operator is casting that to an int to fit into your array of grades.
Next what you are checking with grade[count] != done is if the integer in "grade" at the id "count" is not equal to the bool false. This will always return true in this case.
For your use case what you want to be checking is if your input is equal to the char * "done"
This cannot be happening in the predicate of the while loop because your grade array stores only int.
Therefore the simplest solution to the problem in my opinion, is to check whether the input is equal to "done".
If it is you want to set the done boolean to true
Otherwise we can try to cast it to an int and store that in the grades array.
Here is the revised loop:
while (!done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string input = "";
cin >> input;
if (input == "done")
{
done = true;
}
else
{
grade[count] = stoi(input);
}
count++;
}
The following is somewhat outside the scope of the question, but an additionnal advantage to using stoi() is that it ignores input that is not a number, which will shield against someone entering invalid input like "potato". This is why I immediately cast the input into a string.
Use another variable to store the amount ofgrades the user entered. You also cannot store a string in your integer array:
std::string input = "";
while(count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
getline(cin, input);
if(input == "done")
break;
try
{
grade[count] = std::stoi(input);
count++;
}
catch(std::invalid_argument)
{
cout << "not a valid number\n";
}
}
int actualsize = count;
and then use this variable to abort your for loops:
for (int i = 0; i < actualsize; i++)
There are two simple ways to solve your problem:
You can read strings instead of integers and in case the read string is "done", break the loop, else, convert the read string to an integer, something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string temp;
cin >> temp;
if(temp == "done") {
break;
} else {
grade[count] = stoi(temp);
count++;
total_count = count;
}
}
// rest of the code
```
If you don't want to use strings, then, assuming grades will be non-negative, you can stop reading input when the user types a negative number, say "-1". So, you will need to do something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or -1 to quit: ";
int temp;
cin >> temp;
if(temp == -1) {
break;
} else {
grade[count] = temp;
count++;
total_count = count;
}
}
// rest of the code
```
Also, don't forget to replace SIZE by total_count in rest of the loops i.e. the ones computing 'LOWEST GRADE', 'HIGHEST GRADE' and 'AVERAGE GRADE'.
NOTE: You will have to do #include <string> at the top as well, if you use the first option.

How do i convert a while loop to a for loop in C++?

while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
Above is the while loop I had for my original program and below is my attempt at converting that to a for loop.
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
total = total + grade;
}
This is a simple program to get grade averages. Here is the entire program:
#include <iostream>
#include <fstream>
using namespace std;
int average (int a, int b);
int main()
{
// Declare variable inFile
ifstream inFile;
// Declare variables
int grade, counter, total;
// Declare and initialize sum
int sum = 0;
// Open file
inFile.open("input9.txt");
// Check if the file was opened
if (!inFile)
{
cout << "Input file not found" << endl;
return 1;
}
// Prompt the user to enter the number of grades to process.
cout << "Please enter the number of grades to process: " << endl << endl;
cin >> total;
// Check if the value entered is outside the range (1…100).
if (total < 1 || total > 100)
{
cout << "This number is out of range!" << endl;
return 1;
}
// Set counter to 0.
counter = 0;
// While (counter is less than total)
// Get the value from the file and store it in grade.
// Accumulate its value in sum.
// Increment the counter.
while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
// Print message followed by the value returned by the function average (sum,total).
cout << "The average is: " << average(sum,total) << endl << endl;
inFile.close();
return 0;
}
int average(int a, int b)
{
return static_cast <int> (a) /(static_cast <int> (b));
}
I tried to convert while loop to a for loop but when I debug I get an infinite loop. There are no errors when I build my solution. I'm not sure what other details to add.
You are increasing the value of total in the for loop. Hence, counter never reached total if you keep entering positive values.
Perhaps you meant to use sum instead of total in the loop.
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
sum = sum + grade;
}
You are using wrong variables names, value of total is increasing in the for loop so it becomes an infinite loop, use a different variable names for storing sum and for for-loop termination condition.