Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does switching the order of the if else statement result in an error?

Here is my code:

/* 
    Given a positive integer denoting n, do the following:
        - If 1 <= n <= 9, then print the lowercase English word corresponding to
        the number (e.g., one for 1, two for 2, etc.)
        - If n > 9, print 'Greater than 9'.
*/

#include <iostream>
#include <array>

using namespace std;

int main()
{
    string english_names [9] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int n;
    cin >> n;
    if(n>9) {
        cout << "Greater than 9";
    }
    else {
        cout << english_names[n-1];
    }
}

Using the above code works perfectly, however if I change the if else statement to:

if(1<=n<=9) {
        cout << english_names[n-1];
    }
    else {
        cout << "Greater than 9";
    }

Then the program no longer works properly. It works for an integer n where 1 <= n <= 9 however if the integer is greater than 9 the program does not work.

like image 899
chssu Avatar asked Feb 02 '26 22:02

chssu


2 Answers

This expression:

if(1 <= n <= 9)

is not checking if n is between 1 and 9. Instead the check actually becomes:

if( (1 <= n) <= 9)

which will be either 0 <= 9, or 1 <= 9, both of which are true.

You need to do:

if(1 <= n && n <= 9)
like image 196
cigien Avatar answered Feb 05 '26 11:02

cigien


Though if (1<=n<=9) ... seems to compile okay, but it does not mean the same thing to the compiler as it does to most humans.

It is seen as (1 <= n) <= 9.

1 <= n is true if n is greater or equal to 1. False otherwise. Which gives it the value one if true and zero if false. Both of those values are less than nine, so the overall expression is always true.

like image 26
wallyk Avatar answered Feb 05 '26 12:02

wallyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!