Maximum value in C++

Level 3136 keystrokes

Takes the first element as the current maximum and replaces it whenever a larger value is found, then prints 9.

C++ code

1vector<int> nums = {3, 7, 2, 9, 5};
// Starts from the first element rather than 0, so it also works with negative numbers
2int maxVal = nums[0];
// Checks every element
3for (int n : nums) {
// A larger value becomes the new maximum
4 if (n > maxVal) {
5 maxVal = n;
6 }
7}
// Prints 9
8cout << maxVal << endl;

Output

9
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.

  • <× 5
  • ,× 4
  • ;× 4
  • {× 3
  • }× 3
  • =× 3
  • (× 2
  • )× 2
  • >× 2
  • :× 1

More C++ examples at level 3

← C++ typing practice