If, Else, Else-If in Dart
In Dart, decision-making is handled using conditional statements like if, else if, else, and the conditional operator ? :. These statements allow your code to execute different blocks based on specified conditions.
1. if Statement
The if statement executes a block of code if a specified condition is true:
void main() {
int number = 10;
if (number > 0) {
print('Number is positive');
}
}
2. if-else Statement
The if-else statement executes one block if the condition is true, and another if the condition is false:
void main() {
int number = -5;
if (number > 0) {
print('Number is positive');
} else {
print('Number is not positive');
}
}
3. else if Statement
The else if statement allows you to check multiple conditions:
void main() {
int number = 0;
if (number > 0) {
print('Number is positive');
} else if (number < 0) {
print('Number is negative');
} else {
print('Number is zero');
}
}
Example: Using Decision-Making to Determine Grade
void main() {
int score = 85;
String grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
print('Score: $score, Grade: $grade');
}
Compare Two Numbers
import 'dart:io';
void main() {
// Ask for the first number
print('Enter the first number:');
double? num1 = double.parse(stdin.readLineSync()!);
// Ask for the second number
print('Enter the second number:');
double? num2 = double.parse(stdin.readLineSync()!);
// Compare the numbers
if (num1 > num2) {
print('$num1 is larger than $num2');
} else if (num2 > num1) {
print('$num2 is larger than $num1');
} else {
print('Both numbers are equal');
}
}
Exercises
Try solving the following problems using Dart conditional statements:
- Enter 3 numbers and find which one is the largest.
- Enter marks of 5 subjects, calculate total, percentage, and determine the grade.
- Enter prices of 4 articles. Apply discount: if total > 10,000 → 10%, if > 5,000 → 5%, if > 3,000 → 3%, otherwise no discount.
- Write a program to print the result (Pass/Fail) based on a student’s marks.
