Ternary in printf in C

Level 4155 keystrokes

Uses ternary operator within printf to conditionally display pass or fail status.

C code

// Array of test scores
1int scores[] = {85, 42, 91, 68, 55};
// Loop through all scores
2for (int i = 0; i < 5; i++) {
// One printf call with its arguments split across lines
3 printf("Score %d: %d - %s\n",
// Score number (1-indexed)
4 i + 1,
// Actual score value
5 scores[i],
// Ternary picks the string for %s: "Pass" if >= 60, else "Fail"
6 scores[i] >= 60 ? "Pass" : "Fail");
7}

Output

Score 1: 85 - Pass
Score 2: 42 - Fail
Score 3: 91 - Pass
Score 4: 68 - Pass
Score 5: 55 - Fail
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.

  • ,× 7
  • "× 6
  • ;× 4
  • [× 3
  • ]× 3
  • %× 3
  • +× 3
  • =× 3
  • :× 2
  • (× 2

More C examples at level 4

← C typing practice