Home > front end >  How to check if a number is within an interval without using the boolean operators in C
How to check if a number is within an interval without using the boolean operators in C

Time:01-19

I'm just getting started with programming and this is my first post on this site, hopefully the start of a long and productive journey!

I'm studying C from the Deitel's book and one of the exercises of the control flow 1 (chapter 4 - if, if...else, while) is asking me, among other things, to input a number and check that it's no smaller than 1 and no greater than 20 (in this case an error message has to be displayed to the user until a valid number is entered). In order to make it work I had to use the || operator as follows:

while (number < 1 || number > 20)
{
   cout << "Wrong number, insert a valid number";
   cin >> number;
}

Problem is, the book has yet to introduce boolean operators (||, && ...)!

So my question is, is it possible to operate such a control on a value without using the "or" operator and only using the if, if...else and while, nested if necessary? Thank you in advance.

CodePudding user response:

On approach would be nested ifs.

bool ok = false;
if (number >= 1) {
    if (number <= 20) {
        ok = true;
    }
}
if (!ok) {
    // print error
}

So you assume the number is bad. If it's < 1 then it skips the first if and the number stays bad. If the number is > 1 then it tries the second condition and only sets ok to true is that is true i.e. both conditions are true. You can wrap this in the necessary while look yourself:

bool ok = false;
while(!ok)
{
    // input number
    // check number
    // optional error
}

CodePudding user response:

You could possibly use arithmetic for this. But then it is a trick

do
{
   cout << "Insert a valid number";
   cin >> number;
}
while ( (number-1)*(20-number)<0 );

Another approach is to test in separate

while ( true ) 
{
   cout << "Insert a valid number";
   cin >> number;
   if ( number < 1 ) continue;
   if ( number > 20 ) continue;
   break;
}

CodePudding user response:

Well, you could always use std::clamp()

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
   int low = 10, high = 20;
   int number;

   while ( true )
   {
      cout << "Enter a number between " << low << " and " << high << " inclusive : ";
      cin >> number;
      if ( clamp( number, low, high ) == number ) break;
      cout << "Invalid number\n\n";
   }
}

CodePudding user response:

You can write a function already (see main function) so write one which checks if the number is within an interval and returns 1 if it is and 0 otherwise. This can be done with using only if and return statements in a function. And put a function call in while statement.

  • Related