Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

what is wrong with the code ?? it says segmentation error

0 votes
asked Jul 14, 2020 by AVJ INFINITY (180 points)
#include <stdio.h>

#include <string.h>

#include <stdlib.h>

int main()

{

  int i, c = 0, n = 0, vote = 0, count[i], largest = 0;

  char name[i][25];

  char party[i][25];

  printf ("###### WELCOME TO ELECTION/VOTING#######\n");

  printf ("enter the number of candidates\n");

  scanf ("%d", &n);

  printf ("no. of candidates entered is %d", n);

  for (i = 0; i < n; i++)

    {

      printf ("enter candidate Name\n");

      scanf ("%s", name[i]);

      printf ("Candidate name entered is %s", name[i]);

      printf ("enter Representing party");

      scanf ("%s", party[i]);

    }

  printf

    ("enter the choice\n 1.caste the vote\n 2.find vote count\n 3.find the leading candidate\n");

  scanf ("%d", &c);

  switch (c)

    {

    case 1:

      printf ("The Candidates for the election are\n");

      for (i = 0; i < n; i++)

{

  printf ("%d ", i + 1);

  printf ("%s  ", name[i]);

  printf ("%s", party[i]);

}

      printf

("Please enter the serial number of the candidate to caste vote for your choosen candidate\n");

      scanf ("%d", &vote);

      vote--;

      for (i = 0; i < n; i++)

{

  if (i = vote)

    {

      count[i]++;

      break;

    }

}

      break;

    case 2:

      for (i = 0; i < n; i++)

{

  printf ("the no. of votes for\n %d. %s %s %d\n", i + 1, name[i],

  party[i], count[i]);

}

      break;

    case 3:

      for (i = 1; i < n; i++)

{

  largest = count[0];

  if (count[0] < count[i])

    {

      largest = count[i];

      printf ("the leading candidite is %s with %d votes\n", name[i],

      count[i]);

    }

}

      break;

    }

  return 0;

}

2 Answers

0 votes
answered Jul 15, 2020 by Peter Minarik (84,720 points)

Uninitialized Variables

The main problem here is that the variable i is not initialized. However, you use this to create arrays count, name, party. This leads to unexpected results.

Bugs in the code

Assignment vs comparison

if (i = vote)
This is a value assignment, you probably wanted to compare their values instead:
if (i == vote)

Calculating the leading candidate

This doesn't work as intended either. A correct implementation would be something like this:
int leading = 0;
for (int i = 1; i < n; i++)
{
    if (count[leading] < count[i])
        leading = i;
}
printf ("The leading candidite is %s from party %s with %d votes\n", name[leading], party[leading], count[leading]);

Further Notes:

Scanf Has Its Limitations

Using scanf does not allow you to enter strings with space in it. E.g. candidate name cannot be "John Smith" as scanf will stop at John and the next time you would call it in the code, it will keep reading the stdin starting from "Smith".

Also, if you're scanning for a number but the user enters a string instead, the next time scanf is called, it will have the input still unprocessed, and will try to process the string. This means, that if you are trying to read numbers in a loop, once entering a string will make the code run in an infinite loop.

Also, it is prone to run out of buffer, if the user enters more character than the buffer you try to store your data in.

Use Talkative Identifiers

It's worthwhile to use talkative variable names. It makes easier to understand the code. For instance, instead of n you could use numberOfCandidates or nCandidates.

Group Data Together

You could create a structure that would hold all the data for your candidate: name, party and number of votes:

typedef struct
{
    char name[25];
    char party[25];
    unsigned int voteCount;
} Candidate;

Divide Your Code Into Multiple Functions

It is a good practice not to write lengthy functions, instead separate codes that belong together into well defined functions. Such a function could be one that prints something on the screen asking for an input from the user then storing it into a variable.

Also, the 3 main functionality could potentially be separated into 3 functions (vote, see votes and find the leading candidate).

An Enhanced Solution

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    char name[25];
    char party[25];
    unsigned int voteCount;
    
} Candidate;

static bool scanUint(const char * message, unsigned int * value)
{
    static char buffer[255];
    printf("%s", message);
    fgets(buffer, sizeof(buffer), stdin);
    return (sscanf(buffer, "%ui", value) == 1);
}

static void scanString(const char * message, char * value)
{
    printf("%s", message);
    scanf("%s", value);
}

static void castVote(Candidate * candidates, unsigned int nCandidates)
{
    printf ("The Candidates for the election are:\n");
    for (unsigned int i = 0; i < nCandidates; i++)
        printf ("\t%d. %s [%s]\n", i + 1, candidates[i].name, candidates[i].party);

    int candidateId;
    scanUint("Please enter the ID of the candidate you wish to cast vote on: ", &candidateId);
    if (0 < candidateId && candidateId <= nCandidates)
    {
        candidates[candidateId - 1].voteCount++;
    }
    else
    {
        printf("Invalid candidate ID: %d\n", candidateId);
    }
}

static void listCandidates(const Candidate * candidates, unsigned int nCandidates)
{
    printf("%3s%26s%26s%11s\n", "ID", "Name", "Party", "Vote Count");
    static const unsigned int totalLength = 3 + 26 + 26 + 11;
    for (unsigned int i = 0; i < totalLength; i++)
        printf("-");
    
    printf("\n");
    for (unsigned int i = 0; i < nCandidates; i++)
        printf("%3d%26s%26s%11d\n", i + 1, candidates[i].name, candidates[i].party, candidates[i].voteCount);
}

static void findLeadingCandidate(const Candidate * candidates, unsigned int nCandidates)
{
    unsigned int leadingId = 0;
    for (unsigned int i = 1; i < nCandidates; i++)
    {
        if (candidates[leadingId].voteCount < candidates[i].voteCount)
            leadingId = i;
    }
    printf ("The leading candidate is %s from party %s with %d votes\n", candidates[leadingId].name, candidates[leadingId].party, candidates[leadingId].voteCount);
}

int main()
{
    //
    // Reading the input from the console
    //
    unsigned int nCandidates;
    printf("###### WELCOME TO ELECTION / VOTING ######\n\n");
    while (!scanUint("Enter the number of candidates: ", &nCandidates)) ; // Keep reading until the user enters a valid number
    printf("Entered: %i", nCandidates);

    // Now, `n` is initialized, we can use it to create the arrays.
    Candidate candidates[nCandidates];

    for (unsigned int i = 0; i < nCandidates; i++)
    {
        printf("Candidate #%d:\n", i + 1);
        scanString("\tName: ", candidates[i].name);
        scanString("\tParty: ", candidates[i].party);
        candidates[i].voteCount = 0;
    }

    //
    // Main Menu
    //
    bool keepRunning = true;
    while (keepRunning)
    {
        printf("###### MAIN MENU ######\n\n");
        printf("\t1. Cast a vote on a candidate\n");
        printf("\t2. List candidate details\n");
        printf("\t3. Find the leading candidate\n");
        printf("\t4. Exit\n\n");

        unsigned int choice;
        scanUint("? ", &choice);

        switch (choice)
        {
            case 1: castVote(candidates, nCandidates); break;
            case 2: listCandidates(candidates, nCandidates); break;
            case 3: findLeadingCandidate(candidates, nCandidates); break;
            case 4: keepRunning = false; break;
            default: printf("Unknown option: %d\n", choice);
        }
    }
    
    printf("Good bye!\n");
    return 0;
}
0 votes
answered Jul 16, 2020 by Ashish Kumar (230 points)
In the above problem while defining the size of array you are using i which is used for iteration in the for loop. I guess you wanted to create an array that could fit the details of all the candidates, so I would rather use n to define the size of array. Also the value of n is not known until the scan reads the value from the user. Hence the array size was different from you expectations. With minor modifications i was able to run the code.

int main()

{

  int i, c = 0, n = 0, vote = 0, count[i], largest = 0;

  printf ("###### WELCOME TO ELECTION/VOTING#######\n");

  printf ("enter the number of candidates\n");

  scanf ("%d", &n);

  printf ("no. of candidates entered is %d", n);
  
     char name[n][25];

     char party[n][25];
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...