Home > Enterprise >  print true or false without using if else and any kind of of loop
print true or false without using if else and any kind of of loop

Time:12-12

My friend recently had an interview in which he was asked how do you print true or false if you were given input 0 or 1 by user and you have to do this without using if else or any kind of loop? Unfortunately he didn't asked for the solution from interviewer.I looked for the solution but not able to find related solution anywhere so i thought i should put this question here.

CodePudding user response:

I leave it open whether 0 represents true or 1.

System.out.println(input == 1);

This is Java; other languages are similar, though Java is slightly easier.

Here println does a toString on a boolean object.

This Java answer is the purest, a bit like (bool) (input == 1). Giving an actual boolean value. As the question did not state that string representations should be printed.

Otherwise one might assume that the conditional ternary operator ? : is a form of if else, so array indexing is needed.

print({"true", "false"}[input]);

In C one also could calculate every character numerically.

char s[6];
int tupni = 1 - input;
s[0] = (char) ('t' * input   'f' * tupni);
s[1] = (char) ('r' * input   'a' * tupni);
s[2] = (char) ('u' * input   'l' * tupni); 
s[3] = (char) ('e' * input   's' * tupni); 
s[4] = (char) ('\0' * input   'e' * tupni);
s[5] = '\0';

CodePudding user response:

You can use array. For example:

# i = user input

array[0] = "false"
array[1] = "true"

print(array[i])

You can also use dictionary.

CodePudding user response:

In Javascript,

// userInput is an integer
console.log(Boolean(userInput));

In Python,

# userInput must be an integer and not string
print(bool(userInput))

CodePudding user response:

Good day.

You can use conditional operators or also known as ternary operator for this case.

Syntax : (Condition? true_value: false_value); Example : (value > 500 ? 0 : 1);

  • Related