0

I created an array of integers. How do i compare the integers in the array?

for example, a program that collects the votes of candidates in an election. I want to output the winner (highest votes ) , or how do i say "if THIS is greater than THAT"...where THIS and THAT are members of the same array .

1st Jul 2018, 3:04 PM
StEvEn
StEvEn - avatar
9 Answers
+ 4
//pseudocode in cpp is like // suppose array if your array max = array[0] for ( i = 1; i < lengthofarray ; i++) { if ( array[i] > max) { max = arr[i]; } }
1st Jul 2018, 3:26 PM
Nikhil Dhama
Nikhil Dhama - avatar
+ 4
Peter Parkers for this problem in the example, it will work, but what if your array contains all negative numbers and then you want the maximum number, then your script won't work, it will always show 0 as maximum.
1st Jul 2018, 3:47 PM
Nikhil Dhama
Nikhil Dhama - avatar
+ 3
You can use built-in function of language to find max value in array. for example (using Javascript) you can use Math.max() function returns the largest of zero or more numbers. var votes = [20, 14, 23, 15]; var maxVote = Math.max(...votes);
1st Jul 2018, 3:21 PM
Phurinat Puekkham
Phurinat Puekkham - avatar
+ 2
#include <iostream> using namespace std; int main() { int votes[] = {1, 2, 3, 9, 2, 0}; int votes_length = sizeof(votes)/sizeof(votes[0]); int max = 0; for (int i = 0; i < votes_length; i++) { if (votes[i] > max) { max = votes[i]; } } cout << max; return 0; }
1st Jul 2018, 3:43 PM
Peter Parkers
Peter Parkers - avatar
+ 1
I suggest to read better c++ tutorial because you maded some basic errors like declare a simple int and use it like an array, declare a var in a block and use it outside that block etc...
1st Jul 2018, 4:36 PM
KrOW
KrOW - avatar
0
thanks a lot. But i am using C++
1st Jul 2018, 3:22 PM
StEvEn
StEvEn - avatar
0
thanks guys
1st Jul 2018, 3:53 PM
StEvEn
StEvEn - avatar
0
please can anyone help modify my code? it's giving me some technical issues
1st Jul 2018, 4:27 PM
StEvEn
StEvEn - avatar