Homework Help Please! :)

Can someone take a look and give me some guidance? I am close but not sure how to handle this error. It compiles but crashes when executed. This weeks assignment is on parallel arrays. thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
 /***
Tricia Denning
CMPSC 205-2967, Spring 2014
Assignment 05
Page 447, Problem 26

Write a program that allows the user to enter the last names of five candidates
in a local election and the number of votes received by each candidate.  The program
should then output each candidate's name, the number of votes received, and the
percentage of the total votes received by the candidate. Your program should also output the
winner of the election.


**/
#include <iostream>
#include<iomanip>
#include<string>



using namespace std;

int main()
{//declare arrays
    string candidate[5];
    double votes[5];
    double percent[5];
    int count;
    int sum=0;
    int largest;

cout <<fixed <<showpoint;
    cout << setprecision(2);

    //initialize the arrays
    for(count =0; count < 5; count++){

            cout <<"Enter the candidate name and number of votes: "<<endl;
            cout<<"candidate:";
            cin>>candidate[count];
            cout<<"votes: ";
            cin>> votes[count];

    }//end for loop

//find the sum of the votes
    for(count =0; count <5; count++){
        sum = sum + votes[count];

    }
    //find the percent of votes
    for(count =0; count < 5; count ++){
        percent[count]= votes[count]/ sum;
    }
    //finds the largest number of votes
    int maxIndex = 0;
	for (count = 0; count < 5; count++)
	{
		if (votes[maxIndex] < votes[count])
			maxIndex = count;
	largest = votes[maxIndex];
	}

      //prints the array input
    for (count = 0; count < 5; count++){
        cout<<candidate[count]<< " "<<votes[count]<< " "<<percent[count]<< " "<<endl;
    }
 cout<<" total votes: " <<sum;
 cout<<" The winner of the election is: " <<candidate[largest]<<endl;



    return 0;
}
Last edited on
What sort of error do you get when it crashes? My bet would be out of bounds array somewhere in the code.
Last edited on
largest = votes[maxIndex]; is probably not what you want, especially since you later try to access candidate[largest].

I think your maxIndex should just be your largest (that is, you probably intended largest to be what maxIndex is now).
So just change maxIndex to largest and delete line 61 and you should be good to go.

Alternatively, change largest from int to double and then just change line 69 from candidate[largest] to just largest.
You use a magic number(5) a lot during this program you should make it a constant variable called candidates or something similar.
[code[double votes[5];[/code] why is this a double?? You can have half a vote?
1
2
    for(count =0; count <5; count++){
        sum = sum + votes[count];
why not simply add them after inputting?

1
2
3
4
5
6
7
int sum = 0;
for(count = 0; count < 5; ++count) //also shouldn't use magic numbers
//5 should be number of candidates
{
    //read in the name and votes
    sum += votes;
}


as far as your error goes it should be candidate[maxIndex] on line 69.

@LDM largest is the most votes and maxIndex is the index of the largest vote as far as I can tell but, he never actually uses the largest(well correctly).
Last edited on
Hi Tricia,

largest is the number of votes, so on line 69 you go out of bounds with the array with this part : candidate[largest]

A couple of other things:

Avoid using magic numbers like 5 in your code, make them const variables instead:

const int ArraySize = 5;

Then use ArraySize throughout your code. That way, if you want to change the number of candidates, you can do it in one place only.

Always initialise your variables to something when you declare them, even if they get assigned to again later (like count). Having uninitialised variables is very often a huge source of problems.

This:

sum = sum + votes[count];

can be written more concisely as:

sum += votes[count];


This comment might seem pedantic, but one should always be wary of potential problems. So check for divide by zero, before doing this part:

percent[count]= votes[count]/ sum;

I know you just read in all the votes and calculated the sum just prior to this, but it is prudent to do a check regardless. Also it is a very good idea to check that reading the input actually worked. It is all about making the code as bullet proof as reasonably possible.

With your variable names, don't be afraid to make them longer if it adds more meaning, I might have had: SumOfVotes, LargestVote, CandidateName, CandidateVotes VotePerCentage

I imagine that in your future assignments, you will learn how to group these related variables together into a C style struct or a C++ class

The following might be too advanced for the stage you are at in your class - your teacher will realise you had help if you implement this, but I am mentioning it to help you out in the future.

It is a good idea to provide comments to say what the valid ranges of your variables are, and to do validation code to prove that they are before you use the values.

For example the number, largest & sum of the votes should always be positive, and if you knew there were 100,000 voters in an electorate, then the sum shouldn't be bigger than that, Percentages should add to 100.0. The last 2 are called post conditions, while the others are pre conditions.

Some checking can be enforced by the type of your variables: votes, largest and sum could be unsigned int .

I can see why you made votes double - because of the percentage calc has to be double. There is another way, it is possible to cast the value of a variable to another type, here is the C version which is easy to understand:


 
         VotePerCentage[count]= CandidateVotes[count]/ (double)SumOfVotes;


The C++ version which is better, looks like this:

 
         VotePerCentage[count]= CandidateVotes[count] / static_cast<double>(SumOfVotes);


Do the divide by zero check before casting to double, because comparing doubles to zero is not as easy as what one might expect.

Finally, avoid line 21: it brings in the entire standard namepace, which has thousands of variables & functions in it. The purpose of namspaces is to avoid clashes with variable & function names, but bringing in the whole thing actually increases the risk of clashes!! For example the std namespace has left, right, distance variables, so if you had this:

1
2
3
using namespace std;

double distance = 0.0; // immediate error std::distance is a very different thing 


So the answer there is to pefix std things with std::, as in std::cout

Really one should put their own variables & functions & classes into their own namespace, or more than one if it is warranted.

There you go - plenty to think about!! Hope all goes well, any questions - just ask :+D

Last edited on
Don't forget the std::count that he used TheIdeasMan.
Thank you!! Lots to think about. I am also trying to work on two classes at once..not sure bouncing between c++ and python is helping my brain any LOL
@giblit

Yeah, good work! I guess that further reinforces the idea that these std things can sneak up on one from anywhere !

I guess the good thing is that Tricia has learnt a really good thing early on in her programming career.

I just answered another post which had std::next in it.
Last edited on
Topic archived. No new replies allowed.