Count Occurrences in C

Level 3163 keystrokes

Counts how many times a specific value appears in an array.

C code

// The value 2 appears three times here
1int arr[] = {1, 2, 2, 3, 2, 4};
// count starts at 0; target is the value to look for
2int count = 0, target = 2;
// Check all 6 elements; the body is the if on the next line
3for (int i = 0; i < 6; i++)
// Add 1 for each match (indexes 1, 2 and 4)
4 if (arr[i] == target) count++;
// Print 2 appears 3 times
5printf("%d appears %d times", target, count);

Output

2 appears 3 times
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.

  • ,× 8
  • ;× 6
  • =× 6
  • +× 4
  • (× 3
  • )× 3
  • "× 2
  • [× 2
  • ]× 2
  • %× 2

More C examples at level 3

← C typing practice