Dart

9. If else

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:

  1. Enter 3 numbers and find which one is the largest.
  2. Enter marks of 5 subjects, calculate total, percentage, and determine the grade.
  3. Enter prices of 4 articles. Apply discount: if total > 10,000 → 10%, if > 5,000 → 5%, if > 3,000 → 3%, otherwise no discount.
  4. Write a program to print the result (Pass/Fail) based on a student’s marks.

Leave a Reply

Your email address will not be published. Required fields are marked *