Dart -2 Relational Operators and Logical Operators, If else, Ternary, and Switch

🔍 Dart Conditional Statements: if, else, ternary & switch

In this lesson, you’ll learn how to make decisions in Dart using conditions. We start by understanding relational and logical operators.

📊 Relational Operators in Dart

Operator Description Example (a=5, b=3) Result
==Equal toa == bfalse
!=Not equal toa != btrue
>Greater thana > btrue
<Less thana < bfalse
>=Greater than or equal toa >= btrue
<=Less than or equal toa <= bfalse

🧠 Logical Operators

Operator Description Example Result
&&Logical AND(a > 2 && b < 5)true
||Logical OR(a > 10 || b < 5)true
!Logical NOT!(a == b)true

✅ if and else

Use if to test a condition. Use else to handle the opposite case.

void main() {
  int age = 20;

  if (age >= 18) {
    print("You are an adult.");
  } else {
    print("You are a minor.");
  }
}

📝 else if ladder

Use else if when you want to test multiple conditions.

void main() {
  int marks = 75;

  if (marks >= 90) {
    print("Grade: A+");
  } else if (marks >= 70) {
    print("Grade: B");
  } else {
    print("Grade: C");
  }
}

⚡ Ternary Operator

Shorthand for simple if-else.

void main() {
  int age = 17;
  String result = (age >= 18) ? "Adult" : "Minor";
  print(result);
}

🔀 switch-case Statement

Use switch when you have multiple fixed choices.

void main() {
  String day = "Tuesday";

  switch (day) {
    case "Monday":
      print("Start of the week");
      break;
    case "Tuesday":
      print("Second day");
      break;
    case "Friday":
      print("Almost weekend!");
      break;
    default:
      print("Normal day");
  }
}

🎯 Practice Assignments

  1. Check if a number is even or odd.
  2. Check if a number is positive, negative, or zero.
  3. Take 3 subject marks and print the grade using if-else if.
  4. Write a program using a ternary operator to check voter eligibility (age ≥ 18).
  5. Write a calculator using switch for +, -, *, / operators.

🧪 Try these on DartPad.dev or your Dart console!

Post a Comment

0 Comments

Me