Menu
Coddy logo textTech

The 'if' Statement

Part of the Fundamentals section of Coddy's Dart journey — lesson 31 of 94.

The if statement in Dart evaluates a boolean condition and executes code only when that condition is true.

if (condition) {
  // Code to execute when condition is true
}

Example checking if a number is positive:

void main() {
  int number = 10;
  
  if (number > 0) {
    print('The number is positive');
  }
}

You can use any boolean expression as a condition:

void main() {
  int age = 20;
  bool hasLicense = true;
  
  if (age >= 18 && hasLicense) {
    print('You can drive');
  }
}
challenge icon

Challenge

Easy

Create a program that determines if a student has passed or failed an exam based on their score:

  1. Declare an integer variable named examScore with a value of 68
  2. Declare a constant integer named passingGrade with a value of 70
  3. Use an if statement to check if the student's score is less than the passing grade
  4. If the score is less than the passing grade, print: Exam status: Failed. You need to improve by X points. (where X is the number of points needed to reach the passing grade)
  5. If the score is equal to or greater than the passing grade, print: Exam status: Passed. Good job!

Your output should match the expected format exactly.

Cheat sheet

The if statement in Dart evaluates a boolean condition and executes code only when that condition is true:

if (condition) {
  // Code to execute when condition is true
}

Example with a simple condition:

int number = 10;

if (number > 0) {
  print('The number is positive');
}

You can use complex boolean expressions with logical operators:

int age = 20;
bool hasLicense = true;

if (age >= 18 && hasLicense) {
  print('You can drive');
}

Try it yourself

void main() {
  // Declare your variables here
  int examScore = _;
  const int passingGrade = _;
  
  // Write your if statement here
  if (_) {
    int pointsNeeded = _;
    print("Exam status: Failed. You need to improve by $pointsNeeded points.");
  } else {
    print("Exam status: Passed. Good job!");
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals