Ternary Absolute Value in C

Level 278 keystrokes

Uses the ternary operator to compute the absolute value of -7 by negating it when it is below zero, and prints "Absolute: 7".

C code

// Starts with a negative number, -7
1int num = -7;
// If num is negative, -num flips its sign; otherwise num is kept. -7 < 0, so abs = 7
2int abs = (num < 0) ? -num : num;
// Prints "Absolute: 7"
3printf("Absolute: %d\n", abs);

Output

Absolute: 7
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.

  • ;× 3
  • -× 2
  • :× 2
  • "× 2
  • (× 2
  • )× 2
  • =× 2
  • ,× 1
  • ?× 1
  • \× 1

More C examples at level 2

← C typing practice