WeCodeAcademy

C++ If...Else and Switch

ExampleC++
#include <iostream>
using namespace std;

int main() {
  int score = 72;
  if (score >= 90) cout << "A" << endl;
  else if (score >= 70) cout << "B" << endl;
  else cout << "C" << endl;

  int day = 3;
  switch (day) {
    case 1: cout << "Monday" << endl; break;
    case 3: cout << "Wednesday" << endl; break;
    default: cout << "Other" << endl;
  }
  cout << ((score >= 50) ? "pass" : "fail") << endl;
  return 0;
}
Output
B
Wednesday
pass

Conditions work as in C. The ternary operator a ? b : c is a short if/else.

Quick check

What does (5 > 3) ? "yes" : "no" give?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.