Last active
October 9, 2020 14:38
-
-
Save Frontear/8506588394df699ed536b99c296f736f to your computer and use it in GitHub Desktop.
Programming technique to compare objects inside of a loop without needing to loop twice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| // find the max value in an array | |
| int main() { | |
| int array[] = { 11, 100, 99, 95, 14, 62, 35, 74 }; | |
| auto j = 0u; | |
| for (auto i = 0u; i < 8; ++i) { | |
| if (array[j] < array[i]) { // controls comparisions to find the maximum value without needing to loop the same array twice | |
| j = i; | |
| } | |
| } | |
| // by this point, array[j] is guaranteed to be the maximum value | |
| std::cout << array[j] << std::endl; | |
| return 0; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can easily switch this to find the minimum value. It's not particularly complicated as a code piece, however you may find value in being reminded of this, as its not the most obvious solution