🔍 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 to | a == b | false |
!= | Not equal to | a != b | true |
> | Greater than | a > b | true |
< | Less than | a < b | false |
>= | Greater than or equal to | a >= b | true |
<= | Less than or equal to | a <= b | false |
🧠 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
- Check if a number is even or odd.
- Check if a number is positive, negative, or zero.
- Take 3 subject marks and print the grade using
if-else if
. - Write a program using a ternary operator to check voter eligibility (age ≥ 18).
- Write a calculator using
switch
for +, -, *, / operators.
🧪 Try these on DartPad.dev or your Dart console!
0 Comments