0

I am trying to practice for arrays and was trying to write a simple code for voting system. User inputs the number for what party theywant to vote and in the end number of votes got by the parties displayed. I am getting the right output for votecounter[1] and votecounter[3] but illogical 6 or 8 digits numbers for votecounter[2] and votecounter[4]. Can u point outthe bug in my code?

#include <stdio.h>
#include <cs50.h>

int main (void)
{
    int i, votecounter [5], vote;

    for (i = 1; i <= 4; i++)
        {
            votecounter[i] = 0;

            printf ("Cast your vote for the party you want by typing in their number.\n");
                printf ("1.PTI\n");
            printf ("2.PPP\n");
            printf ("3.MQM\n");
            printf ("4.PMLN\n");

            for ( i = 1; i <=15; i++)
                {
                    vote = GetInt();

                    if (vote < 1 || vote > 4)
                        {
                            printf ("invalid vote.\n");
                        }
                    else
                        votecounter [vote]++;

                }
        }
    printf ("The number of votes for PTI is %i.\n", votecounter[1]);
    printf("The number of votes for PPP is %i.\n", votecounter[2]);
    printf ("The number of votes for MQM is %i.\n", votecounter[3]);
    printf ("The number of votes for PMLN is %i.\n", votecounter[4]);
    return 0;
}
1

you have your second for loop nested inside the first one which means that the second for loop is not executed after votecounter[1] to votecounter[4] are initialized to 0, but rather it's executed once after each element of votecounter is initialized to 0.

so in the first iteration, votecounter[1] is set to 0 and you're taking 15 votes. so at this point if a vote vote is > 1, vote[vote] is incremented even though it hasn't been initialized yet (it contains a garbage value). hence, you're not getting the correct results.

0
  1. A bit puzzled as to why you are using 2 FOR loops here - are you wanting to canvass 15 votes? If so you could do away with the first (outer) FOR loop altogether. Put the printf's which display the options inside the second (inner) FOR loop if you want them to display every time you're asking for input.

  2. You have used the same variable 'i' for both FOR loops - one inside the other. Can only imagine the chaos! If you must use 2 nested FOR loops (see point 1 above) then change the label to 'j' (or whatever) in the second (inner) loop.

1
  • Still having the same error when doing it by 2 different named variables – Furrukh Jamal Jun 11 '15 at 10:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .