luc081.c (1385B)
1 /* Create structure for Cricketers (Name, Age, Tests, Avg Runs). Sort 20 records by average runs using qsort(). 2 */ 3 /* Let Us C, Chap- 17 (Structures), Qn No.: B(d) */ 4 5 /* This file is auto-generated by a bot. */ 6 /* This code is not compiled; it is for reference only. */ 7 8 9 #include <stdio.h> 10 #include <string.h> 11 #include <stdlib.h> 12 13 struct cricketer 14 { 15 char name[30]; 16 int age; 17 int tests; 18 float avg_runs; 19 }; 20 21 // Comparator function for qsort 22 int compare(const void *a, const void *b) 23 { 24 struct cricketer *c1 = (struct cricketer *)a; 25 struct cricketer *c2 = (struct cricketer *)b; 26 27 if (c1->avg_runs > c2->avg_runs) return 1; 28 else if (c1->avg_runs < c2->avg_runs) return -1; 29 else return 0; 30 } 31 32 int main() 33 { 34 // Initializing fewer than 20 for demonstration, but logic applies to 20 35 struct cricketer team[5] = { 36 {"Kohli", 34, 110, 53.4}, 37 {"Smith", 33, 95, 59.8}, 38 {"Root", 32, 120, 50.1}, 39 {"Sharma", 35, 80, 45.5}, 40 {"Williamson", 32, 90, 54.0} 41 }; 42 int n = 5, i; 43 44 printf("Before Sorting:\n"); 45 for (i = 0; i < n; i++) 46 printf("%s: %.2f\n", team[i].name, team[i].avg_runs); 47 48 qsort(team, n, sizeof(struct cricketer), compare); 49 50 printf("\nAfter Sorting (Ascending Avg Runs):\n"); 51 for (i = 0; i < n; i++) 52 printf("%s: %.2f\n", team[i].name, team[i].avg_runs); 53 54 return 0; 55 }