Conditional Statements

  • + 0 comments

    Exercise was ment to teach conditional statements, so I used them all without anything else which would be (cheating in my opinion).

    I changed input type int n to unsigned int n because of given constraints. It says that there can't be negative numbers, so we should use a proper type.

    I have put Greater than 9 condition before all other because it is more likely that user will input greater number than 9. This way we prevent 9 statement checks which will make code execute faster in most cases.

    This is the code:

    		unsigned int n = stoi(ltrim(rtrim(n_temp)));
    
    		if (n > 9)
            cout << "Greater than 9";
        else if (n == 1)
            cout << "one";
        else if (n == 2)
            cout << "two";
        else if (n == 3)
            cout << "three";
        else if (n == 4)
            cout << "four";
        else if (n == 5)
            cout << "five";
        else if (n == 6)
            cout << "six";
        else if (n == 7)
            cout << "seven";
        else if (n == 8)
            cout << "eight";
        else
            cout << "nine";