C ยท Chapter 12 of 45

C If...Else

The if statement lets a program execute code only when a condition is true. You can extend it with else if to check further conditions, and else to provide a default action.

Conditions are placed inside parentheses after if, and the code to run is placed inside curly braces.

Syntax
if (condition) {
  // code
} else if (condition2) {
  // code
} else {
  // code
}

Basic if / else

An if statement runs a block only if its condition is true. Adding an else block provides an alternative action when the condition is false.

Chaining with else if

else if lets you test multiple conditions in sequence; the first one that's true runs, and the rest are skipped.

Example 1 (c)
#include <stdio.h>

int main() {
  int age = 20;
  if (age >= 18) {
    printf("Adult\n");
  } else {
    printf("Minor\n");
  }
  return 0;
}
Output
Adult

Since age is 20, the condition is true, so 'Adult' is printed.

Example 2 (c)
#include <stdio.h>

int main() {
  int score = 75;
  if (score >= 90) {
    printf("A\n");
  } else if (score >= 70) {
    printf("B\n");
  } else {
    printf("C\n");
  }
  return 0;
}
Output
B

The first true condition (score >= 70) determines which branch runs.

Key points

  • if runs code only when its condition is true.
  • else if chains additional conditions.
  • else provides a default when no condition is true.
  • Conditions must be enclosed in parentheses.
๐Ÿ’ก Note: Only one branch of an if/else if/else chain will ever execute.

๐Ÿ“ Quick Quiz

1. What happens if the if condition is false and there's no else?

2. How many branches of an if/else if/else chain can execute?

3. Where must the condition of an if statement be placed?