CodeBlanks Logo Icon CodeBlanks

The if statement

Learn how to check a condition with if.

The if statement

In Dart you check a condition with if. If the condition is true the block runs; if false it is skipped. The form is if (condition) { ... }.

For example int score = 85; if (score >= 50) { print("passed"); } prints passed because score >= 50 is true. The condition goes inside parentheses; the block inside curly braces.

Condition and block

After if a condition is written inside parentheses. The condition must be a bool expression: true or false. Comparison operators (==, !=, <, >, <=, >=) or logical operators (&&, ||, !) produce one.

When the condition is true the block inside the curly braces runs. For single-line blocks the braces are technically optional but always recommended for readability.

Practice Print passed/failed

Declare an int variable score with the value 85. Check the condition with if (score >= 50); when true print print("passed");. The output on a single line must be passed.

Starter code

main.dart
// Declare score, check 50 and above with if, print passed

Sample solution

main.dart
int score = 85;
if (score >= 50) {
  print("passed");
}

Expected output

passed

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a correct if form?

main.dart
int x = 10;
  • if (x > 5) print(x);)
  • if x > 5 { print(x); }
  • if (x > 5) { print(x); } Correct answer
  • if [x > 5] { print(x); }

Explanation: The condition goes in parentheses; the block in curly braces.

2 Complete the if condition

Question
int score = 85;
if (____) {
  print("passed");
}
Answer
int score = 85;
if (score >= 50) {
  print("passed");
}

Explanation: score >= 50 is true for 50 and above.

3 Match each part to its job

Term Meaning
if Condition statement
(cond) Condition in parens
{ ... } Block
score >= 50 Comparison example

All lessons in Beginner