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 .
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];
}
}
+ 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.
+ 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);
+ 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;
}
+ 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...
0
thanks a lot. But i am using C++
0
thanks guys
0
please can anyone help modify my code?
it's giving me some technical issues