الدرس 4 من 5

الشروط: if و else و switch

تقدمك في مسار Dart: 0/5
افتح على يوتيوب
if and else
void main() {
  var age = 20;
  if (age >= 18) {
    print('Accepted');
  } else {
    print('Rejected');
  }
}
else if (grades)
void main() {
  var score = 85;
  if (score >= 90) {
    print('A');
  } else if (score >= 80) {
    print('B');
  } else {
    print('C');
  }
}
Separate ifs (the bug) vs else if chain
void main() {
  var grade = 90;

  // Bug: separate ifs, the last else belongs to the last if only
  if (grade >= 85) print('Excellent');
  if (grade >= 75) print('Very good');
  else print('Invalid');

  // Correct: one chain, first true wins
  if (grade >= 85) {
    print('Excellent');
  } else if (grade >= 75) {
    print('Very good');
  } else {
    print('Invalid');
  }
}
&& and ||
void main() {
  var age = 20;
  var hasId = true;
  if (age >= 18 && hasId) {
    print('Enter');
  }

  var isAdmin = false;
  var isOwner = true;
  if (isAdmin || isOwner) {
    print('Allowed');
  }
}
Nested if
void main() {
  var age = 20;
  var hasTicket = true;
  if (age >= 18) {
    if (hasTicket) {
      print('Welcome');
    } else {
      print('Buy ticket');
    }
  }
}
switch
void main() {
  var day = 3;
  switch (day) {
    case 1:
      print('Monday');
      break;
    case 3:
      print('Wednesday');
      break;
    default:
      print('Other day');
  }
}
Ternary (one-line if)
void main() {
  var age = 20;
  var msg = age >= 18 ? 'Adult' : 'Minor';
  print(msg);
}
Max of 3 numbers
void main() {
  var a = 10, b = 15, c = 20;
  if (a >= b && a >= c) {
    print(a);
  } else if (b >= a && b >= c) {
    print(b);
  } else {
    print(c);
  }
}
Read a number from the user
import 'dart:io';

void main() {
  print('Enter a number:');
  int n = int.parse(stdin.readLineSync()!);
  if (n % 2 == 0) {
    print('Even');
  } else {
    print('Odd');
  }
}

التعليقات والأسئلة

اكتب اسمك الحقيقي وتعليقك أو سؤالك. مش محتاج حساب.