Question

Hello, I am having trouble with a problem in my C language class. I am trying...

Hello, I am having trouble with a problem in my C language class. I am trying to make a program with the following requirements:

1. Use #define to define MAX_SIZE1 as 20, and MAX_SIZE2 as 10

2. Use typedef to define the following struct type:

struct {

    char name[MAX_SIZE1];

    int scores[MAX_SIZE2];

}

3. The program accepts from the command line an integer n (<= 30) as the number of students in the class. You may assume that the input will always be valid.

4. Dynamically allocate memory for an array of n entries; each entry is a structure defined in step 2.

5. Store student name and randomly generate 10 scores in the range between 50 and 100 for each student in the dynamically allocated memory. You may declare and initialize an array of 30 names in an array, and use them as student names.

6. Use qsort to sort the array based on the total scores in the descending order.

7. Output the sorted grade book in a format of your choice.

8. Output the elapsed time of your program execution.

My problem is that I dont know how to use qsort to sort the array based on the total scores in descending order. Can you help me? I have pasted my current code below:

#include<stdio.h>
#include <time.h>
#include<stdlib.h>
#define MAX_SIZE1 20
#define MAX_SIZE2 10

typedef struct student
{
   char name[MAX_SIZE1];
   int score[MAX_SIZE2];
};

/*comparison function "comp()" start here*/
int comp(struct student *s1,struct student *s2)
{
   if(sum(s1)>sum(s2))
   return 1; /* if total score of s1 is greater than total score of s2 return 1 */
   else
   return 0;
}

int sum(struct student *s) /* it find the sum of grade */
{
   int i,su=0;
   for ( i=0;i<10;i++)
   su-su+s->score[1];
   return su;
}
/* comparison function "comp()" end */

int main()
{
   int n,i,j;
   time_t t;
   printf("Enter number of students: ");
   scanf("%d",&n);
   struct student s[n]; /*dynamic allocation of array*/

   for(i=0; i<n; i++)
{
   printf("\nEnter the name of student:");
   scanf("%s",s[i].name);
   srand((unsigned) time(&t));
   for(j=0;j<10;j++)
   s[i].score[j]=50+rand()%50;
}

/*qsort(s);*/

/* output sorted result*/
   printf("Name\t Subject1\t Subject2\t Subject3\t Subject4\t Subject5\t Subject6\t Subject7\t Subject8\t Subject9\t Subject10/t Total Score");
   for(i=0;i<n;i++)
{
   printf("\n \n%s\t",s[i].name);
   for(j=0;j<10;j++)
   printf("%d\t",s[i].score[j]);
   printf("%d\t",sum(&s[i]));
}

return 0;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Basically qsort means quick sort. Qsort uses the quicksort algorithm to sort the given array. so i m first giving the algorithm of quick sort and then i will give the algorithm of Qsort.

as in quicksort the main function is the partition function and the quicksort function. Thats why i m just writing these two for explaination.

CODE

/* This function takes last element as pivot, places

   the pivot element at its correct position in sorted

    array, and places all smaller (smaller than pivot)

   to left of pivot and all greater elements to right

   of pivot */

int partition (int arr[], int low, int high)

{

    int pivot = arr[high];    // pivot

    int i = (low - 1); // Index of smaller element

    for (int j = low; j <= high- 1; j++)

    {

        // If current element is smaller than or

        // equal to pivot

        if (arr[j] <= pivot)

        {

            i++;    // increment index of smaller element

            swap(&arr[i], &arr[j]);

        }

    }

    swap(&arr[i + 1], &arr[high]);

    return (i + 1);

}

/* The main function that implements QuickSort

arr[] --> Array to be sorted,

  low --> Starting index,

  high --> Ending index */

void quickSort(int arr[], int low, int high)

{

    if (low < high)

    {

        /* pi is partitioning index, arr[p] is now

           at right place */

        int pi = partition(arr, low, high);

        // Separately sort elements before

        // partition and after partition

        quickSort(arr, low, pi - 1);

        quickSort(arr, pi + 1, high);

    }

}

So basically the abve algorithm is used in Qsort but the most important part of Qsort is the Comparator function.

the prototype of Qsort() is:-

void qsort (void* base, size_t num, size_t size,

            int (*comparator)(const void*,const void*));

COMPARATOR FUNCTION:-

The comparator function takes two arguments and contains logic to decide their relative order in sorted output. The idea is to provide flexibility so that qsort() can be used for any type (including user defined types) and can be used to obtain any desired order (increasing, decreasing or any other).

CODE with the help of an example:-

For example, let there be an array of students where following is type of student.

struct Student

{

    int age, marks;

    char name[20];

};

Lets say we need to sort the students based on marks in descending order. The comparator function will look like:

int comparator(const void *p, const void *q)

{

    int l = ((struct Student *)p)->marks;

    int r = ((struct Student *)q)->marks;

    return (r - l);

}

Add a comment
Know the answer?
Add Answer to:
Hello, I am having trouble with a problem in my C language class. I am trying...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please I need help in C language, I am trying to modify the code per the...

    Please I need help in C language, I am trying to modify the code per the below instructions, but I am getting errors. Can't fgure it out. The attempted code modification and data file is privided below, after the instructions. Thank you. Instructions:                  1.      First, add a function named printMsg that displays a message, a greeting, or an introduction to the program for the user. Add a statement that calls that function from the main function when your program starts....

  • I am trying to add a string command to my code. what am i doing wrong?...

    I am trying to add a string command to my code. what am i doing wrong? #define _CRT_SECURE_NO_WARNINGS #define _USE_MATH_DEFINES #include <stdio.h> #include <string.h> #include <math.h> int main(void) {    int i, j;    int rowA, colA, rowB, colB;    int A[10][10], B[10][10];    int sum[10][10];    char str1[10];    printf("This is a matrix calculator\n");    //read in size from user MATRIX A    printf("Enter in matrix A....\n");    printf("\t#row = ");    scanf("%d", &rowA);    printf("\t#col = ");   ...

  • Create a C program to implement a grade book. Must follow these guidelines: 1. Use #define...

    Create a C program to implement a grade book. Must follow these guidelines: 1. Use #define to define MAX_SIZE1 as 20, and MAX_SIZE2 as 10 2. Use typedef to define the following struct type: struct { char name[MAX_SIZE1]; int scores[MAX_SIZE2]; } 3. The program accepts from the comand line an integer n (<= 30) as the number of students in the class. You may assume that the input will always be valid. 4. Dynamically allocate memory for an array of...

  • Rework this project to include a class. As explained in class, your project should have its...

    Rework this project to include a class. As explained in class, your project should have its functionalities moved to a class, and then create each course as an object to a class that inherits all the different functionalities of the class. You createclass function should be used as a constructor that takes in the name of the file containing the student list. (This way different objects are created with different class list files.) Here is the code I need you...

  • I am having problems with the following assignment. It is done in the c language. The...

    I am having problems with the following assignment. It is done in the c language. The code is not reading the a.txt file. The instructions are in the picture below and so is my code. It should read the a.txt file and print. The red car hit the blue car and name how many times those words appeared. Can i please get some help. Thank you. MY CODE: #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char *str; int...

  • I'm having trouble sorting this square matrix (a 2d array that has number of rows and...

    I'm having trouble sorting this square matrix (a 2d array that has number of rows and same number of column n x n) using row-wise approach in C programming. Please help me program this in C to sort it using row-wise approach, here is the code: #include <stdio.h> #define MAX 100 int main() { int mat[MAX][MAX]; int i, j, m, n; int rowsum, columnsum, diagonalsum; int k; int magic = 0; int transpose[MAX][MAX]; printf("Enter the # of rows and columns...

  • I am trying to figure out why my C code is outputting "exited, segmentation fault". The...

    I am trying to figure out why my C code is outputting "exited, segmentation fault". The game is supposed to generate 4 random numbers and store them in the "secret" array. Then the user is suppose to guess the secret code. The program also calculates the score of the user's guess. For now, I printed out the random secret code that has been generated, but when the game continues, it will output "exited, segmentation fault". Also, the GetSecretCode function has...

  • I am trying to write C programming code and output will be as below but I...

    I am trying to write C programming code and output will be as below but I donno how to get the result analysis part. help me to add the 2nd part with my code: here is my code below: #include <stdio.h> #define MAX 100 struct studentMarkVariable{ int id; float marks; }; void getData(struct studentMarkVariable arrs[]); void show(struct studentMarkVariable arrs[]); int main() { printf ("####### Marks Analyzer V3.0 ####### \n");       struct studentMarkVariable arrs[MAX];     getData(arrs);     show(arrs); return 0; }...

  • ​what's wrong with my code?????? #include <stdio.h> #include <stdlib.h> #include <string.h>                         &

    ​what's wrong with my code?????? #include <stdio.h> #include <stdlib.h> #include <string.h>                            #define MAXBINS 99 #define MAXCORS 26 #define MAXCUS 100 #define MAXPUR 10 /* datatype for a list of orders ----------------- */ typedef struct { int bin_order_number; char bin_order_char; }bin_order; typedef struct { int orderNo; bin_order orderbin; }order; typedef struct { int cusnumber; int n;   /* number of the orders what the txt include */ order oo[MAXPUR+1]; }customer; typedef struct{ int n; /*number of the customers */ customer cc[MAXCUS+1];...

  • C Programming Question Hi, I have the following code and in my submission I'm supposed to...

    C Programming Question Hi, I have the following code and in my submission I'm supposed to only include function definitions (i.e. implementations) in the file. However, I'm not NOT required to write the main, struct definitions and function prototypes. Could someone help me fix this code? Text Version: #include<stdio.h> #include<stdlib.h> #include <string.h> struct ip_address { int octet_1; int octet_2; int octet_3; int octet_4; }; typedef struct ip_address ip_address_t; void print_ip_address(ip_address_t ip1){ printf("%d.%d.%d.%d", ip1.octet_1,ip1.octet_2,ip1.octet_3,ip1.octet_4); } int is_valid(ip_address_t ip1){ if(ip1.octet_1 < 0...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT