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 of code based on specified conditions. Here’s how you can use decision-making in Dart:

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 of code if the condition is true, and another block of code 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');
}

Enter two numbers and check which one is bigger

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');
  }
}

Exercise:

   1. Enter 3 numbers and check which one is larger.

    2. Enter 5 subject numbers and find the total, percentage and then find the grade

    3. Enter 4 articles price.. If the total is greater than 10,000 then 10% discount, if           greater than 5 then 5% 3000 then 3% or else no discount.

     4. Example – Write a program to print the result based on the student’s marks.

Leave a Reply

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