Home > Mobile >  if the number is divisible by 3 print A and if it divisible by 5 print B and if it is divisible by b
if the number is divisible by 3 print A and if it divisible by 5 print B and if it is divisible by b

Time:07-14

if the number is divisible by 3 print A and if it is divisible by 5 print B and if it is divisible by both print C without using more than 2 if the statement (dart will be preferred)

CodePudding user response:

Yes you can do this in dart by using ternary operator (but this also works as if-else statement).

Example:

int a = 3;

a%3==0 && a%5==0?
 print("C"):
 a%5==0?
 print("B"):
 a%3==0?
 print("A"):
 print("not divisible by 3 and 5");

CodePudding user response:

Here's a solution:

void main(List<String> arguments) {
  test(1);
  test(2);
  test(3);
  test(4);
  test(5);
  test(10);
  test(15);
}

void test(int i) {
  final by5 = i % 5 == 0;
  final by3 = i % 3 == 0;
  switch ((by5 ? 2 : 0)   (by3 ? 1 : 0)) {
    case 1:
      print('$i: A');
      break;
    case 2:
      print('$i: B');
      break;
    case 3:
      print('$i: C');
      break;
    default:
      print('$i: Neither');
  }
}

Output:

1: Neither
2: Neither
3: A
4: Neither
5: B
10: B
15: C
  • Related