Ternary Operator in C++

Level 288 keystrokes

Uses the ternary operator to pick "Pass" or "Fail" depending on whether score (85) is at least 60, and prints Pass.

C++ code

// Stores the score 85 in the int variable score
1int score = 85;
// condition ? a : b gives a if the condition is true, otherwise b
// 85 >= 60 is true, so result becomes "Pass"
2string result = (score >= 60) ? "Pass" : "Fail";
// Prints the chosen string, Pass
3cout << result << endl;

Output

Pass
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • "× 4
  • <× 4
  • ;× 3
  • =× 3
  • :× 1
  • ?× 1
  • (× 1
  • )× 1
  • >× 1

More C++ examples at level 2

← C++ typing practice