How do I make an array to find the largest portion of another array?

I am trying to find the candidate that received the largest amount of votes from the following file:

Johnson 5000
Miller 4000
Duffy 6000
Robinson 2500
Ashtony 1800

here is my code:

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;


int main()
{
   string candidates[6];
   double votes[6];
   double sum = 0.0;

   ifstream inFile("candidates.txt");

   for ( int i = 0; i < 6; ++i )
   {
	  
	  
      if ( inFile >> candidates[i] >> votes[i] )
      {
		sum = sum + votes[i];
      }
      else
      {
         break;
      }
   }
   cout << endl;
   
   cout << "Candidate      Votes      % of Total" << endl;

   cout << setprecision(0) << candidates[0] << setw(5) << "\t" << votes[0]
		<< setw(15) << setprecision(4) << ((votes[0] / sum) * 100) << endl;
   cout << setprecision(0) << candidates[1] << setw(5) << "\t" << votes[1]
		<< setw(15) << setprecision(4)<< ((votes[1] / sum) * 100) << endl;
   cout << setprecision(0) << candidates[2] << setw(5) << "\t" << votes[2]
		<< setw(15) << setprecision(4)<< ((votes[2] / sum) * 100) << endl;
   cout << setprecision(0) << candidates[3] << setw(5) << "\t" << votes[3]
		<< setw(15) << setprecision(4)<< ((votes[3] / sum) * 100) << endl;
   cout << setprecision(0) << candidates[4] << setw(5) << "\t" << votes[4]
		<< setw(15) << setprecision(3) << ((votes[4] / sum) * 100) << endl;

  
   cout << "\n" << endl;
   cout << setprecision(0) << "Total " << setw(5) << "\t" << sum 
	   << "\n" << endl;

}

Recommended Answers

All 3 Replies

using structs or classes would be easier and more elegant. What do
you think?

Keep track of the index of the highest value while taking input. Initialize to the first element:

int hi = 0;

When you find a new highest value, capture the index:

if ( votes[i] > votes[hi] )
         {
            hi = i;
         }

The winner is candidate[hi] .

By doing this, you have established a direct relationship between the two arrays:

//We can assume that 'votes[3]' corrosponds to 'candidates[3]', for example.
if ( inFile >> candidates[i] >> votes[i] )

So all you really need to do is extract the largest value from the votes[] array:

int index = 0;
int max = 0;

for(int i=0; i<6; i++)
{
     if(votes[i] > max)
     {
          max = votes[i];
          index = i;         
     }
}

cout << "The winner is " << candidates[index] << " with a winning vote count of " << votes[index];
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.