๐ŸŽ“ A1Learner
๐Ÿ”

C++ If and Else

An if statement runs a block of code only when a test gives true. That test is called a condition, and an else block runs when the condition gives false.

An if block

The condition is true here, because 20 is at least 18. The block runs and prints its line.

#include <iostream>

int main() {
  int age = 20;
  if (age >= 18) {
    std::cout << "Adult" << std::endl;
  }
  return 0;
}

Both branches in one program

The first test uses the value 20 and prints the if line. The second test uses the value 12 and prints the else line.

#include <iostream>

int main() {
  int first = 20;
  if (first >= 18) {
    std::cout << "First: Adult" << std::endl;
  } else {
    std::cout << "First: Child" << std::endl;
  }
  int second = 12;
  if (second >= 18) {
    std::cout << "Second: Adult" << std::endl;
  } else {
    std::cout << "Second: Child" << std::endl;
  }
  return 0;
}

An else if chain

The chain tests each condition in order. The score 85 reaches the second band and prints the grade B line.

#include <iostream>

int main() {
  int score = 85;
  if (score >= 90) {
    std::cout << "Grade: A" << std::endl;
  } else if (score >= 80) {
    std::cout << "Grade: B" << std::endl;
  } else if (score >= 70) {
    std::cout << "Grade: C" << std::endl;
  } else {
    std::cout << "Grade: F" << std::endl;
  }
  return 0;
}

Example

#include <iostream>

int main() {
  int age = 10;
  std::cout << "Age: " << age << std::endl;
  if (age < 12) {
    std::cout << "Ticket: 5" << std::endl;
  } else if (age >= 65) {
    std::cout << "Ticket: 8" << std::endl;
  } else {
    std::cout << "Ticket: 12" << std::endl;
  }
  return 0;
}

Key points

  • Use if to run a block when a condition is true.
  • A condition is a test that gives true or false.
  • Use else to run a block when the condition is false.
  • Use else if to test a new condition after a false one.
  • Only the first true branch in a chain runs.
  • Braces mark the start and the end of each block.

In this example, age holds 10. The first line prints the age with its label. The first condition tests whether 10 is under 12, and that test gives true. The ticket line therefore prints the child price of 5.

Note

The condition sits in parentheses after the word if.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

When does an else block run?