Ternary Operator Chain in C

Level 5256 keystrokes

Converts a score to a letter grade with a chain of ternary operators: each false branch holds the next test, from >= 90 for A down to F. For the scores 95, 82, 73, 65 and 45 it prints A, B, C, D and F.

C code

// Returns the letter grade as a string literal
1const char *getGrade(int score) {
// condition ? if_true : if_false; 90 or more gives "A"
// Each false branch holds the next ternary, so the tests run from top to bottom
2 return score >= 90 ? "A" :
// Below 90: 80 or more gives "B"
3 score >= 80 ? "B" :
// Below 80: 70 or more gives "C"
4 score >= 70 ? "C" :
// Below 70: 60 or more gives "D", anything lower "F"
5 score >= 60 ? "D" : "F";
6}
7
// One score for each grade
8int scores[] = {95, 82, 73, 65, 45};
9
// Visits the five scores
10for (int i = 0; i < 5; i++) {
// Prints Score 95: A, Score 82: B, Score 73: C, Score 65: D and Score 45: F
11 printf("Score %d: %s\n", scores[i], getGrade(scores[i]));
12}

Output

Score 95: A
Score 82: B
Score 73: C
Score 65: D
Score 45: F
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.

  • "× 12
  • ,× 6
  • =× 6
  • ;× 5
  • :× 5
  • ?× 4
  • (× 4
  • )× 4
  • >× 4
  • [× 3

More C examples at level 5

← C typing practice