find the minimum value entered while using infinite loop c++

1.2k views Asked by At

My task is to find the minimum number between n input values that the user should enter in an infinite loop until a certain number or character is entered to stop the loop.

The problem that I am facing is, I can't get the condition that tests the input to see which of the entered numbers is the smallest to work. Also, a second problem is, I want to end the loop with a char not an int, but I don't know if that is even possible.

I searched online but I can't find any answers.

Side note: I am new to C++. I am using Borland C++ v5.02.

#include <iostream>
#include <conio.h>

int I, min =0;
cout<<"Enter a number :";

do{
    cin >> I;
    if (I < min){
        if (I > 0){
            min = I;
        }
    }
}while (I > -1);

cout << min;
2

There are 2 answers

0
ToqaOs On BEST ANSWER

the problem with the code was with the header I couldn't find a one that was working with my compiler Borland v5.02 c++ but thanks to @JerryJeremiah he leads me to it.

also, I redeclared the min =INT_MAX; because I am using this code in a loop.

the code is working with me now.

#include <iostream>
#include <conio.h>
#include <limits.h>
int main()
{
     int I, min =INT_MAX;

     cout<<"Enter number of input :";

            do{
              cin>>I;
                if (I<min ){

                    if(I>0){
                         min =I;
                    }
                }

                }while(I>-1);

           cout<<min;
         min =INT_MAX;
         getch();
}
3
AudioBubble On

I solved your problem by using a try-catch block and stoi().

stoi() is used to convert a string into a number. If the number input is not convertible (meaning that a char is entered and the loop should break), const std::invalid_argument & e is catch and automatically break the loop.

#include <iostream>
using namespace std;

int main()
{
    int Min = INT_MAX; string I; int x;

    do
    {
        cout << "Enter a number or a char : ";

        cin >> I; 
        try
        {
            x = stoi(I);
            if (x < Min)
            {
                if (x > 0) {Min = x;}
            }
        }
        catch(const std::invalid_argument & e) {break;}
    }
    while(x > 0);

    cout << "Minimum positive number entered : " << Min;
}

Output:

Enter a number or a char : 10
Enter a number or a char : 8
Enter a number or a char : 5
Enter a number or a char : 7
Enter a number or a char : a
Minimum positive number entered : 5

As your code is a bit unclear, I changed both constraint to I>0, and you can easily modified this bit.

For the prolem with INT_MAX, maybe #include <climits> or #include <limits.h> will help, as specified here. If the problem persist, the workaround is to set Min to something high, for example 10^9.

*Note: Ran on Code::Blocks 20.03, Windows 10 64-bit.